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 __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel @require_tf class A__ : '''simple docstring''' snake_case__ = MBartConfig snake_case__ = {} snake_case__ = """gelu""" def __init__( self : Union[str, Any] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Dict=13 , _SCREAMING_SNAKE_CASE : Tuple=7 , _SCREAMING_SNAKE_CASE : int=True , _SCREAMING_SNAKE_CASE : Tuple=False , _SCREAMING_SNAKE_CASE : Dict=99 , _SCREAMING_SNAKE_CASE : int=32 , _SCREAMING_SNAKE_CASE : str=2 , _SCREAMING_SNAKE_CASE : Optional[int]=4 , _SCREAMING_SNAKE_CASE : Dict=37 , _SCREAMING_SNAKE_CASE : Tuple=0.1 , _SCREAMING_SNAKE_CASE : str=0.1 , _SCREAMING_SNAKE_CASE : Optional[int]=20 , _SCREAMING_SNAKE_CASE : Dict=2 , _SCREAMING_SNAKE_CASE : List[str]=1 , _SCREAMING_SNAKE_CASE : Any=0 , ): """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = seq_length UpperCamelCase = is_training UpperCamelCase = use_labels UpperCamelCase = vocab_size UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = intermediate_size UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = max_position_embeddings UpperCamelCase = eos_token_id UpperCamelCase = pad_token_id UpperCamelCase = bos_token_id def _SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" UpperCamelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) UpperCamelCase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) UpperCamelCase = tf.concat([input_ids, eos_tensor] , axis=1 ) UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) UpperCamelCase = prepare_mbart_inputs_dict(__a , __a , __a ) return config, inputs_dict def _SCREAMING_SNAKE_CASE ( self : List[str] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" UpperCamelCase = TFMBartModel(config=__a ).get_decoder() UpperCamelCase = inputs_dict['input_ids'] UpperCamelCase = input_ids[:1, :] UpperCamelCase = inputs_dict['attention_mask'][:1, :] UpperCamelCase = inputs_dict['head_mask'] UpperCamelCase = 1 # first forward pass UpperCamelCase = model(__a , attention_mask=__a , head_mask=__a , use_cache=__a ) UpperCamelCase , UpperCamelCase = outputs.to_tuple() UpperCamelCase = past_key_values[1] def lowercase__ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase=None , _UpperCamelCase=None , _UpperCamelCase=None , _UpperCamelCase=None , _UpperCamelCase=None , ) -> Optional[Any]: """simple docstring""" if attention_mask is None: UpperCamelCase = tf.cast(tf.math.not_equal(snake_case_ , config.pad_token_id) , tf.inta) if decoder_attention_mask is None: UpperCamelCase = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id) , tf.inta), ] , axis=-1 , ) if head_mask is None: UpperCamelCase = tf.ones((config.encoder_layers, config.encoder_attention_heads)) if decoder_head_mask is None: UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads)) if cross_attn_head_mask is None: UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads)) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class A__ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): '''simple docstring''' snake_case__ = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else () snake_case__ = (TFMBartForConditionalGeneration,) if is_tf_available() else () snake_case__ = ( { """conversational""": TFMBartForConditionalGeneration, """feature-extraction""": TFMBartModel, """summarization""": TFMBartForConditionalGeneration, """text2text-generation""": TFMBartForConditionalGeneration, """translation""": TFMBartForConditionalGeneration, } if is_tf_available() else {} ) snake_case__ = True snake_case__ = False snake_case__ = False def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" if pipeline_test_casse_name != "FeatureExtractionPipelineTests": # Exception encountered when calling layer '...' return True return False def _SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" UpperCamelCase = TFMBartModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=__a ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__a ) @require_sentencepiece @require_tokenizers @require_tf class A__ ( unittest.TestCase ): '''simple docstring''' snake_case__ = [ """ UN Chief Says There Is No Military Solution in Syria""", ] snake_case__ = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", ] snake_case__ = """facebook/mbart-large-en-ro""" @cached_property def _SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def _SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" UpperCamelCase = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def _SCREAMING_SNAKE_CASE ( self : Optional[int] , **_SCREAMING_SNAKE_CASE : Optional[int] ): """simple docstring""" UpperCamelCase = self.translate_src_text(**__a ) self.assertListEqual(self.expected_text , __a ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , **_SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" UpperCamelCase = self.tokenizer(self.src_text , **__a , return_tensors='tf' ) UpperCamelCase = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 ) UpperCamelCase = self.tokenizer.batch_decode(__a , skip_special_tokens=__a ) return generated_words @slow def _SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" self._assert_generated_batch_equal_expected()
280
'''simple docstring''' import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP SCREAMING_SNAKE_CASE_: Any =False try: SCREAMING_SNAKE_CASE_: Optional[Any] =_is_package_available('google.colab') except ModuleNotFoundError: pass @input.register class __A : def __init__(self : int , __a : str = None , __a : list = [] ): UpperCAmelCase_ = 0 UpperCAmelCase_ = choices UpperCAmelCase_ = prompt if sys.platform == "win32": UpperCAmelCase_ = "*" else: UpperCAmelCase_ = "➔ " def _lowercase (self : Union[str, Any] , __a : Optional[int] , __a : str = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 32 , __a ) else: forceWrite(self.choices[index] , __a ) def _lowercase (self : Any , __a : int ): if index == self.position: forceWrite(f""" {self.arrow_char} """ ) self.write_choice(__a ) else: forceWrite(f""" {self.choices[index]}""" ) reset_cursor() def _lowercase (self : Optional[Any] , __a : Direction , __a : int = 1 ): UpperCAmelCase_ = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(__a ) move_cursor(__a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP["up"] ) def _lowercase (self : Dict ): self.move_direction(Direction.UP ) @input.mark(KEYMAP["down"] ) def _lowercase (self : Any ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP["newline"] ) def _lowercase (self : Optional[Any] ): move_cursor(len(self.choices ) - self.position , "DOWN" ) return self.position @input.mark(KEYMAP["interrupt"] ) def _lowercase (self : str ): move_cursor(len(self.choices ) - self.position , "DOWN" ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(__a )] for number in range(10 )] ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = int(chr(self.current_selection ) ) UpperCAmelCase_ = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , __a ) else: return else: return def _lowercase (self : Optional[Any] , __a : int = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , "\n" ) if in_colab: forceWrite("Please input a choice index (starting from 0), and press enter" , "\n" ) else: forceWrite("Please select a choice using the arrow or number keys, and selecting with enter" , "\n" ) UpperCAmelCase_ = default_choice for i in range(len(self.choices ) ): self.print_choice(__a ) forceWrite("\n" ) move_cursor(len(self.choices ) - self.position , "UP" ) with cursor.hide(): while True: if in_colab: try: UpperCAmelCase_ = int(builtins.input() ) except ValueError: UpperCAmelCase_ = default_choice else: UpperCAmelCase_ = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , "UP" ) clear_line() self.write_choice(__a , "\n" ) return choice
78
0
from PIL import Image def _UpperCAmelCase ( UpperCAmelCase : Image ): """simple docstring""" __lowerCamelCase , __lowerCamelCase : Tuple = image.size __lowerCamelCase : Any = 0 __lowerCamelCase : Optional[int] = image.load() for i in range(snake_case_ ): for j in range(snake_case_ ): __lowerCamelCase : Optional[int] = pixels[j, i] mean += pixel mean //= width * height for j in range(snake_case_ ): for i in range(snake_case_ ): __lowerCamelCase : List[Any] = 255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": __UpperCamelCase : str = mean_threshold(Image.open('path_to_image').convert('L')) image.save('output_image_path')
519
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE_: Optional[int] ={'configuration_beit': ['BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BeitConfig', 'BeitOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[int] =['BeitFeatureExtractor'] SCREAMING_SNAKE_CASE_: int =['BeitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[int] =[ 'BEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BeitForImageClassification', 'BeitForMaskedImageModeling', 'BeitForSemanticSegmentation', 'BeitModel', 'BeitPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: int =[ 'FlaxBeitForImageClassification', 'FlaxBeitForMaskedImageModeling', 'FlaxBeitModel', 'FlaxBeitPreTrainedModel', ] if TYPE_CHECKING: from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_beit import BeitFeatureExtractor from .image_processing_beit import BeitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_beit import ( BEIT_PRETRAINED_MODEL_ARCHIVE_LIST, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, BeitPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_beit import ( FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel, FlaxBeitPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_: Dict =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
78
0
"""simple docstring""" from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging __SCREAMING_SNAKE_CASE : Optional[Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Dict = { 't5-small': 'https://huggingface.co/t5-small/resolve/main/config.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/config.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/config.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/config.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/config.json', } class lowerCamelCase_( UpperCamelCase__ ): '''simple docstring''' lowercase__ : List[Any] = """t5""" lowercase__ : List[str] = ["""past_key_values"""] lowercase__ : List[str] = {"""hidden_size""": """d_model""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""} def __init__( self , lowerCamelCase__=3_2_1_2_8 , lowerCamelCase__=5_1_2 , lowerCamelCase__=6_4 , lowerCamelCase__=2_0_4_8 , lowerCamelCase__=6 , lowerCamelCase__=None , lowerCamelCase__=8 , lowerCamelCase__=3_2 , lowerCamelCase__=1_2_8 , lowerCamelCase__=0.1 , lowerCamelCase__=1e-6 , lowerCamelCase__=1.0 , lowerCamelCase__="relu" , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=0 , lowerCamelCase__=1 , **lowerCamelCase__ , ): _lowerCamelCase = vocab_size _lowerCamelCase = d_model _lowerCamelCase = d_kv _lowerCamelCase = d_ff _lowerCamelCase = num_layers _lowerCamelCase = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry _lowerCamelCase = num_heads _lowerCamelCase = relative_attention_num_buckets _lowerCamelCase = relative_attention_max_distance _lowerCamelCase = dropout_rate _lowerCamelCase = layer_norm_epsilon _lowerCamelCase = initializer_factor _lowerCamelCase = feed_forward_proj _lowerCamelCase = use_cache _lowerCamelCase = self.feed_forward_proj.split('''-''' ) _lowerCamelCase = act_info[-1] _lowerCamelCase = act_info[0] == '''gated''' if len(__a ) > 1 and act_info[0] != "gated" or len(__a ) > 2: raise ValueError( F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" '''Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ''' '''\'gated-gelu\' or \'relu\'''' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": _lowerCamelCase = '''gelu_new''' super().__init__( pad_token_id=__a , eos_token_id=__a , is_encoder_decoder=__a , **__a , ) class lowerCamelCase_( UpperCamelCase__ ): '''simple docstring''' @property def snake_case__ ( self ): _lowerCamelCase = { '''input_ids''': {0: '''batch''', 1: '''encoder_sequence'''}, '''attention_mask''': {0: '''batch''', 1: '''encoder_sequence'''}, } if self.use_past: _lowerCamelCase = '''past_encoder_sequence + sequence''' _lowerCamelCase = {0: '''batch'''} _lowerCamelCase = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''} else: _lowerCamelCase = {0: '''batch''', 1: '''decoder_sequence'''} _lowerCamelCase = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(__a , direction='''inputs''' ) return common_inputs @property def snake_case__ ( self ): return 1_3
661
'''simple docstring''' import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed SCREAMING_SNAKE_CASE_: Any ={ 'distilbert': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), 'roberta': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), 'bert': (BertConfig, BertForMaskedLM, BertTokenizer), 'gpt2': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def lowerCAmelCase_ ( snake_case_ : Any ) -> str: '''simple docstring''' assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def lowerCAmelCase_ ( snake_case_ : Optional[Any] , snake_case_ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' if args.student_type == "roberta": UpperCAmelCase_ = False elif args.student_type == "gpt2": UpperCAmelCase_ = False def lowerCAmelCase_ ( snake_case_ : Optional[int] , snake_case_ : List[Any] ) -> Tuple: '''simple docstring''' if args.student_type == "roberta": UpperCAmelCase_ = False def lowerCAmelCase_ ( ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = argparse.ArgumentParser(description="Training" ) parser.add_argument("--force" , action="store_true" , help="Overwrite dump_path if it already exists." ) parser.add_argument( "--dump_path" , type=snake_case_ , required=snake_case_ , help="The output directory (log, checkpoints, parameters, etc.)" ) parser.add_argument( "--data_file" , type=snake_case_ , required=snake_case_ , help="The binarized file (tokenized + tokens_to_ids) and grouped by sequence." , ) parser.add_argument( "--student_type" , type=snake_case_ , choices=["distilbert", "roberta", "gpt2"] , required=snake_case_ , help="The student type (DistilBERT, RoBERTa)." , ) parser.add_argument("--student_config" , type=snake_case_ , required=snake_case_ , help="Path to the student configuration." ) parser.add_argument( "--student_pretrained_weights" , default=snake_case_ , type=snake_case_ , help="Load student initialization checkpoint." ) parser.add_argument( "--teacher_type" , choices=["bert", "roberta", "gpt2"] , required=snake_case_ , help="Teacher type (BERT, RoBERTa)." ) parser.add_argument("--teacher_name" , type=snake_case_ , required=snake_case_ , help="The teacher model." ) parser.add_argument("--temperature" , default=2.0 , type=snake_case_ , help="Temperature for the softmax temperature." ) parser.add_argument( "--alpha_ce" , default=0.5 , type=snake_case_ , help="Linear weight for the distillation loss. Must be >=0." ) parser.add_argument( "--alpha_mlm" , default=0.0 , type=snake_case_ , help="Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag." , ) parser.add_argument("--alpha_clm" , default=0.5 , type=snake_case_ , help="Linear weight for the CLM loss. Must be >=0." ) parser.add_argument("--alpha_mse" , default=0.0 , type=snake_case_ , help="Linear weight of the MSE loss. Must be >=0." ) parser.add_argument( "--alpha_cos" , default=0.0 , type=snake_case_ , help="Linear weight of the cosine embedding loss. Must be >=0." ) parser.add_argument( "--mlm" , action="store_true" , help="The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM." ) parser.add_argument( "--mlm_mask_prop" , default=0.15 , type=snake_case_ , help="Proportion of tokens for which we need to make a prediction." , ) parser.add_argument("--word_mask" , default=0.8 , type=snake_case_ , help="Proportion of tokens to mask out." ) parser.add_argument("--word_keep" , default=0.1 , type=snake_case_ , help="Proportion of tokens to keep." ) parser.add_argument("--word_rand" , default=0.1 , type=snake_case_ , help="Proportion of tokens to randomly replace." ) parser.add_argument( "--mlm_smoothing" , default=0.7 , type=snake_case_ , help="Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec)." , ) parser.add_argument("--token_counts" , type=snake_case_ , help="The token counts in the data_file for MLM." ) parser.add_argument( "--restrict_ce_to_mask" , action="store_true" , help="If true, compute the distillation loss only the [MLM] prediction distribution." , ) parser.add_argument( "--freeze_pos_embs" , action="store_true" , help="Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only." , ) parser.add_argument( "--freeze_token_type_embds" , action="store_true" , help="Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only." , ) parser.add_argument("--n_epoch" , type=snake_case_ , default=3 , help="Number of pass on the whole dataset." ) parser.add_argument("--batch_size" , type=snake_case_ , default=5 , help="Batch size (for each process)." ) parser.add_argument( "--group_by_size" , action="store_false" , help="If true, group sequences that have similar length into the same batch. Default is true." , ) parser.add_argument( "--gradient_accumulation_steps" , type=snake_case_ , default=50 , help="Gradient accumulation for larger training batches." , ) parser.add_argument("--warmup_prop" , default=0.05 , type=snake_case_ , help="Linear warmup proportion." ) parser.add_argument("--weight_decay" , default=0.0 , type=snake_case_ , help="Weight decay if we apply some." ) parser.add_argument("--learning_rate" , default=5E-4 , type=snake_case_ , help="The initial learning rate for Adam." ) parser.add_argument("--adam_epsilon" , default=1E-6 , type=snake_case_ , help="Epsilon for Adam optimizer." ) parser.add_argument("--max_grad_norm" , default=5.0 , type=snake_case_ , help="Max gradient norm." ) parser.add_argument("--initializer_range" , default=0.02 , type=snake_case_ , help="Random initialization range." ) parser.add_argument( "--fp16" , action="store_true" , help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit" , ) parser.add_argument( "--fp16_opt_level" , type=snake_case_ , default="O1" , help=( "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html" ) , ) parser.add_argument("--n_gpu" , type=snake_case_ , default=1 , help="Number of GPUs in the node." ) parser.add_argument("--local_rank" , type=snake_case_ , default=-1 , help="Distributed training - Local rank" ) parser.add_argument("--seed" , type=snake_case_ , default=56 , help="Random seed" ) parser.add_argument("--log_interval" , type=snake_case_ , default=5_00 , help="Tensorboard logging interval." ) parser.add_argument("--checkpoint_interval" , type=snake_case_ , default=40_00 , help="Checkpoint interval." ) UpperCAmelCase_ = parser.parse_args() sanity_checks(snake_case_ ) # ARGS # init_gpu_params(snake_case_ ) set_seed(snake_case_ ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f"""Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite""" " itUse `--force` if you want to overwrite it" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f"""Experiment will be dumped and logged in {args.dump_path}""" ) # SAVE PARAMS # logger.info(f"""Param: {args}""" ) with open(os.path.join(args.dump_path , "parameters.json" ) , "w" ) as f: json.dump(vars(snake_case_ ) , snake_case_ , indent=4 ) git_log(args.dump_path ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = MODEL_CLASSES[args.student_type] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = MODEL_CLASSES[args.teacher_type] # TOKENIZER # UpperCAmelCase_ = teacher_tokenizer_class.from_pretrained(args.teacher_name ) UpperCAmelCase_ = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): UpperCAmelCase_ = tokenizer.all_special_tokens.index(snake_case_ ) UpperCAmelCase_ = tokenizer.all_special_ids[idx] logger.info(f"""Special tokens {special_tok_ids}""" ) UpperCAmelCase_ = special_tok_ids UpperCAmelCase_ = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f"""Loading data from {args.data_file}""" ) with open(args.data_file , "rb" ) as fp: UpperCAmelCase_ = pickle.load(snake_case_ ) if args.mlm: logger.info(f"""Loading token counts from {args.token_counts} (already pre-computed)""" ) with open(args.token_counts , "rb" ) as fp: UpperCAmelCase_ = pickle.load(snake_case_ ) UpperCAmelCase_ = np.maximum(snake_case_ , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): UpperCAmelCase_ = 0.0 # do not predict special tokens UpperCAmelCase_ = torch.from_numpy(snake_case_ ) else: UpperCAmelCase_ = None UpperCAmelCase_ = LmSeqsDataset(params=snake_case_ , data=snake_case_ ) logger.info("Data loader created." ) # STUDENT # logger.info(f"""Loading student config from {args.student_config}""" ) UpperCAmelCase_ = student_config_class.from_pretrained(args.student_config ) UpperCAmelCase_ = True if args.student_pretrained_weights is not None: logger.info(f"""Loading pretrained weights from {args.student_pretrained_weights}""" ) UpperCAmelCase_ = student_model_class.from_pretrained(args.student_pretrained_weights , config=snake_case_ ) else: UpperCAmelCase_ = student_model_class(snake_case_ ) if args.n_gpu > 0: student.to(f"""cuda:{args.local_rank}""" ) logger.info("Student loaded." ) # TEACHER # UpperCAmelCase_ = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=snake_case_ ) if args.n_gpu > 0: teacher.to(f"""cuda:{args.local_rank}""" ) logger.info(f"""Teacher loaded from {args.teacher_name}.""" ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(snake_case_ , snake_case_ ) if args.freeze_token_type_embds: freeze_token_type_embeddings(snake_case_ , snake_case_ ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() UpperCAmelCase_ = Distiller( params=snake_case_ , dataset=snake_case_ , token_probs=snake_case_ , student=snake_case_ , teacher=snake_case_ ) distiller.train() logger.info("Let's go get some drinks." ) if __name__ == "__main__": main()
78
0
def __lowerCAmelCase ( A_ : int ) -> int: if not isinstance(snake_case_ , snake_case_ ): __UpperCAmelCase = F'''Input value of [number={number}] must be an integer''' raise TypeError(snake_case_ ) if number < 1: __UpperCAmelCase = F'''Input value of [number={number}] must be > 0''' raise ValueError(snake_case_ ) __UpperCAmelCase = 1 for i in range(1 , snake_case_ ): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
221
'''simple docstring''' import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __A ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): a__ : int = AutoencoderKL a__ : Optional[Any] = """sample""" a__ : Union[str, Any] = 1e-2 @property def _lowercase (self : Optional[int] ): UpperCAmelCase_ = 4 UpperCAmelCase_ = 3 UpperCAmelCase_ = (32, 32) UpperCAmelCase_ = floats_tensor((batch_size, num_channels) + sizes ).to(__a ) return {"sample": image} @property def _lowercase (self : Any ): return (3, 32, 32) @property def _lowercase (self : Dict ): return (3, 32, 32) def _lowercase (self : int ): UpperCAmelCase_ = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } UpperCAmelCase_ = self.dummy_input return init_dict, inputs_dict def _lowercase (self : int ): pass def _lowercase (self : int ): pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def _lowercase (self : List[Any] ): # enable deterministic behavior for gradient checkpointing UpperCAmelCase_ , UpperCAmelCase_ = self.prepare_init_args_and_inputs_for_common() UpperCAmelCase_ = self.model_class(**__a ) model.to(__a ) assert not model.is_gradient_checkpointing and model.training UpperCAmelCase_ = model(**__a ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() UpperCAmelCase_ = torch.randn_like(__a ) UpperCAmelCase_ = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing UpperCAmelCase_ = self.model_class(**__a ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(__a ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training UpperCAmelCase_ = model_a(**__a ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() UpperCAmelCase_ = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) UpperCAmelCase_ = dict(model.named_parameters() ) UpperCAmelCase_ = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def _lowercase (self : Any ): UpperCAmelCase_ , UpperCAmelCase_ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=__a ) self.assertIsNotNone(__a ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(__a ) UpperCAmelCase_ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def _lowercase (self : List[str] ): UpperCAmelCase_ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) UpperCAmelCase_ = model.to(__a ) model.eval() if torch_device == "mps": UpperCAmelCase_ = torch.manual_seed(0 ) else: UpperCAmelCase_ = torch.Generator(device=__a ).manual_seed(0 ) UpperCAmelCase_ = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) UpperCAmelCase_ = image.to(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , sample_posterior=__a , generator=__a ).sample UpperCAmelCase_ = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": UpperCAmelCase_ = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": UpperCAmelCase_ = torch.tensor( [-0.13_52, 0.08_78, 0.04_19, -0.08_18, -0.10_69, 0.06_88, -0.14_58, -0.44_46, -0.00_26] ) else: UpperCAmelCase_ = torch.tensor( [-0.24_21, 0.46_42, 0.25_07, -0.04_38, 0.06_82, 0.31_60, -0.20_18, -0.07_27, 0.24_85] ) self.assertTrue(torch_all_close(__a , __a , rtol=1E-2 ) ) @slow class __A ( unittest.TestCase ): def _lowercase (self : Dict , __a : Dict , __a : int ): return f"""gaussian_noise_s={seed}_shape={"_".join([str(__a ) for s in shape] )}.npy""" def _lowercase (self : str ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self : Optional[Any] , __a : Optional[Any]=0 , __a : str=(4, 3, 512, 512) , __a : List[str]=False ): UpperCAmelCase_ = torch.floataa if fpaa else torch.floataa UpperCAmelCase_ = torch.from_numpy(load_hf_numpy(self.get_file_format(__a , __a ) ) ).to(__a ).to(__a ) return image def _lowercase (self : List[Any] , __a : Union[str, Any]="CompVis/stable-diffusion-v1-4" , __a : List[Any]=False ): UpperCAmelCase_ = "fp16" if fpaa else None UpperCAmelCase_ = torch.floataa if fpaa else torch.floataa UpperCAmelCase_ = AutoencoderKL.from_pretrained( __a , subfolder="vae" , torch_dtype=__a , revision=__a , ) model.to(__a ).eval() return model def _lowercase (self : List[Any] , __a : List[Any]=0 ): if torch_device == "mps": return torch.manual_seed(__a ) return torch.Generator(device=__a ).manual_seed(__a ) @parameterized.expand( [ # fmt: off [33, [-0.16_03, 0.98_78, -0.04_95, -0.07_90, -0.27_09, 0.83_75, -0.20_60, -0.08_24], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_76, 0.11_68, 0.13_32, -0.48_40, -0.25_08, -0.07_91, -0.04_93, -0.40_89], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def _lowercase (self : List[Any] , __a : Dict , __a : Optional[int] , __a : List[str] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , generator=__a , sample_posterior=__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, -2:, :2].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(__a , __a , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.05_13, 0.02_89, 1.37_99, 0.21_66, -0.25_73, -0.08_71, 0.51_03, -0.09_99]], [47, [-0.41_28, -0.13_20, -0.37_04, 0.19_65, -0.41_16, -0.23_32, -0.33_40, 0.22_47]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : Dict , __a : Optional[int] , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , fpaa=__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , generator=__a , sample_posterior=__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.16_09, 0.98_66, -0.04_87, -0.07_77, -0.27_16, 0.83_68, -0.20_55, -0.08_14], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_77, 0.11_47, 0.13_33, -0.48_41, -0.25_06, -0.08_05, -0.04_91, -0.40_85], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def _lowercase (self : str , __a : int , __a : Union[str, Any] , __a : List[Any] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, -2:, :2].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(__a , __a , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.20_51, -0.18_03, -0.23_11, -0.21_14, -0.32_92, -0.35_74, -0.29_53, -0.33_23]], [37, [-0.26_32, -0.26_25, -0.21_99, -0.27_41, -0.45_39, -0.49_90, -0.37_20, -0.49_25]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : int , __a : int , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.03_69, 0.02_07, -0.07_76, -0.06_82, -0.17_47, -0.19_30, -0.14_65, -0.20_39]], [16, [-0.16_28, -0.21_34, -0.27_47, -0.26_42, -0.37_74, -0.44_04, -0.36_87, -0.42_77]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : Union[str, Any] , __a : List[str] , __a : Optional[Any] ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) , fpaa=__a ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , atol=5E-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def _lowercase (self : List[str] , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) , fpaa=__a ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__a , __a , atol=1E-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def _lowercase (self : Union[str, Any] , __a : Dict ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__a , __a , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.30_01, 0.09_18, -2.69_84, -3.97_20, -3.20_99, -5.03_53, 1.73_38, -0.20_65, 3.42_67]], [47, [-1.50_30, -4.38_71, -6.03_55, -9.11_57, -1.66_61, -2.78_53, 2.16_07, -5.08_23, 2.56_33]], # fmt: on ] ) def _lowercase (self : Tuple , __a : List[Any] , __a : List[Any] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model.encode(__a ).latent_dist UpperCAmelCase_ = dist.sample(generator=__a ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] UpperCAmelCase_ = sample[0, -1, -3:, -3:].flatten().cpu() UpperCAmelCase_ = torch.tensor(__a ) UpperCAmelCase_ = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(__a , __a , atol=__a )
78
0
"""simple docstring""" from __future__ import annotations def lowercase_ ( __UpperCAmelCase ) -> float: if not nums: raise ValueError("""List is empty""" ) return sum(snake_case_ ) / len(snake_case_ ) if __name__ == "__main__": import doctest doctest.testmod()
299
'''simple docstring''' import logging from transformers import PretrainedConfig SCREAMING_SNAKE_CASE_: Any =logging.getLogger(__name__) SCREAMING_SNAKE_CASE_: Any ={ 'bertabs-finetuned-cnndm': 'https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json', } class __A ( UpperCamelCase__ ): a__ : List[Any] = """bertabs""" def __init__(self : Any , __a : int=30522 , __a : Tuple=512 , __a : Tuple=6 , __a : Dict=512 , __a : int=8 , __a : List[Any]=512 , __a : List[str]=0.2 , __a : List[Any]=6 , __a : int=768 , __a : Any=8 , __a : Dict=2048 , __a : Tuple=0.2 , **__a : Optional[int] , ): super().__init__(**__a ) UpperCAmelCase_ = vocab_size UpperCAmelCase_ = max_pos UpperCAmelCase_ = enc_layers UpperCAmelCase_ = enc_hidden_size UpperCAmelCase_ = enc_heads UpperCAmelCase_ = enc_ff_size UpperCAmelCase_ = enc_dropout UpperCAmelCase_ = dec_layers UpperCAmelCase_ = dec_hidden_size UpperCAmelCase_ = dec_heads UpperCAmelCase_ = dec_ff_size UpperCAmelCase_ = dec_dropout
78
0
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer SCREAMING_SNAKE_CASE :Union[str, Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :str = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} SCREAMING_SNAKE_CASE :str = { 'vocab_file': { 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt' ), 'facebook/dpr-ctx_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json' ), 'facebook/dpr-ctx_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json' ), }, } SCREAMING_SNAKE_CASE :List[Any] = { 'vocab_file': { 'facebook/dpr-question_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt' ), 'facebook/dpr-question_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'facebook/dpr-question_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json' ), 'facebook/dpr-question_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json' ), }, } SCREAMING_SNAKE_CASE :Optional[int] = { 'vocab_file': { 'facebook/dpr-reader-single-nq-base': ( 'https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt' ), 'facebook/dpr-reader-multiset-base': ( 'https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'facebook/dpr-reader-single-nq-base': ( 'https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json' ), 'facebook/dpr-reader-multiset-base': ( 'https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json' ), }, } SCREAMING_SNAKE_CASE :Optional[Any] = { 'facebook/dpr-ctx_encoder-single-nq-base': 5_12, 'facebook/dpr-ctx_encoder-multiset-base': 5_12, } SCREAMING_SNAKE_CASE :Optional[Any] = { 'facebook/dpr-question_encoder-single-nq-base': 5_12, 'facebook/dpr-question_encoder-multiset-base': 5_12, } SCREAMING_SNAKE_CASE :int = { 'facebook/dpr-reader-single-nq-base': 5_12, 'facebook/dpr-reader-multiset-base': 5_12, } SCREAMING_SNAKE_CASE :Optional[Any] = { 'facebook/dpr-ctx_encoder-single-nq-base': {'do_lower_case': True}, 'facebook/dpr-ctx_encoder-multiset-base': {'do_lower_case': True}, } SCREAMING_SNAKE_CASE :Any = { 'facebook/dpr-question_encoder-single-nq-base': {'do_lower_case': True}, 'facebook/dpr-question_encoder-multiset-base': {'do_lower_case': True}, } SCREAMING_SNAKE_CASE :List[Any] = { 'facebook/dpr-reader-single-nq-base': {'do_lower_case': True}, 'facebook/dpr-reader-multiset-base': {'do_lower_case': True}, } class __lowerCAmelCase ( UpperCamelCase__ ): """simple docstring""" _SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION _SCREAMING_SNAKE_CASE = DPRContextEncoderTokenizer class __lowerCAmelCase ( UpperCamelCase__ ): """simple docstring""" _SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION _SCREAMING_SNAKE_CASE = DPRQuestionEncoderTokenizer SCREAMING_SNAKE_CASE :Union[str, Any] = collections.namedtuple( '''DPRSpanPrediction''', ['''span_score''', '''relevance_score''', '''doc_id''', '''start_index''', '''end_index''', '''text'''] ) SCREAMING_SNAKE_CASE :List[Any] = collections.namedtuple('''DPRReaderOutput''', ['''start_logits''', '''end_logits''', '''relevance_logits''']) SCREAMING_SNAKE_CASE :str = r'\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `\'tf\'`: Return TensorFlow `tf.constant` objects.\n - `\'pt\'`: Return PyTorch `torch.Tensor` objects.\n - `\'np\'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer\'s default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Return:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n ' @add_start_docstrings(UpperCamelCase__ ) class __lowerCAmelCase : """simple docstring""" def __call__( self : Dict , _lowerCAmelCase : Any , _lowerCAmelCase : Optional[str] = None , _lowerCAmelCase : Optional[str] = None , _lowerCAmelCase : Union[bool, str] = False , _lowerCAmelCase : Union[bool, str] = False , _lowerCAmelCase : Optional[int] = None , _lowerCAmelCase : Optional[Union[str, TensorType]] = None , _lowerCAmelCase : Optional[bool] = None , **_lowerCAmelCase : List[str] , ) -> Optional[int]: """simple docstring""" if titles is None and texts is None: return super().__call__( __a , padding=__a , truncation=__a , max_length=__a , return_tensors=__a , return_attention_mask=__a , **__a , ) elif titles is None or texts is None: snake_case_ = titles if texts is None else texts return super().__call__( __a , __a , padding=__a , truncation=__a , max_length=__a , return_tensors=__a , return_attention_mask=__a , **__a , ) snake_case_ = titles if not isinstance(__a , __a ) else [titles] snake_case_ = texts if not isinstance(__a , __a ) else [texts] snake_case_ = len(__a ) snake_case_ = questions if not isinstance(__a , __a ) else [questions] * n_passages assert len(__a ) == len( __a ), F'''There should be as many titles than texts but got {len(__a )} titles and {len(__a )} texts.''' snake_case_ = super().__call__(__a , __a , padding=__a , truncation=__a )["input_ids"] snake_case_ = super().__call__(__a , add_special_tokens=__a , padding=__a , truncation=__a )["input_ids"] snake_case_ = { "input_ids": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(__a , __a ) ] } if return_attention_mask is not False: snake_case_ = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) snake_case_ = attention_mask return self.pad(__a , padding=__a , max_length=__a , return_tensors=__a ) def lowerCAmelCase__ ( self : List[Any] , _lowerCAmelCase : BatchEncoding , _lowerCAmelCase : DPRReaderOutput , _lowerCAmelCase : int = 1_6 , _lowerCAmelCase : int = 6_4 , _lowerCAmelCase : int = 4 , ) -> Optional[int]: """simple docstring""" snake_case_ = reader_input["input_ids"] snake_case_ , snake_case_ , snake_case_ = reader_output[:3] snake_case_ = len(__a ) snake_case_ = sorted(range(__a ) , reverse=__a , key=relevance_logits.__getitem__ ) snake_case_ = [] for doc_id in sorted_docs: snake_case_ = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence snake_case_ = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: snake_case_ = sequence_ids.index(self.pad_token_id ) else: snake_case_ = len(__a ) snake_case_ = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=__a , top_spans=__a , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=__a , start_index=__a , end_index=__a , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(__a ) >= num_spans: break return nbest_spans_predictions[:num_spans] def lowerCAmelCase__ ( self : Any , _lowerCAmelCase : List[int] , _lowerCAmelCase : List[int] , _lowerCAmelCase : int , _lowerCAmelCase : int , ) -> int: """simple docstring""" snake_case_ = [] for start_index, start_score in enumerate(__a ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) snake_case_ = sorted(__a , key=lambda _lowerCAmelCase : x[1] , reverse=__a ) snake_case_ = [] for (start_index, end_index), score in scores: assert start_index <= end_index, F'''Wrong span indices: [{start_index}:{end_index}]''' snake_case_ = end_index - start_index + 1 assert length <= max_answer_length, F'''Span is too long: {length} > {max_answer_length}''' if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(__a ) == top_spans: break return chosen_span_intervals @add_end_docstrings(UpperCamelCase__ ) class __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" _SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE = READER_PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE = READER_PRETRAINED_INIT_CONFIGURATION _SCREAMING_SNAKE_CASE = ["""input_ids""", """attention_mask"""] _SCREAMING_SNAKE_CASE = DPRReaderTokenizer
283
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE_: Tuple =logging.get_logger(__name__) def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> int: '''simple docstring''' UpperCAmelCase_ = "huggingface/label-files" UpperCAmelCase_ = "imagenet-1k-id2label.json" UpperCAmelCase_ = json.load(open(hf_hub_download(snake_case_ , snake_case_ , repo_type="dataset" ) , "r" ) ) UpperCAmelCase_ = {int(snake_case_ ): v for k, v in idalabel.items()} UpperCAmelCase_ = {v: k for k, v in idalabel.items()} UpperCAmelCase_ = "std_conv" if "bit" in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" UpperCAmelCase_ = BitConfig( conv_layer=snake_case_ , num_labels=10_00 , idalabel=snake_case_ , labelaid=snake_case_ , ) return config def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' if "stem.conv" in name: UpperCAmelCase_ = name.replace("stem.conv" , "bit.embedder.convolution" ) if "blocks" in name: UpperCAmelCase_ = name.replace("blocks" , "layers" ) if "head.fc" in name: UpperCAmelCase_ = name.replace("head.fc" , "classifier.1" ) if name.startswith("norm" ): UpperCAmelCase_ = "bit." + name if "bit" not in name and "classifier" not in name: UpperCAmelCase_ = "bit.encoder." + name return name def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = "http://images.cocodataset.org/val2017/000000039769.jpg" UpperCAmelCase_ = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : Tuple , snake_case_ : Optional[Any] , snake_case_ : int=False ) -> List[Any]: '''simple docstring''' UpperCAmelCase_ = get_config(snake_case_ ) # load original model from timm UpperCAmelCase_ = create_model(snake_case_ , pretrained=snake_case_ ) timm_model.eval() # load state_dict of original model UpperCAmelCase_ = timm_model.state_dict() for key in state_dict.copy().keys(): UpperCAmelCase_ = state_dict.pop(snake_case_ ) UpperCAmelCase_ = val.squeeze() if "head" in key else val # load HuggingFace model UpperCAmelCase_ = BitForImageClassification(snake_case_ ) model.eval() model.load_state_dict(snake_case_ ) # create image processor UpperCAmelCase_ = create_transform(**resolve_data_config({} , model=snake_case_ ) ) UpperCAmelCase_ = transform.transforms UpperCAmelCase_ = { "bilinear": PILImageResampling.BILINEAR, "bicubic": PILImageResampling.BICUBIC, "nearest": PILImageResampling.NEAREST, } UpperCAmelCase_ = BitImageProcessor( do_resize=snake_case_ , size={"shortest_edge": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=snake_case_ , crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]} , do_normalize=snake_case_ , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = transform(snake_case_ ).unsqueeze(0 ) UpperCAmelCase_ = processor(snake_case_ , return_tensors="pt" ).pixel_values # verify pixel values assert torch.allclose(snake_case_ , snake_case_ ) # verify logits with torch.no_grad(): UpperCAmelCase_ = model(snake_case_ ) UpperCAmelCase_ = outputs.logits print("Logits:" , logits[0, :3] ) print("Predicted class:" , model.config.idalabel[logits.argmax(-1 ).item()] ) UpperCAmelCase_ = timm_model(snake_case_ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(snake_case_ , outputs.logits , atol=1E-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) print(f"""Saving model {model_name} and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(snake_case_ ) processor.save_pretrained(snake_case_ ) if push_to_hub: print(f"""Pushing model {model_name} and processor to the hub""" ) model.push_to_hub(f"""ybelkada/{model_name}""" ) processor.push_to_hub(f"""ybelkada/{model_name}""" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: int =argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='resnetv2_50x1_bitm', type=str, help='Name of the BiT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model to the hub.', ) SCREAMING_SNAKE_CASE_: Union[str, Any] =parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
78
0
"""simple docstring""" from pathlib import Path import fire def A_ ( snake_case__ , snake_case__ , snake_case__ ) -> int: _UpperCamelCase :Union[str, Any] = Path(snake_case_ ) _UpperCamelCase :str = Path(snake_case_ ) dest_dir.mkdir(exist_ok=snake_case_ ) for path in src_dir.iterdir(): _UpperCamelCase :Tuple = [x.rstrip() for x in list(path.open().readlines() )][:n] _UpperCamelCase :Tuple = dest_dir.joinpath(path.name ) print(snake_case_ ) dest_path.open('''w''' ).write('''\n'''.join(snake_case_ ) ) if __name__ == "__main__": fire.Fire(minify)
355
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class __A ( unittest.TestCase ): def _lowercase (self : List[str] ): UpperCAmelCase_ = 0 def _lowercase (self : Tuple ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("openai/clip-vit-base-patch32" ) self.assertIsInstance(__a , __a ) def _lowercase (self : str ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : Dict ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : List[str] ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = CLIPConfig() # Create a dummy config file with image_proceesor_type UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ).to_dict() config_dict.pop("image_processor_type" ) UpperCAmelCase_ = CLIPImageProcessor(**__a ) # save in new folder model_config.save_pretrained(__a ) config.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) # make sure private variable is not incorrectly saved UpperCAmelCase_ = json.loads(config.to_json_string() ) self.assertTrue("_processor_class" not in dict_as_saved ) self.assertIsInstance(__a , __a ) def _lowercase (self : int ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : Tuple ): with self.assertRaisesRegex( __a , "clip-base is not a local folder and is not a valid model identifier" ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("clip-base" ) def _lowercase (self : Optional[int] ): with self.assertRaisesRegex( __a , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a , revision="aaaaaa" ) def _lowercase (self : Union[str, Any] ): with self.assertRaisesRegex( __a , "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json." , ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/config-no-model" ) def _lowercase (self : List[Any] ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(__a ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" ) # If remote code is disabled, we can't load this config. with self.assertRaises(__a ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a , trust_remote_code=__a ) self.assertEqual(reloaded_image_processor.__class__.__name__ , "NewImageProcessor" ) def _lowercase (self : Optional[int] ): try: AutoConfig.register("custom" , __a ) AutoImageProcessor.register(__a , __a ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__a ): AutoImageProcessor.register(__a , __a ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = CustomImageProcessor.from_pretrained(__a ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def _lowercase (self : Optional[int] ): class __A ( UpperCamelCase__ ): a__ : str = True try: AutoConfig.register("custom" , __a ) AutoImageProcessor.register(__a , __a ) # If remote code is not set, the default is to use local UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(not hasattr(__a , "is_local" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
78
0
'''simple docstring''' import unittest from transformers import GPTSwaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin __SCREAMING_SNAKE_CASE : Any =get_tests_dir('fixtures/test_sentencepiece_with_bytefallback.model') @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" A__ : int = GPTSwaTokenizer A__ : Optional[Any] = False A__ : str = True A__ : Optional[int] = False def a__ ( self ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing A: Dict = GPTSwaTokenizer(__a , eos_token="""<unk>""" , bos_token="""<unk>""" , pad_token="""<unk>""" ) tokenizer.save_pretrained(self.tmpdirname ) def a__ ( self , A ) -> Optional[int]: A: Tuple = """This is a test""" A: Optional[int] = """This is a test""" return input_text, output_text def a__ ( self ) -> Dict: A: List[str] = """<s>""" A: Optional[Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a ) , __a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a ) , __a ) def a__ ( self ) -> str: A: Tuple = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<unk>""" ) self.assertEqual(vocab_keys[1] , """<s>""" ) self.assertEqual(vocab_keys[-1] , """j""" ) self.assertEqual(len(__a ) , 20_00 ) def a__ ( self ) -> Optional[Any]: self.assertEqual(self.get_tokenizer().vocab_size , 20_00 ) def a__ ( self ) -> Dict: A: List[Any] = GPTSwaTokenizer(__a ) A: Dict = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__a , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [4_65, 2_87, 2_65, 6_31, 8_42] ) A: str = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) # fmt: off self.assertListEqual( __a , ["""▁I""", """▁was""", """▁bor""", """n""", """▁in""", """▁""", """<0x39>""", """2""", """0""", """0""", """0""", """,""", """▁and""", """▁this""", """▁is""", """▁f""", """al""", """s""", """<0xC3>""", """<0xA9>""", """."""] , ) # fmt: on A: List[str] = tokenizer.convert_tokens_to_ids(__a ) self.assertListEqual( __a , [2_62, 2_72, 15_25, 2_86, 2_71, 2_68, 60, 9_16, 6_33, 6_33, 6_33, 2_59, 2_66, 3_01, 2_87, 3_84, 3_67, 2_63, 1_98, 1_72, 2_60] , ) A: List[str] = tokenizer.convert_ids_to_tokens(__a ) # fmt: off self.assertListEqual( __a , ["""▁I""", """▁was""", """▁bor""", """n""", """▁in""", """▁""", """<0x39>""", """2""", """0""", """0""", """0""", """,""", """▁and""", """▁this""", """▁is""", """▁f""", """al""", """s""", """<0xC3>""", """<0xA9>""", """."""] ) # fmt: on def a__ ( self ) -> Union[str, Any]: A: List[Any] = GPTSwaTokenizer(__a ) A: Optional[Any] = ["""This is a test""", """I was born in 92000, and this is falsé."""] A: str = [ [4_65, 2_87, 2_65, 6_31, 8_42], [2_62, 2_72, 15_25, 2_86, 2_71, 2_68, 60, 9_16, 6_33, 6_33, 6_33, 2_59, 2_66, 3_01, 2_87, 3_84, 3_67, 2_63, 1_98, 1_72, 2_60], ] # Test that encode_fast returns the same as tokenize + convert_tokens_to_ids for text, expected_ids in zip(__a , __a ): self.assertListEqual(tokenizer.encode_fast(__a ) , __a ) # Test that decode_fast returns the input text for text, token_ids in zip(__a , __a ): self.assertEqual(tokenizer.decode_fast(__a ) , __a ) @slow def a__ ( self ) -> int: A: Union[str, Any] = [ """<|python|>def fibonacci(n)\n if n < 0:\n print('Incorrect input')""", """Hey there, how are you doing this fine day?""", """This is a text with a trailing spaces followed by a dot .""", """Häj sväjs lillebrör! =)""", """Det är inget fel på Mr. Cool""", ] # fmt: off A: Dict = {"""input_ids""": [[6_34_23, 5, 68_11, 1_49_54, 2_82, 8_16, 38_21, 6_34_66, 6_34_25, 6_34_62, 18, 6_39_78, 6_78, 3_01, 13_20, 6_34_23, 6_34_55, 6_34_58, 18, 6_39_82, 42_46, 39_40, 19_01, 4_77_89, 55_47, 1_89_94], [1_96_30, 11_00, 6_34_46, 13_42, 6_33, 5_44, 44_88, 5_93, 51_02, 24_16, 6_34_95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [16_52, 4_28, 2_68, 19_36, 5_15, 2_68, 5_85_93, 2_24_13, 91_06, 5_46, 2_68, 3_32_13, 6_39_79, 6_98, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [5_51_30, 6_34_50, 9_24, 6_34_49, 22_49, 40_62, 15_58, 3_18, 6_35_04, 2_14_98, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [5_09, 3_77, 28_27, 25_59, 3_32, 65_75, 6_34_43, 2_68_01, 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]], """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, 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, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [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], [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]]} # fmt: on self.tokenizer_integration_test_util( expected_encoding=__a , model_name="""AI-Sweden/gpt-sw3-126m""" , sequences=__a , )
135
'''simple docstring''' import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..utils.py_utils import no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: from .features import FeatureType SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_: Tuple =False, False, False @dataclass class __A : a__ : Optional[int] = None a__ : bool = True a__ : bool = True a__ : Optional[str] = None # Automatically constructed a__ : ClassVar[str] = "dict" a__ : ClassVar[Any] = pa.struct({"""bytes""": pa.binary(), """path""": pa.string()} ) a__ : str = field(default="""Audio""" , init=UpperCamelCase__ , repr=UpperCamelCase__ ) def __call__(self : Optional[Any] ): return self.pa_type def _lowercase (self : str , __a : Union[str, bytes, dict] ): try: import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files. except ImportError as err: raise ImportError("To support encoding audio data, please install 'soundfile'." ) from err if isinstance(__a , __a ): return {"bytes": None, "path": value} elif isinstance(__a , __a ): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes UpperCAmelCase_ = BytesIO() sf.write(__a , value["array"] , value["sampling_rate"] , format="wav" ) return {"bytes": buffer.getvalue(), "path": None} elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally if value["path"].endswith("pcm" ): # "PCM" only has raw audio bytes if value.get("sampling_rate" ) is None: # At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate raise KeyError("To use PCM files, please specify a 'sampling_rate' in Audio object" ) if value.get("bytes" ): # If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!) UpperCAmelCase_ = np.frombuffer(value["bytes"] , dtype=np.intaa ).astype(np.floataa ) / 32767 else: UpperCAmelCase_ = np.memmap(value["path"] , dtype="h" , mode="r" ).astype(np.floataa ) / 32767 UpperCAmelCase_ = BytesIO(bytes() ) sf.write(__a , __a , value["sampling_rate"] , format="wav" ) return {"bytes": buffer.getvalue(), "path": None} else: return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the audio bytes, and path is used to infer the audio format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( f"""An audio sample should have one of 'path' or 'bytes' but they are missing or None in {value}.""" ) def _lowercase (self : Dict , __a : dict , __a : Optional[Dict[str, Union[str, bool, None]]] = None ): if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Audio(decode=True) instead." ) UpperCAmelCase_ , UpperCAmelCase_ = (value["path"], BytesIO(value["bytes"] )) if value["bytes"] is not None else (value["path"], None) if path is None and file is None: raise ValueError(f"""An audio sample should have one of 'path' or 'bytes' but both are None in {value}.""" ) try: import librosa import soundfile as sf except ImportError as err: raise ImportError("To support decoding audio files, please install 'librosa' and 'soundfile'." ) from err UpperCAmelCase_ = xsplitext(__a )[1][1:].lower() if path is not None else None if not config.IS_OPUS_SUPPORTED and audio_format == "opus": raise RuntimeError( "Decoding 'opus' files requires system library 'libsndfile'>=1.0.31, " "You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. " ) elif not config.IS_MP3_SUPPORTED and audio_format == "mp3": raise RuntimeError( "Decoding 'mp3' files requires system library 'libsndfile'>=1.1.0, " "You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. " ) if file is None: UpperCAmelCase_ = token_per_repo_id or {} UpperCAmelCase_ = path.split("::" )[-1] try: UpperCAmelCase_ = string_to_dict(__a , config.HUB_DATASETS_URL )["repo_id"] UpperCAmelCase_ = token_per_repo_id[repo_id] except (ValueError, KeyError): UpperCAmelCase_ = None with xopen(__a , "rb" , use_auth_token=__a ) as f: UpperCAmelCase_ , UpperCAmelCase_ = sf.read(__a ) else: UpperCAmelCase_ , UpperCAmelCase_ = sf.read(__a ) UpperCAmelCase_ = array.T if self.mono: UpperCAmelCase_ = librosa.to_mono(__a ) if self.sampling_rate and self.sampling_rate != sampling_rate: UpperCAmelCase_ = librosa.resample(__a , orig_sr=__a , target_sr=self.sampling_rate ) UpperCAmelCase_ = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def _lowercase (self : Dict ): from .features import Value if self.decode: raise ValueError("Cannot flatten a decoded Audio feature." ) return { "bytes": Value("binary" ), "path": Value("string" ), } def _lowercase (self : Optional[Any] , __a : Union[pa.StringArray, pa.StructArray] ): if pa.types.is_string(storage.type ): UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.binary() ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.string() ) UpperCAmelCase_ = pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ) and storage.type.get_all_field_indices("array" ): UpperCAmelCase_ = pa.array([Audio().encode_example(__a ) if x is not None else None for x in storage.to_pylist()] ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: UpperCAmelCase_ = storage.field("bytes" ) else: UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: UpperCAmelCase_ = storage.field("path" ) else: UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.string() ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) return array_cast(__a , self.pa_type ) def _lowercase (self : Dict , __a : pa.StructArray ): @no_op_if_value_is_null def path_to_bytes(__a : Tuple ): with xopen(__a , "rb" ) as f: UpperCAmelCase_ = f.read() return bytes_ UpperCAmelCase_ = pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) UpperCAmelCase_ = pa.array( [os.path.basename(__a ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(__a , self.pa_type )
78
0
from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class _UpperCamelCase ( UpperCamelCase__ ): """simple docstring""" lowerCAmelCase = """Salesforce/blip-image-captioning-base""" lowerCAmelCase = ( """This is a tool that generates a description of an image. It takes an input named `image` which should be the """ """image to caption, and returns a text that contains the description in English.""" ) lowerCAmelCase = """image_captioner""" lowerCAmelCase = AutoModelForVisionaSeq lowerCAmelCase = ["""image"""] lowerCAmelCase = ["""text"""] def __init__( self , *a__ , **a__ ) -> List[Any]: requires_backends(self , ["""vision"""] ) super().__init__(*__a , **__a ) def _UpperCAmelCase ( self , a__ ) -> Any: return self.pre_processor(images=__a , return_tensors="""pt""" ) def _UpperCAmelCase ( self , a__ ) -> int: return self.model.generate(**__a ) def _UpperCAmelCase ( self , a__ ) -> str: return self.pre_processor.batch_decode(__a , skip_special_tokens=__a )[0].strip()
641
'''simple docstring''' import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def lowerCAmelCase_ ( snake_case_ : Any , snake_case_ : Optional[int] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg" UpperCAmelCase_ = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ).convert("RGB" ) UpperCAmelCase_ = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.4814_5466, 0.457_8275, 0.4082_1073) , (0.2686_2954, 0.2613_0258, 0.2757_7711) ), ] ) UpperCAmelCase_ = transform(snake_case_ ).unsqueeze(0 ).to(snake_case_ ) return image def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' if "visual_encoder" in key: UpperCAmelCase_ = re.sub("visual_encoder*" , "vision_model.encoder" , snake_case_ ) if "blocks" in key: UpperCAmelCase_ = re.sub(R"blocks" , "layers" , snake_case_ ) if "attn" in key: UpperCAmelCase_ = re.sub(R"attn" , "self_attn" , snake_case_ ) if "norm1" in key: UpperCAmelCase_ = re.sub(R"norm1" , "layer_norm1" , snake_case_ ) if "norm2" in key: UpperCAmelCase_ = re.sub(R"norm2" , "layer_norm2" , snake_case_ ) if "encoder.norm" in key: UpperCAmelCase_ = re.sub(R"encoder.norm" , "post_layernorm" , snake_case_ ) if "encoder.patch_embed.proj" in key: UpperCAmelCase_ = re.sub(R"encoder.patch_embed.proj" , "embeddings.patch_embedding" , snake_case_ ) if "encoder.pos_embed" in key: UpperCAmelCase_ = re.sub(R"encoder.pos_embed" , "embeddings.position_embedding" , snake_case_ ) if "encoder.cls_token" in key: UpperCAmelCase_ = re.sub(R"encoder.cls_token" , "embeddings.class_embedding" , snake_case_ ) if "self_attn" in key: UpperCAmelCase_ = re.sub(R"self_attn.proj" , "self_attn.projection" , snake_case_ ) return key @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : Any=None ) -> Union[str, Any]: '''simple docstring''' if config_path is not None: UpperCAmelCase_ = BlipConfig.from_pretrained(snake_case_ ) else: UpperCAmelCase_ = BlipConfig(projection_dim=5_12 , text_config={} , vision_config={} ) UpperCAmelCase_ = BlipForConditionalGeneration(snake_case_ ).eval() UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth" UpperCAmelCase_ = blip_decoder(pretrained=snake_case_ , image_size=3_84 , vit="base" ) UpperCAmelCase_ = pt_model.eval() UpperCAmelCase_ = pt_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value hf_model.load_state_dict(snake_case_ ) UpperCAmelCase_ = 3_84 UpperCAmelCase_ = load_demo_image(image_size=snake_case_ , device="cpu" ) UpperCAmelCase_ = BertTokenizer.from_pretrained("bert-base-uncased" ) UpperCAmelCase_ = tokenizer(["a picture of"] ).input_ids UpperCAmelCase_ = hf_model.generate(snake_case_ , snake_case_ ) assert out[0].tolist() == [3_05_22, 10_37, 38_61, 19_97, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] UpperCAmelCase_ = hf_model.generate(snake_case_ ) assert out[0].tolist() == [3_05_22, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(snake_case_ ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' UpperCAmelCase_ = ( "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth" ) UpperCAmelCase_ = blip_vqa(pretrained=snake_case_ , image_size=snake_case_ , vit="base" ) vqa_model.eval() UpperCAmelCase_ = vqa_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value UpperCAmelCase_ = BlipForQuestionAnswering(snake_case_ ) hf_vqa_model.load_state_dict(snake_case_ ) UpperCAmelCase_ = ["How many dogs are in this image?"] UpperCAmelCase_ = tokenizer(snake_case_ , return_tensors="pt" ).input_ids UpperCAmelCase_ = hf_vqa_model.generate(snake_case_ , snake_case_ ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + "_vqa" ) UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth" UpperCAmelCase_ = blip_itm(pretrained=snake_case_ , image_size=snake_case_ , vit="base" ) itm_model.eval() UpperCAmelCase_ = itm_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value UpperCAmelCase_ = BlipForImageTextRetrieval(snake_case_ ) UpperCAmelCase_ = ["A picture of a woman with a dog sitting in a beach"] UpperCAmelCase_ = tokenizer( snake_case_ , return_tensors="pt" , padding="max_length" , truncation=snake_case_ , max_length=35 , ).input_ids hf_itm_model.load_state_dict(snake_case_ ) hf_itm_model.eval() UpperCAmelCase_ = hf_itm_model(snake_case_ , snake_case_ , use_itm_head=snake_case_ ) UpperCAmelCase_ = hf_itm_model(snake_case_ , snake_case_ , use_itm_head=snake_case_ ) assert out[0].item() == 0.2110_6874_9427_7954 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.4_5698_8453_8650_5127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + "_itm" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Optional[Any] =argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') SCREAMING_SNAKE_CASE_: int =parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
78
0
"""simple docstring""" def _A ( __lowercase=2_8123 ): """simple docstring""" lowerCamelCase__ = [1] * (limit + 1) for i in range(2 , int(limit**0.5 ) + 1 ): sum_divs[i * i] += i for k in range(i + 1 , limit // i + 1 ): sum_divs[k * i] += k + i lowerCamelCase__ = set() lowerCamelCase__ = 0 for n in range(1 , limit + 1 ): if sum_divs[n] > n: abundants.add(snake_case_ ) if not any((n - a in abundants) for a in abundants ): res += n return res if __name__ == "__main__": print(solution())
129
'''simple docstring''' import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowerCAmelCase_ ( snake_case_ : List[Any] , snake_case_ : Union[str, Any]=0.999 , snake_case_ : Tuple="cosine" , ) -> Optional[Any]: '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(snake_case_ : Optional[int] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(snake_case_ : Optional[Any] ): return math.exp(t * -12.0 ) else: raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) UpperCAmelCase_ = [] for i in range(snake_case_ ): UpperCAmelCase_ = i / num_diffusion_timesteps UpperCAmelCase_ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(snake_case_ ) / alpha_bar_fn(snake_case_ ) , snake_case_ ) ) return torch.tensor(snake_case_ , dtype=torch.floataa ) class __A ( UpperCamelCase__ , UpperCamelCase__ ): a__ : Tuple = [e.name for e in KarrasDiffusionSchedulers] a__ : Optional[Any] = 2 @register_to_config def __init__(self : Union[str, Any] , __a : int = 1000 , __a : float = 0.0_00_85 , __a : float = 0.0_12 , __a : str = "linear" , __a : Optional[Union[np.ndarray, List[float]]] = None , __a : str = "epsilon" , __a : Optional[bool] = False , __a : Optional[bool] = False , __a : float = 1.0 , __a : str = "linspace" , __a : int = 0 , ): if trained_betas is not None: UpperCAmelCase_ = torch.tensor(__a , dtype=torch.floataa ) elif beta_schedule == "linear": UpperCAmelCase_ = torch.linspace(__a , __a , __a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. UpperCAmelCase_ = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , __a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule UpperCAmelCase_ = betas_for_alpha_bar(__a , alpha_transform_type="cosine" ) elif beta_schedule == "exp": UpperCAmelCase_ = betas_for_alpha_bar(__a , alpha_transform_type="exp" ) else: raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}""" ) UpperCAmelCase_ = 1.0 - self.betas UpperCAmelCase_ = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(__a , __a , __a ) UpperCAmelCase_ = use_karras_sigmas def _lowercase (self : Optional[Any] , __a : Union[str, Any] , __a : Tuple=None ): if schedule_timesteps is None: UpperCAmelCase_ = self.timesteps UpperCAmelCase_ = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: UpperCAmelCase_ = 1 if len(__a ) > 1 else 0 else: UpperCAmelCase_ = timestep.cpu().item() if torch.is_tensor(__a ) else timestep UpperCAmelCase_ = self._index_counter[timestep_int] return indices[pos].item() @property def _lowercase (self : List[Any] ): # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _lowercase (self : Optional[Any] , __a : torch.FloatTensor , __a : Union[float, torch.FloatTensor] , ): UpperCAmelCase_ = self.index_for_timestep(__a ) UpperCAmelCase_ = self.sigmas[step_index] UpperCAmelCase_ = sample / ((sigma**2 + 1) ** 0.5) return sample def _lowercase (self : Any , __a : int , __a : Union[str, torch.device] = None , __a : Optional[int] = None , ): UpperCAmelCase_ = num_inference_steps UpperCAmelCase_ = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": UpperCAmelCase_ = np.linspace(0 , num_train_timesteps - 1 , __a , dtype=__a )[::-1].copy() elif self.config.timestep_spacing == "leading": UpperCAmelCase_ = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 UpperCAmelCase_ = (np.arange(0 , __a ) * step_ratio).round()[::-1].copy().astype(__a ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": UpperCAmelCase_ = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 UpperCAmelCase_ = (np.arange(__a , 0 , -step_ratio )).round().copy().astype(__a ) timesteps -= 1 else: raise ValueError( f"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.""" ) UpperCAmelCase_ = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) UpperCAmelCase_ = np.log(__a ) UpperCAmelCase_ = np.interp(__a , np.arange(0 , len(__a ) ) , __a ) if self.config.use_karras_sigmas: UpperCAmelCase_ = self._convert_to_karras(in_sigmas=__a , num_inference_steps=self.num_inference_steps ) UpperCAmelCase_ = np.array([self._sigma_to_t(__a , __a ) for sigma in sigmas] ) UpperCAmelCase_ = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) UpperCAmelCase_ = torch.from_numpy(__a ).to(device=__a ) UpperCAmelCase_ = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) UpperCAmelCase_ = torch.from_numpy(__a ) UpperCAmelCase_ = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(__a ).startswith("mps" ): # mps does not support float64 UpperCAmelCase_ = timesteps.to(__a , dtype=torch.floataa ) else: UpperCAmelCase_ = timesteps.to(device=__a ) # empty dt and derivative UpperCAmelCase_ = None UpperCAmelCase_ = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter UpperCAmelCase_ = defaultdict(__a ) def _lowercase (self : int , __a : Optional[Any] , __a : List[str] ): # get log sigma UpperCAmelCase_ = np.log(__a ) # get distribution UpperCAmelCase_ = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range UpperCAmelCase_ = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) UpperCAmelCase_ = low_idx + 1 UpperCAmelCase_ = log_sigmas[low_idx] UpperCAmelCase_ = log_sigmas[high_idx] # interpolate sigmas UpperCAmelCase_ = (low - log_sigma) / (low - high) UpperCAmelCase_ = np.clip(__a , 0 , 1 ) # transform interpolation to time range UpperCAmelCase_ = (1 - w) * low_idx + w * high_idx UpperCAmelCase_ = t.reshape(sigma.shape ) return t def _lowercase (self : Dict , __a : torch.FloatTensor , __a : Optional[int] ): UpperCAmelCase_ = in_sigmas[-1].item() UpperCAmelCase_ = in_sigmas[0].item() UpperCAmelCase_ = 7.0 # 7.0 is the value used in the paper UpperCAmelCase_ = np.linspace(0 , 1 , __a ) UpperCAmelCase_ = sigma_min ** (1 / rho) UpperCAmelCase_ = sigma_max ** (1 / rho) UpperCAmelCase_ = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _lowercase (self : List[str] ): return self.dt is None def _lowercase (self : List[Any] , __a : Union[torch.FloatTensor, np.ndarray] , __a : Union[float, torch.FloatTensor] , __a : Union[torch.FloatTensor, np.ndarray] , __a : bool = True , ): UpperCAmelCase_ = self.index_for_timestep(__a ) # advance index counter by 1 UpperCAmelCase_ = timestep.cpu().item() if torch.is_tensor(__a ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: UpperCAmelCase_ = self.sigmas[step_index] UpperCAmelCase_ = self.sigmas[step_index + 1] else: # 2nd order / Heun's method UpperCAmelCase_ = self.sigmas[step_index - 1] UpperCAmelCase_ = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API UpperCAmelCase_ = 0 UpperCAmelCase_ = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": UpperCAmelCase_ = sigma_hat if self.state_in_first_order else sigma_next UpperCAmelCase_ = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": UpperCAmelCase_ = sigma_hat if self.state_in_first_order else sigma_next UpperCAmelCase_ = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": UpperCAmelCase_ = model_output else: raise ValueError( f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""" ) if self.config.clip_sample: UpperCAmelCase_ = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order UpperCAmelCase_ = (sample - pred_original_sample) / sigma_hat # 3. delta timestep UpperCAmelCase_ = sigma_next - sigma_hat # store for 2nd order step UpperCAmelCase_ = derivative UpperCAmelCase_ = dt UpperCAmelCase_ = sample else: # 2. 2nd order / Heun's method UpperCAmelCase_ = (sample - pred_original_sample) / sigma_next UpperCAmelCase_ = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample UpperCAmelCase_ = self.dt UpperCAmelCase_ = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=__a ) def _lowercase (self : Any , __a : torch.FloatTensor , __a : torch.FloatTensor , __a : torch.FloatTensor , ): # Make sure sigmas and timesteps have the same device and dtype as original_samples UpperCAmelCase_ = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(__a ): # mps does not support float64 UpperCAmelCase_ = self.timesteps.to(original_samples.device , dtype=torch.floataa ) UpperCAmelCase_ = timesteps.to(original_samples.device , dtype=torch.floataa ) else: UpperCAmelCase_ = self.timesteps.to(original_samples.device ) UpperCAmelCase_ = timesteps.to(original_samples.device ) UpperCAmelCase_ = [self.index_for_timestep(__a , __a ) for t in timesteps] UpperCAmelCase_ = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): UpperCAmelCase_ = sigma.unsqueeze(-1 ) UpperCAmelCase_ = original_samples + noise * sigma return noisy_samples def __len__(self : str ): return self.config.num_train_timesteps
78
0
"""simple docstring""" import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() __A = logging.get_logger(__name__) __A = { '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', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', } __A = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', ] def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> str: for attribute in key.split("." ): __lowerCAmelCase: Tuple = getattr(snake_case_ , snake_case_ ) if weight_type is not None: __lowerCAmelCase: Any = getattr(snake_case_ , snake_case_ ).shape else: __lowerCAmelCase: Any = hf_pointer.shape assert hf_shape == value.shape, ( F"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" F" {value.shape} for {full_name}" ) if weight_type == "weight": __lowerCAmelCase: Dict = value elif weight_type == "weight_g": __lowerCAmelCase: Tuple = value elif weight_type == "weight_v": __lowerCAmelCase: List[Any] = value elif weight_type == "bias": __lowerCAmelCase: Tuple = value else: __lowerCAmelCase: Dict = value logger.info(F"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> List[Any]: __lowerCAmelCase: Optional[int] = [] __lowerCAmelCase: List[Any] = fairseq_model.state_dict() __lowerCAmelCase: Union[str, Any] = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight __lowerCAmelCase: Optional[Any] = None for name, value in fairseq_dict.items(): __lowerCAmelCase: Tuple = False if "conv_layers" in name: load_conv_layer( snake_case_ , snake_case_ , snake_case_ , snake_case_ , hf_model.config.feat_extract_norm == "group" , ) __lowerCAmelCase: List[str] = True elif name.split("." )[0] == "proj": __lowerCAmelCase: List[str] = fairseq_model.proj __lowerCAmelCase: Dict = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: __lowerCAmelCase: Tuple = True if "*" in mapped_key: __lowerCAmelCase: Optional[int] = name.split(snake_case_ )[0].split("." )[-2] __lowerCAmelCase: List[Any] = mapped_key.replace("*" , snake_case_ ) if "weight_g" in name: __lowerCAmelCase: List[Any] = "weight_g" elif "weight_v" in name: __lowerCAmelCase: Tuple = "weight_v" elif "bias" in name: __lowerCAmelCase: int = "bias" elif "weight" in name: __lowerCAmelCase: List[str] = "weight" else: __lowerCAmelCase: Optional[Any] = None set_recursively(snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) continue if not is_used: unused_weights.append(snake_case_ ) logger.warning(F"Unused weights: {unused_weights}" ) return proj_weight def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Any: __lowerCAmelCase: Tuple = full_name.split("conv_layers." )[-1] __lowerCAmelCase: List[Any] = name.split("." ) __lowerCAmelCase: List[str] = int(items[0] ) __lowerCAmelCase: Optional[int] = 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." ) __lowerCAmelCase: Dict = 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." ) __lowerCAmelCase: Dict = 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." ) __lowerCAmelCase: Dict = 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." ) __lowerCAmelCase: List[Any] = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(snake_case_ ) def a__ ( __SCREAMING_SNAKE_CASE ) -> List[str]: __lowerCAmelCase , __lowerCAmelCase: str = emb.weight.shape __lowerCAmelCase: str = nn.Linear(snake_case_ , snake_case_ , bias=snake_case_ ) __lowerCAmelCase: str = emb.weight.data return lin_layer def a__ ( __SCREAMING_SNAKE_CASE ) -> List[Any]: with open(snake_case_ , "r" , encoding="utf-8" ) as f: __lowerCAmelCase: Any = f.readlines() __lowerCAmelCase: Any = [line.split(" " )[0] for line in lines] __lowerCAmelCase: List[str] = len(snake_case_ ) __lowerCAmelCase: Any = { "<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3, } vocab_dict.update(dict(zip(snake_case_ , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ) -> Dict: __lowerCAmelCase: Union[str, Any] = WavaVecaConfig.from_pretrained(snake_case_ ) __lowerCAmelCase: Optional[int] = SpeechaTextaConfig.from_pretrained( snake_case_ , vocab_size=snake_case_ , decoder_layers=snake_case_ , do_stable_layer_norm=snake_case_ ) __lowerCAmelCase: str = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=snake_case_ , return_attention_mask=snake_case_ , ) __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase: Tuple = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} ) __lowerCAmelCase: Dict = model[0].eval() # set weights for wav2vec2 encoder __lowerCAmelCase: List[Any] = WavaVecaModel(snake_case_ ) __lowerCAmelCase: List[Any] = recursively_load_weights_wavaveca(model.encoder , snake_case_ ) __lowerCAmelCase: Union[str, Any] = SpeechaTextaForCausalLM(snake_case_ ) __lowerCAmelCase , __lowerCAmelCase: Optional[int] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=snake_case_ ) # set output linear layer unexpected_keys.remove("embed_out" ) __lowerCAmelCase: str = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(F"The following keys are missing when loading the decoder weights: {missing_keys}" ) logger.warning(F"The following keys are unexpected when loading the decoder weights: {unexpected_keys}" ) __lowerCAmelCase: Optional[Any] = SpeechEncoderDecoderModel(encoder=snake_case_ , decoder=snake_case_ ) __lowerCAmelCase: str = False # add projection layer __lowerCAmelCase: Tuple = nn.Parameter(projection_layer.weight ) __lowerCAmelCase: Dict = nn.Parameter(projection_layer.bias ) __lowerCAmelCase: List[str] = create_vocab_dict(snake_case_ ) with open(os.path.join(snake_case_ , "vocab.json" ) , "w" ) as fp: json.dump(snake_case_ , snake_case_ ) __lowerCAmelCase: List[Any] = SpeechaTextaTokenizer(os.path.join(snake_case_ , "vocab.json" ) ) tokenizer.save_pretrained(snake_case_ ) __lowerCAmelCase: Dict = hf_wavavec.config.to_dict() __lowerCAmelCase: int = tokenizer.pad_token_id __lowerCAmelCase: Union[str, Any] = tokenizer.bos_token_id __lowerCAmelCase: Optional[Any] = tokenizer.eos_token_id __lowerCAmelCase: str = "speech_to_text_2" __lowerCAmelCase: str = "wav2vec2" __lowerCAmelCase: Optional[int] = SpeechEncoderDecoderConfig.from_dict(snake_case_ ) hf_wavavec.save_pretrained(snake_case_ ) feature_extractor.save_pretrained(snake_case_ ) if __name__ == "__main__": __A = 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( "--encoder_config_path", default="facebook/wav2vec2-large-lv60", type=str, help="Path to hf encoder wav2vec2 checkpoint config", ) parser.add_argument( "--decoder_config_path", default="facebook/s2t-small-mustc-en-fr-st", type=str, help="Path to hf decoder s2t checkpoint config", ) parser.add_argument("--vocab_size", default=10224, type=int, help="Vocab size of decoder") parser.add_argument("--num_decoder_layers", default=7, type=int, help="Number of decoder layers") __A = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
346
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __A ( UpperCamelCase__ ): a__ : List[str] = """Salesforce/blip-image-captioning-base""" a__ : Optional[Any] = ( """This is a tool that generates a description of an image. It takes an input named `image` which should be the """ """image to caption, and returns a text that contains the description in English.""" ) a__ : str = """image_captioner""" a__ : List[str] = AutoModelForVisionaSeq a__ : int = ["""image"""] a__ : Optional[Any] = ["""text"""] def __init__(self : Any , *__a : Dict , **__a : Union[str, Any] ): requires_backends(self , ["vision"] ) super().__init__(*__a , **__a ) def _lowercase (self : Union[str, Any] , __a : "Image" ): return self.pre_processor(images=__a , return_tensors="pt" ) def _lowercase (self : List[str] , __a : Dict ): return self.model.generate(**__a ) def _lowercase (self : int , __a : Optional[Any] ): return self.pre_processor.batch_decode(__a , skip_special_tokens=__a )[0].strip()
78
0
import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class A__ : '''simple docstring''' def __init__( self : Tuple , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Union[str, Any]=2 , _SCREAMING_SNAKE_CASE : List[Any]=True , _SCREAMING_SNAKE_CASE : str=False , _SCREAMING_SNAKE_CASE : List[Any]=10 , _SCREAMING_SNAKE_CASE : Optional[int]=3 , _SCREAMING_SNAKE_CASE : Any=32 * 4 , _SCREAMING_SNAKE_CASE : Any=32 * 6 , _SCREAMING_SNAKE_CASE : Optional[int]=4 , _SCREAMING_SNAKE_CASE : Optional[Any]=32 , ): """simple docstring""" UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = is_training UpperCamelCase = use_auxiliary_loss UpperCamelCase = num_queries UpperCamelCase = num_channels UpperCamelCase = min_size UpperCamelCase = max_size UpperCamelCase = num_labels UpperCamelCase = mask_feature_size def _SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( __a ) UpperCamelCase = torch.ones([self.batch_size, self.min_size, self.max_size] , device=__a ) UpperCamelCase = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=__a ) > 0.5 ).float() UpperCamelCase = (torch.rand((self.batch_size, self.num_labels) , device=__a ) > 0.5).long() UpperCamelCase = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=128 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def _SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase = {'pixel_values': pixel_values, 'pixel_mask': pixel_mask} return config, inputs_dict def _SCREAMING_SNAKE_CASE ( self : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" UpperCamelCase = output.encoder_hidden_states UpperCamelCase = output.pixel_decoder_hidden_states UpperCamelCase = output.transformer_decoder_hidden_states self.parent.assertTrue(len(__a ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(__a ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(__a ) , config.decoder_config.decoder_layers ) def _SCREAMING_SNAKE_CASE ( self : Tuple , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Any=False ): """simple docstring""" with torch.no_grad(): UpperCamelCase = MaskFormerModel(config=__a ) model.to(__a ) model.eval() UpperCamelCase = model(pixel_values=__a , pixel_mask=__a ) UpperCamelCase = model(__a , output_hidden_states=__a ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(__a , __a ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" UpperCamelCase = MaskFormerForInstanceSegmentation(config=__a ) model.to(__a ) model.eval() def comm_check_on_output(_SCREAMING_SNAKE_CASE : Any ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): UpperCamelCase = model(pixel_values=__a , pixel_mask=__a ) UpperCamelCase = model(__a ) comm_check_on_output(__a ) UpperCamelCase = model( pixel_values=__a , pixel_mask=__a , mask_labels=__a , class_labels=__a ) comm_check_on_output(__a ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class A__ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): '''simple docstring''' snake_case__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () snake_case__ = ( {"""feature-extraction""": MaskFormerModel, """image-segmentation""": MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False def _SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" UpperCamelCase = MaskFormerModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=__a , has_text_modality=__a ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(__a , **__a , output_hidden_states=__a ) def _SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*__a ) @unittest.skip(reason='MaskFormer does not use inputs_embeds' ) def _SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" pass @unittest.skip(reason='MaskFormer does not have a get_input_embeddings method' ) def _SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" pass @unittest.skip(reason='MaskFormer is not a generative model' ) def _SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" pass @unittest.skip(reason='MaskFormer does not use token embeddings' ) def _SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" pass @require_torch_multi_gpu @unittest.skip( reason='MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def _SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" pass def _SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(__a ) UpperCamelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase = [*signature.parameters.keys()] UpperCamelCase = ['pixel_values'] self.assertListEqual(arg_names[:1] , __a ) @slow def _SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" for model_name in ["facebook/maskformer-swin-small-coco"]: UpperCamelCase = MaskFormerModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def _SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" UpperCamelCase = (self.model_tester.min_size,) * 2 UpperCamelCase = { 'pixel_values': torch.randn((2, 3, *size) , device=__a ), 'mask_labels': torch.randn((2, 10, *size) , device=__a ), 'class_labels': torch.zeros(2 , 10 , device=__a ).long(), } UpperCamelCase = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(__a ) UpperCamelCase = model(**__a ) self.assertTrue(outputs.loss is not None ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(__a , **__a , output_hidden_states=__a ) def _SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(__a ).to(__a ) UpperCamelCase = model(**__a , output_attentions=__a ) self.assertTrue(outputs.attentions is not None ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss UpperCamelCase = self.all_model_classes[1] UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs() UpperCamelCase = model_class(__a ) model.to(__a ) model.train() UpperCamelCase = model(__a , mask_labels=__a , class_labels=__a ).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" UpperCamelCase = self.all_model_classes[1] UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs() UpperCamelCase = True UpperCamelCase = True UpperCamelCase = model_class(__a ) model.to(__a ) model.train() UpperCamelCase = model(__a , mask_labels=__a , class_labels=__a ) UpperCamelCase = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() UpperCamelCase = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't UpperCamelCase = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() UpperCamelCase = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=__a ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) __magic_name__ : int = 1e-4 def lowercase__ ( ) -> Optional[int]: """simple docstring""" UpperCamelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') return image @require_vision @slow class A__ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" return ( MaskFormerImageProcessor.from_pretrained('facebook/maskformer-swin-small-coco' ) if is_vision_available() else None ) def _SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" UpperCamelCase = MaskFormerModel.from_pretrained('facebook/maskformer-swin-small-coco' ).to(__a ) UpperCamelCase = self.default_image_processor UpperCamelCase = prepare_img() UpperCamelCase = image_processor(__a , return_tensors='pt' ).to(__a ) UpperCamelCase = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__a , (1, 3, 800, 1088) ) with torch.no_grad(): UpperCamelCase = model(**__a ) UpperCamelCase = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(__a ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , __a , atol=__a ) ) UpperCamelCase = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(__a ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , __a , atol=__a ) ) UpperCamelCase = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(__a ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , __a , atol=__a ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" UpperCamelCase = ( MaskFormerForInstanceSegmentation.from_pretrained('facebook/maskformer-swin-small-coco' ) .to(__a ) .eval() ) UpperCamelCase = self.default_image_processor UpperCamelCase = prepare_img() UpperCamelCase = image_processor(__a , return_tensors='pt' ).to(__a ) UpperCamelCase = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__a , (1, 3, 800, 1088) ) with torch.no_grad(): UpperCamelCase = model(**__a ) # masks_queries_logits UpperCamelCase = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) UpperCamelCase = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] UpperCamelCase = torch.tensor(__a ).to(__a ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __a , atol=__a ) ) # class_queries_logits UpperCamelCase = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) UpperCamelCase = torch.tensor( [ [1.6_5_1_2E0_0, -5.2_5_7_2E0_0, -3.3_5_1_9E0_0], [3.6_1_6_9E-0_2, -5.9_0_2_5E0_0, -2.9_3_1_3E0_0], [1.0_7_6_6E-0_4, -7.7_6_3_0E0_0, -5.1_2_6_3E0_0], ] ).to(__a ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __a , atol=__a ) ) def _SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" UpperCamelCase = ( MaskFormerForInstanceSegmentation.from_pretrained('facebook/maskformer-resnet101-coco-stuff' ) .to(__a ) .eval() ) UpperCamelCase = self.default_image_processor UpperCamelCase = prepare_img() UpperCamelCase = image_processor(__a , return_tensors='pt' ).to(__a ) UpperCamelCase = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__a , (1, 3, 800, 1088) ) with torch.no_grad(): UpperCamelCase = model(**__a ) # masks_queries_logits UpperCamelCase = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) UpperCamelCase = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] UpperCamelCase = torch.tensor(__a ).to(__a ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __a , atol=__a ) ) # class_queries_logits UpperCamelCase = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) UpperCamelCase = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(__a ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __a , atol=__a ) ) def _SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" UpperCamelCase = ( MaskFormerForInstanceSegmentation.from_pretrained('facebook/maskformer-swin-small-coco' ) .to(__a ) .eval() ) UpperCamelCase = self.default_image_processor UpperCamelCase = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors='pt' , ) UpperCamelCase = inputs['pixel_values'].to(__a ) UpperCamelCase = [el.to(__a ) for el in inputs['mask_labels']] UpperCamelCase = [el.to(__a ) for el in inputs['class_labels']] with torch.no_grad(): UpperCamelCase = model(**__a ) self.assertTrue(outputs.loss is not None )
280
'''simple docstring''' import logging import math from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union import torch from .tensor_utils import tensor_tree_map, tree_map def lowerCAmelCase_ ( snake_case_ : Union[dict, list, tuple, torch.Tensor] ) -> List[Tuple[int, ...]]: '''simple docstring''' UpperCAmelCase_ = [] if isinstance(snake_case_ , snake_case_ ): for v in tree.values(): shapes.extend(_fetch_dims(snake_case_ ) ) elif isinstance(snake_case_ , (list, tuple) ): for t in tree: shapes.extend(_fetch_dims(snake_case_ ) ) elif isinstance(snake_case_ , torch.Tensor ): shapes.append(tree.shape ) else: raise ValueError("Not supported" ) return shapes @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : Tuple[int, ...] ) -> Tuple[int, ...]: '''simple docstring''' UpperCAmelCase_ = [] for d in reversed(snake_case_ ): idx.append(flat_idx % d ) UpperCAmelCase_ = flat_idx // d return tuple(reversed(snake_case_ ) ) @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : Sequence[int] , snake_case_ : Sequence[int] , snake_case_ : Sequence[int] , snake_case_ : Optional[Sequence[bool]] = None , snake_case_ : Optional[Sequence[bool]] = None , ) -> List[Tuple[slice, ...]]: '''simple docstring''' def reduce_edge_list(snake_case_ : List[bool] ) -> None: UpperCAmelCase_ = True for i in range(len(snake_case_ ) ): UpperCAmelCase_ = -1 * (i + 1) l[reversed_idx] &= tally UpperCAmelCase_ = l[reversed_idx] if start_edges is None: UpperCAmelCase_ = [s == 0 for s in start] reduce_edge_list(snake_case_ ) if end_edges is None: UpperCAmelCase_ = [e == (d - 1) for e, d in zip(snake_case_ , snake_case_ )] reduce_edge_list(snake_case_ ) # Base cases. Either start/end are empty and we're done, or the final, # one-dimensional tensor can be simply sliced if len(snake_case_ ) == 0: return [()] elif len(snake_case_ ) == 1: return [(slice(start[0] , end[0] + 1 ),)] UpperCAmelCase_ = [] UpperCAmelCase_ = [] # Dimensions common to start and end can be selected directly for s, e in zip(snake_case_ , snake_case_ ): if s == e: path_list.append(slice(snake_case_ , s + 1 ) ) else: break UpperCAmelCase_ = tuple(snake_case_ ) UpperCAmelCase_ = len(snake_case_ ) # start == end, and we're done if divergence_idx == len(snake_case_ ): return [path] def upper() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None UpperCAmelCase_ = start[divergence_idx] return tuple( path + (slice(snake_case_ , sdi + 1 ),) + s for s in _get_minimal_slice_set( start[divergence_idx + 1 :] , [d - 1 for d in dims[divergence_idx + 1 :]] , dims[divergence_idx + 1 :] , start_edges=start_edges[divergence_idx + 1 :] , end_edges=[True for _ in end_edges[divergence_idx + 1 :]] , ) ) def lower() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None UpperCAmelCase_ = end[divergence_idx] return tuple( path + (slice(snake_case_ , edi + 1 ),) + s for s in _get_minimal_slice_set( [0 for _ in start[divergence_idx + 1 :]] , end[divergence_idx + 1 :] , dims[divergence_idx + 1 :] , start_edges=[True for _ in start_edges[divergence_idx + 1 :]] , end_edges=end_edges[divergence_idx + 1 :] , ) ) # If both start and end are at the edges of the subtree rooted at # divergence_idx, we can just select the whole subtree at once if start_edges[divergence_idx] and end_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] + 1 ),) ) # If just start is at the edge, we can grab almost all of the subtree, # treating only the ragged bottom edge as an edge case elif start_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] ),) ) slices.extend(lower() ) # Analogous to the previous case, but the top is ragged this time elif end_edges[divergence_idx]: slices.extend(upper() ) slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] + 1 ),) ) # If both sides of the range are ragged, we need to handle both sides # separately. If there's contiguous meat in between them, we can index it # in one big chunk else: slices.extend(upper() ) UpperCAmelCase_ = end[divergence_idx] - start[divergence_idx] if middle_ground > 1: slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] ),) ) slices.extend(lower() ) return slices @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : torch.Tensor , snake_case_ : int , snake_case_ : int , snake_case_ : int ) -> torch.Tensor: '''simple docstring''' UpperCAmelCase_ = t.shape[:no_batch_dims] UpperCAmelCase_ = list(_flat_idx_to_idx(snake_case_ , snake_case_ ) ) # _get_minimal_slice_set is inclusive UpperCAmelCase_ = list(_flat_idx_to_idx(flat_end - 1 , snake_case_ ) ) # Get an ordered list of slices to perform UpperCAmelCase_ = _get_minimal_slice_set( snake_case_ , snake_case_ , snake_case_ , ) UpperCAmelCase_ = [t[s] for s in slices] return torch.cat([s.view((-1,) + t.shape[no_batch_dims:] ) for s in sliced_tensors] ) def lowerCAmelCase_ ( snake_case_ : Callable , snake_case_ : Dict[str, Any] , snake_case_ : int , snake_case_ : int , snake_case_ : bool = False , snake_case_ : Any = None , snake_case_ : bool = False , ) -> Any: '''simple docstring''' if not (len(snake_case_ ) > 0): raise ValueError("Must provide at least one input" ) UpperCAmelCase_ = [shape[:no_batch_dims] for shape in _fetch_dims(snake_case_ )] UpperCAmelCase_ = tuple([max(snake_case_ ) for s in zip(*snake_case_ )] ) def _prep_inputs(snake_case_ : torch.Tensor ) -> torch.Tensor: if not low_mem: if not sum(t.shape[:no_batch_dims] ) == no_batch_dims: UpperCAmelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) UpperCAmelCase_ = t.reshape(-1 , *t.shape[no_batch_dims:] ) else: UpperCAmelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) return t UpperCAmelCase_ = tensor_tree_map(_prep_inputs , snake_case_ ) UpperCAmelCase_ = None if _out is not None: UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.view([-1] + list(t.shape[no_batch_dims:] ) ) , _out ) UpperCAmelCase_ = 1 for d in orig_batch_dims: flat_batch_dim *= d UpperCAmelCase_ = flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0) def _select_chunk(snake_case_ : torch.Tensor ) -> torch.Tensor: return t[i : i + chunk_size] if t.shape[0] != 1 else t UpperCAmelCase_ = 0 UpperCAmelCase_ = prepped_outputs for _ in range(snake_case_ ): # Chunk the input if not low_mem: UpperCAmelCase_ = _select_chunk else: UpperCAmelCase_ = partial( _chunk_slice , flat_start=snake_case_ , flat_end=min(snake_case_ , i + chunk_size ) , no_batch_dims=len(snake_case_ ) , ) UpperCAmelCase_ = tensor_tree_map(snake_case_ , snake_case_ ) # Run the layer on the chunk UpperCAmelCase_ = layer(**snake_case_ ) # Allocate space for the output if out is None: UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.new_zeros((flat_batch_dim,) + t.shape[1:] ) , snake_case_ ) # Put the chunk in its pre-allocated space if isinstance(snake_case_ , snake_case_ ): def assign(snake_case_ : dict , snake_case_ : dict ) -> None: for k, v in da.items(): if isinstance(snake_case_ , snake_case_ ): assign(snake_case_ , da[k] ) else: if _add_into_out: v[i : i + chunk_size] += da[k] else: UpperCAmelCase_ = da[k] assign(snake_case_ , snake_case_ ) elif isinstance(snake_case_ , snake_case_ ): for xa, xa in zip(snake_case_ , snake_case_ ): if _add_into_out: xa[i : i + chunk_size] += xa else: UpperCAmelCase_ = xa elif isinstance(snake_case_ , torch.Tensor ): if _add_into_out: out[i : i + chunk_size] += output_chunk else: UpperCAmelCase_ = output_chunk else: raise ValueError("Not supported" ) i += chunk_size UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.view(orig_batch_dims + t.shape[1:] ) , snake_case_ ) return out class __A : def __init__(self : Dict , __a : int = 512 , ): UpperCAmelCase_ = max_chunk_size UpperCAmelCase_ = None UpperCAmelCase_ = None def _lowercase (self : List[Any] , __a : Callable , __a : tuple , __a : int ): logging.info("Tuning chunk size..." ) if min_chunk_size >= self.max_chunk_size: return min_chunk_size UpperCAmelCase_ = [2**l for l in range(int(math.log(self.max_chunk_size , 2 ) ) + 1 )] UpperCAmelCase_ = [c for c in candidates if c > min_chunk_size] UpperCAmelCase_ = [min_chunk_size] + candidates candidates[-1] += 4 def test_chunk_size(__a : int ) -> bool: try: with torch.no_grad(): fn(*__a , chunk_size=__a ) return True except RuntimeError: return False UpperCAmelCase_ = 0 UpperCAmelCase_ = len(__a ) - 1 while i > min_viable_chunk_size_index: UpperCAmelCase_ = test_chunk_size(candidates[i] ) if not viable: UpperCAmelCase_ = (min_viable_chunk_size_index + i) // 2 else: UpperCAmelCase_ = i UpperCAmelCase_ = (i + len(__a ) - 1) // 2 return candidates[min_viable_chunk_size_index] def _lowercase (self : int , __a : Iterable , __a : Iterable ): UpperCAmelCase_ = True for aa, aa in zip(__a , __a ): assert type(__a ) == type(__a ) if isinstance(__a , (list, tuple) ): consistent &= self._compare_arg_caches(__a , __a ) elif isinstance(__a , __a ): UpperCAmelCase_ = [v for _, v in sorted(aa.items() , key=lambda __a : x[0] )] UpperCAmelCase_ = [v for _, v in sorted(aa.items() , key=lambda __a : x[0] )] consistent &= self._compare_arg_caches(__a , __a ) else: consistent &= aa == aa return consistent def _lowercase (self : List[str] , __a : Callable , __a : tuple , __a : int , ): UpperCAmelCase_ = True UpperCAmelCase_ = tree_map(lambda __a : a.shape if isinstance(__a , torch.Tensor ) else a , __a , __a ) if self.cached_arg_data is not None: # If args have changed shape/value, we need to re-tune assert len(self.cached_arg_data ) == len(__a ) UpperCAmelCase_ = self._compare_arg_caches(self.cached_arg_data , __a ) else: # Otherwise, we can reuse the precomputed value UpperCAmelCase_ = False if not consistent: UpperCAmelCase_ = self._determine_favorable_chunk_size( __a , __a , __a , ) UpperCAmelCase_ = arg_data assert self.cached_chunk_size is not None return self.cached_chunk_size
78
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCamelCase : List[Any] = { 'configuration_luke': ['LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LukeConfig'], 'tokenization_luke': ['LukeTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Dict = [ 'LUKE_PRETRAINED_MODEL_ARCHIVE_LIST', 'LukeForEntityClassification', 'LukeForEntityPairClassification', 'LukeForEntitySpanClassification', 'LukeForMultipleChoice', 'LukeForQuestionAnswering', 'LukeForSequenceClassification', 'LukeForTokenClassification', 'LukeForMaskedLM', 'LukeModel', 'LukePreTrainedModel', ] if TYPE_CHECKING: from .configuration_luke import LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP, LukeConfig from .tokenization_luke import LukeTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_luke import ( LUKE_PRETRAINED_MODEL_ARCHIVE_LIST, LukeForEntityClassification, LukeForEntityPairClassification, LukeForEntitySpanClassification, LukeForMaskedLM, LukeForMultipleChoice, LukeForQuestionAnswering, LukeForSequenceClassification, LukeForTokenClassification, LukeModel, LukePreTrainedModel, ) else: import sys __UpperCamelCase : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
519
'''simple docstring''' import copy import re class __A : a__ : Optional[int] = """hp""" a__ : Optional[Any] = {} a__ : List[Any] = None @classmethod def _lowercase (cls : Optional[int] , __a : str , __a : Tuple ): UpperCAmelCase_ = prefix UpperCAmelCase_ = defaults cls.build_naming_info() @staticmethod def _lowercase (__a : List[Any] , __a : List[str] ): if len(__a ) == 0: return "" UpperCAmelCase_ = None if any(char.isdigit() for char in word ): raise Exception(f"""Parameters should not contain numbers: '{word}' contains a number""" ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(__a ) + 1 ): UpperCAmelCase_ = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: UpperCAmelCase_ = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(__a : Union[str, Any] ): UpperCAmelCase_ = "" while integer != 0: UpperCAmelCase_ = chr(ord("A" ) + integer % 10 ) + s integer //= 10 return s UpperCAmelCase_ = 0 while True: UpperCAmelCase_ = word + "#" + int_to_alphabetic(__a ) if sword in info["reverse_short_word"]: continue else: UpperCAmelCase_ = sword break UpperCAmelCase_ = short_word UpperCAmelCase_ = word return short_word @staticmethod def _lowercase (__a : List[str] , __a : Union[str, Any] ): UpperCAmelCase_ = param_name.split("_" ) UpperCAmelCase_ = [TrialShortNamer.shortname_for_word(__a , __a ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name UpperCAmelCase_ = ["", "_"] for separator in separators: UpperCAmelCase_ = separator.join(__a ) if shortname not in info["reverse_short_param"]: UpperCAmelCase_ = shortname UpperCAmelCase_ = param_name return shortname return param_name @staticmethod def _lowercase (__a : int , __a : Union[str, Any] ): UpperCAmelCase_ = TrialShortNamer.shortname_for_key(__a , __a ) UpperCAmelCase_ = short_name UpperCAmelCase_ = param_name @classmethod def _lowercase (cls : Any ): if cls.NAMING_INFO is not None: return UpperCAmelCase_ = { "short_word": {}, "reverse_short_word": {}, "short_param": {}, "reverse_short_param": {}, } UpperCAmelCase_ = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(__a , __a ) UpperCAmelCase_ = info @classmethod def _lowercase (cls : int , __a : Optional[int] ): cls.build_naming_info() assert cls.PREFIX is not None UpperCAmelCase_ = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(f"""You should provide a default value for the param name {k} with value {v}""" ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue UpperCAmelCase_ = cls.NAMING_INFO["short_param"][k] if isinstance(__a , __a ): UpperCAmelCase_ = 1 if v else 0 UpperCAmelCase_ = "" if isinstance(__a , (int, float) ) else "-" UpperCAmelCase_ = f"""{key}{sep}{v}""" name.append(__a ) return "_".join(__a ) @classmethod def _lowercase (cls : Dict , __a : Dict ): UpperCAmelCase_ = repr[len(cls.PREFIX ) + 1 :] if repr == "": UpperCAmelCase_ = [] else: UpperCAmelCase_ = repr.split("_" ) UpperCAmelCase_ = {} for value in values: if "-" in value: UpperCAmelCase_ , UpperCAmelCase_ = value.split("-" ) else: UpperCAmelCase_ = re.sub("[0-9.]" , "" , __a ) UpperCAmelCase_ = float(re.sub("[^0-9.]" , "" , __a ) ) UpperCAmelCase_ = cls.NAMING_INFO["reverse_short_param"][p_k] UpperCAmelCase_ = p_v for k in cls.DEFAULTS: if k not in parameters: UpperCAmelCase_ = cls.DEFAULTS[k] return parameters
78
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 __SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Union[str, Any] = '▁' __SCREAMING_SNAKE_CASE : str = { 'vocab_file': 'vocab.json', 'spm_file': 'sentencepiece.bpe.model', } __SCREAMING_SNAKE_CASE : Any = { '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' ) }, } __SCREAMING_SNAKE_CASE : Tuple = { 'facebook/s2t-small-librispeech-asr': 1_0_2_4, } __SCREAMING_SNAKE_CASE : Any = ['pt', 'fr', 'ru', 'nl', 'ro', 'it', 'es', 'de'] __SCREAMING_SNAKE_CASE : Dict = {'mustc': MUSTC_LANGS} class lowerCamelCase_( UpperCamelCase__ ): '''simple docstring''' lowercase__ : List[str] = VOCAB_FILES_NAMES lowercase__ : Tuple = PRETRAINED_VOCAB_FILES_MAP lowercase__ : List[Any] = MAX_MODEL_INPUT_SIZES lowercase__ : int = ["""input_ids""", """attention_mask"""] lowercase__ : List[int] = [] def __init__( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__="<s>" , lowerCamelCase__="</s>" , lowerCamelCase__="<pad>" , lowerCamelCase__="<unk>" , lowerCamelCase__=False , lowerCamelCase__=False , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__ = None , **lowerCamelCase__ , ): _lowerCamelCase = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__a , eos_token=__a , unk_token=__a , pad_token=__a , do_upper_case=__a , do_lower_case=__a , tgt_lang=__a , lang_codes=__a , sp_model_kwargs=self.sp_model_kwargs , **__a , ) _lowerCamelCase = do_upper_case _lowerCamelCase = do_lower_case _lowerCamelCase = load_json(__a ) _lowerCamelCase = {v: k for k, v in self.encoder.items()} _lowerCamelCase = spm_file _lowerCamelCase = load_spm(__a , 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 snake_case__ ( self ): return len(self.encoder ) @property def snake_case__ ( self ): return self._tgt_lang @tgt_lang.setter def snake_case__ ( self , lowerCamelCase__ ): _lowerCamelCase = new_tgt_lang self.set_tgt_lang_special_tokens(__a ) def snake_case__ ( self , lowerCamelCase__ ): _lowerCamelCase = self.lang_code_to_id[tgt_lang] _lowerCamelCase = [lang_code_id] def snake_case__ ( self , lowerCamelCase__ ): return self.sp_model.encode(__a , out_type=__a ) def snake_case__ ( self , lowerCamelCase__ ): return self.encoder.get(__a , self.encoder[self.unk_token] ) def snake_case__ ( self , lowerCamelCase__ ): return self.decoder.get(__a , self.unk_token ) def snake_case__ ( self , lowerCamelCase__ ): _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(__a ) out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " " _lowerCamelCase = [] else: current_sub_tokens.append(__a ) _lowerCamelCase = self.sp_model.decode(__a ) out_string += decoded.upper() if self.do_upper_case else decoded return out_string.strip() def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__=None ): 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 snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ = None , lowerCamelCase__ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__a , token_ids_a=__a , already_has_special_tokens=__a ) _lowerCamelCase = [1] * len(self.prefix_tokens ) _lowerCamelCase = [1] if token_ids_a is None: return prefix_ones + ([0] * len(__a )) + suffix_ones return prefix_ones + ([0] * len(__a )) + ([0] * len(__a )) + suffix_ones def snake_case__ ( self ): _lowerCamelCase = self.encoder.copy() vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): _lowerCamelCase = self.__dict__.copy() _lowerCamelCase = None return state def __setstate__( self , lowerCamelCase__ ): _lowerCamelCase = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): _lowerCamelCase = {} _lowerCamelCase = load_spm(self.spm_file , self.sp_model_kwargs ) def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ = None ): _lowerCamelCase = Path(__a ) 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 , __a ) if os.path.abspath(self.spm_file ) != os.path.abspath(__a ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __a ) elif not os.path.isfile(self.spm_file ): with open(__a , '''wb''' ) as fi: _lowerCamelCase = self.sp_model.serialized_model_proto() fi.write(__a ) return (str(__a ), str(__a )) def lowerCAmelCase_( lowercase_ : str , lowercase_ : Dict[str, Any] ) -> sentencepiece.SentencePieceProcessor: _lowerCamelCase = sentencepiece.SentencePieceProcessor(**snake_case_ ) spm.Load(str(snake_case_ ) ) return spm def lowerCAmelCase_( lowercase_ : str ) -> Union[Dict, List]: with open(snake_case_ , '''r''' ) as f: return json.load(snake_case_ ) def lowerCAmelCase_( lowercase_ : Any , lowercase_ : str ) -> None: with open(snake_case_ , '''w''' ) as f: json.dump(snake_case_ , snake_case_ , indent=2 )
661
'''simple docstring''' from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging SCREAMING_SNAKE_CASE_: int =logging.get_logger(__name__) class __A ( UpperCamelCase__ ): a__ : Tuple = ["""pixel_values"""] def __init__(self : int , __a : bool = True , __a : Union[int, float] = 1 / 255 , __a : bool = True , __a : int = 8 , **__a : int , ): super().__init__(**__a ) UpperCAmelCase_ = do_rescale UpperCAmelCase_ = rescale_factor UpperCAmelCase_ = do_pad UpperCAmelCase_ = pad_size def _lowercase (self : Optional[int] , __a : np.ndarray , __a : float , __a : Optional[Union[str, ChannelDimension]] = None , **__a : Optional[int] ): return rescale(__a , scale=__a , data_format=__a , **__a ) def _lowercase (self : Optional[int] , __a : np.ndarray , __a : int , __a : Optional[Union[str, ChannelDimension]] = None ): UpperCAmelCase_ , UpperCAmelCase_ = get_image_size(__a ) UpperCAmelCase_ = (old_height // size + 1) * size - old_height UpperCAmelCase_ = (old_width // size + 1) * size - old_width return pad(__a , ((0, pad_height), (0, pad_width)) , mode="symmetric" , data_format=__a ) def _lowercase (self : Tuple , __a : ImageInput , __a : Optional[bool] = None , __a : Optional[float] = None , __a : Optional[bool] = None , __a : Optional[int] = None , __a : Optional[Union[str, TensorType]] = None , __a : Union[str, ChannelDimension] = ChannelDimension.FIRST , **__a : List[str] , ): 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_pad if do_pad is not None else self.do_pad UpperCAmelCase_ = pad_size if pad_size is not None else self.pad_size UpperCAmelCase_ = make_list_of_images(__a ) if not valid_images(__a ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) # All transformations expect numpy arrays. UpperCAmelCase_ = [to_numpy_array(__a ) for image in images] if do_rescale: UpperCAmelCase_ = [self.rescale(image=__a , scale=__a ) for image in images] if do_pad: UpperCAmelCase_ = [self.pad(__a , size=__a ) for image in images] UpperCAmelCase_ = [to_channel_dimension_format(__a , __a ) for image in images] UpperCAmelCase_ = {"pixel_values": images} return BatchFeature(data=__a , tensor_type=__a )
78
0
from math import sqrt def __lowerCAmelCase ( A_ : int ) -> bool: assert isinstance(snake_case_ , snake_case_ ) and ( number >= 0 ), "'number' must been an int and positive" __UpperCAmelCase = True # 0 and 1 are none primes. if number <= 1: __UpperCAmelCase = False for divisor in range(2 , int(round(sqrt(snake_case_ ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: __UpperCAmelCase = False break # precondition assert isinstance(snake_case_ , snake_case_ ), "'status' must been from type bool" return status def __lowerCAmelCase ( A_ : List[str] ) -> List[Any]: assert isinstance(snake_case_ , snake_case_ ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N __UpperCAmelCase = list(range(2 , n + 1 ) ) __UpperCAmelCase = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(snake_case_ ) ): for j in range(i + 1 , len(snake_case_ ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): __UpperCAmelCase = 0 # filters actual prime numbers. __UpperCAmelCase = [x for x in begin_list if x != 0] # precondition assert isinstance(snake_case_ , snake_case_ ), "'ans' must been from type list" return ans def __lowerCAmelCase ( A_ : Union[str, Any] ) -> Dict: assert isinstance(snake_case_ , snake_case_ ) and (n > 2), "'N' must been an int and > 2" __UpperCAmelCase = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 , n + 1 ): if is_prime(snake_case_ ): ans.append(snake_case_ ) # precondition assert isinstance(snake_case_ , snake_case_ ), "'ans' must been from type list" return ans def __lowerCAmelCase ( A_ : Any ) -> int: assert isinstance(snake_case_ , snake_case_ ) and number >= 0, "'number' must been an int and >= 0" __UpperCAmelCase = [] # this list will be returns of the function. # potential prime number factors. __UpperCAmelCase = 2 __UpperCAmelCase = number if number == 0 or number == 1: ans.append(snake_case_ ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(snake_case_ ): while quotient != 1: if is_prime(snake_case_ ) and (quotient % factor == 0): ans.append(snake_case_ ) quotient /= factor else: factor += 1 else: ans.append(snake_case_ ) # precondition assert isinstance(snake_case_ , snake_case_ ), "'ans' must been from type list" return ans def __lowerCAmelCase ( A_ : List[str] ) -> List[Any]: assert isinstance(snake_case_ , snake_case_ ) and ( number >= 0 ), "'number' bust been an int and >= 0" __UpperCAmelCase = 0 # prime factorization of 'number' __UpperCAmelCase = prime_factorization(snake_case_ ) __UpperCAmelCase = max(snake_case_ ) # precondition assert isinstance(snake_case_ , snake_case_ ), "'ans' must been from type int" return ans def __lowerCAmelCase ( A_ : Union[str, Any] ) -> Union[str, Any]: assert isinstance(snake_case_ , snake_case_ ) and ( number >= 0 ), "'number' bust been an int and >= 0" __UpperCAmelCase = 0 # prime factorization of 'number' __UpperCAmelCase = prime_factorization(snake_case_ ) __UpperCAmelCase = min(snake_case_ ) # precondition assert isinstance(snake_case_ , snake_case_ ), "'ans' must been from type int" return ans def __lowerCAmelCase ( A_ : List[str] ) -> List[str]: assert isinstance(snake_case_ , snake_case_ ), "'number' must been an int" assert isinstance(number % 2 == 0 , snake_case_ ), "compare bust been from type bool" return number % 2 == 0 def __lowerCAmelCase ( A_ : Dict ) -> Any: assert isinstance(snake_case_ , snake_case_ ), "'number' must been an int" assert isinstance(number % 2 != 0 , snake_case_ ), "compare bust been from type bool" return number % 2 != 0 def __lowerCAmelCase ( A_ : Optional[Any] ) -> Any: assert ( isinstance(snake_case_ , snake_case_ ) and (number > 2) and is_even(snake_case_ ) ), "'number' must been an int, even and > 2" __UpperCAmelCase = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' __UpperCAmelCase = get_prime_numbers(snake_case_ ) __UpperCAmelCase = len(snake_case_ ) # run variable for while-loops. __UpperCAmelCase = 0 __UpperCAmelCase = None # exit variable. for break up the loops __UpperCAmelCase = True while i < len_pn and loop: __UpperCAmelCase = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: __UpperCAmelCase = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(snake_case_ , snake_case_ ) and (len(snake_case_ ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def __lowerCAmelCase ( A_ : int , A_ : Optional[int] ) -> Optional[int]: assert ( isinstance(snake_case_ , snake_case_ ) and isinstance(snake_case_ , snake_case_ ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." __UpperCAmelCase = 0 while numbera != 0: __UpperCAmelCase = numbera % numbera __UpperCAmelCase = numbera __UpperCAmelCase = rest # precondition assert isinstance(snake_case_ , snake_case_ ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def __lowerCAmelCase ( A_ : List[str] , A_ : Tuple ) -> Tuple: assert ( isinstance(snake_case_ , snake_case_ ) and isinstance(snake_case_ , snake_case_ ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." __UpperCAmelCase = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' __UpperCAmelCase = prime_factorization(snake_case_ ) __UpperCAmelCase = prime_factorization(snake_case_ ) elif numbera == 1 or numbera == 1: __UpperCAmelCase = [] __UpperCAmelCase = [] __UpperCAmelCase = max(snake_case_ , snake_case_ ) __UpperCAmelCase = 0 __UpperCAmelCase = 0 __UpperCAmelCase = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: __UpperCAmelCase = prime_fac_a.count(snake_case_ ) __UpperCAmelCase = prime_fac_a.count(snake_case_ ) for _ in range(max(snake_case_ , snake_case_ ) ): ans *= n else: __UpperCAmelCase = prime_fac_a.count(snake_case_ ) for _ in range(snake_case_ ): ans *= n done.append(snake_case_ ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: __UpperCAmelCase = prime_fac_a.count(snake_case_ ) for _ in range(snake_case_ ): ans *= n done.append(snake_case_ ) # precondition assert isinstance(snake_case_ , snake_case_ ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def __lowerCAmelCase ( A_ : Union[str, Any] ) -> Union[str, Any]: assert isinstance(snake_case_ , snake_case_ ) and (n >= 0), "'number' must been a positive int" __UpperCAmelCase = 0 __UpperCAmelCase = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(snake_case_ ): ans += 1 # precondition assert isinstance(snake_case_ , snake_case_ ) and is_prime( snake_case_ ), "'ans' must been a prime number and from type int" return ans def __lowerCAmelCase ( A_ : List[str] , A_ : Tuple ) -> List[str]: assert ( is_prime(snake_case_ ) and is_prime(snake_case_ ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" __UpperCAmelCase = p_number_a + 1 # jump to the next number __UpperCAmelCase = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(snake_case_ ): number += 1 while number < p_number_a: ans.append(snake_case_ ) number += 1 # fetch the next prime number. while not is_prime(snake_case_ ): number += 1 # precondition assert ( isinstance(snake_case_ , snake_case_ ) and ans[0] != p_number_a and ans[len(snake_case_ ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def __lowerCAmelCase ( A_ : Tuple ) -> Union[str, Any]: assert isinstance(snake_case_ , snake_case_ ) and (n >= 1), "'n' must been int and >= 1" __UpperCAmelCase = [] # will be returned. for divisor in range(1 , n + 1 ): if n % divisor == 0: ans.append(snake_case_ ) # precondition assert ans[0] == 1 and ans[len(snake_case_ ) - 1] == n, "Error in function getDivisiors(...)" return ans def __lowerCAmelCase ( A_ : List[str] ) -> str: assert isinstance(snake_case_ , snake_case_ ) and ( number > 1 ), "'number' must been an int and >= 1" __UpperCAmelCase = get_divisors(snake_case_ ) # precondition assert ( isinstance(snake_case_ , snake_case_ ) and (divisors[0] == 1) and (divisors[len(snake_case_ ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def __lowerCAmelCase ( A_ : int , A_ : int ) -> int: assert ( isinstance(snake_case_ , snake_case_ ) and isinstance(snake_case_ , snake_case_ ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. __UpperCAmelCase = gcd(abs(snake_case_ ) , abs(snake_case_ ) ) # precondition assert ( isinstance(snake_case_ , snake_case_ ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def __lowerCAmelCase ( A_ : int ) -> List[str]: assert isinstance(snake_case_ , snake_case_ ) and (n >= 0), "'n' must been a int and >= 0" __UpperCAmelCase = 1 # this will be return. for factor in range(1 , n + 1 ): ans *= factor return ans def __lowerCAmelCase ( A_ : List[str] ) -> Optional[Any]: assert isinstance(snake_case_ , snake_case_ ) and (n >= 0), "'n' must been an int and >= 0" __UpperCAmelCase = 0 __UpperCAmelCase = 1 __UpperCAmelCase = 1 # this will be return for _ in range(n - 1 ): __UpperCAmelCase = ans ans += fiba __UpperCAmelCase = tmp return ans
221
'''simple docstring''' import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# SCREAMING_SNAKE_CASE_: Dict =[ # (stable-diffusion, HF Diffusers) ('time_embed.0.weight', 'time_embedding.linear_1.weight'), ('time_embed.0.bias', 'time_embedding.linear_1.bias'), ('time_embed.2.weight', 'time_embedding.linear_2.weight'), ('time_embed.2.bias', 'time_embedding.linear_2.bias'), ('input_blocks.0.0.weight', 'conv_in.weight'), ('input_blocks.0.0.bias', 'conv_in.bias'), ('out.0.weight', 'conv_norm_out.weight'), ('out.0.bias', 'conv_norm_out.bias'), ('out.2.weight', 'conv_out.weight'), ('out.2.bias', 'conv_out.bias'), ] SCREAMING_SNAKE_CASE_: List[Any] =[ # (stable-diffusion, HF Diffusers) ('in_layers.0', 'norm1'), ('in_layers.2', 'conv1'), ('out_layers.0', 'norm2'), ('out_layers.3', 'conv2'), ('emb_layers.1', 'time_emb_proj'), ('skip_connection', 'conv_shortcut'), ] SCREAMING_SNAKE_CASE_: Union[str, Any] =[] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks SCREAMING_SNAKE_CASE_: Any =f"down_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Tuple =f"input_blocks.{3*i + j + 1}.0." unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 SCREAMING_SNAKE_CASE_: Optional[Any] =f"down_blocks.{i}.attentions.{j}." SCREAMING_SNAKE_CASE_: List[str] =f"input_blocks.{3*i + j + 1}.1." unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks SCREAMING_SNAKE_CASE_: Union[str, Any] =f"up_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Any =f"output_blocks.{3*i + j}.0." unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.attentions.{j}." SCREAMING_SNAKE_CASE_: Optional[int] =f"output_blocks.{3*i + j}.1." unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 SCREAMING_SNAKE_CASE_: Union[str, Any] =f"down_blocks.{i}.downsamplers.0.conv." SCREAMING_SNAKE_CASE_: Union[str, Any] =f"input_blocks.{3*(i+1)}.0.op." unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.upsamplers.0." SCREAMING_SNAKE_CASE_: List[Any] =f"output_blocks.{3*i + 2}.{1 if i == 0 else 2}." unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) SCREAMING_SNAKE_CASE_: int ='mid_block.attentions.0.' SCREAMING_SNAKE_CASE_: List[Any] ='middle_block.1.' unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): SCREAMING_SNAKE_CASE_: Tuple =f"mid_block.resnets.{j}." SCREAMING_SNAKE_CASE_: Tuple =f"middle_block.{2*j}." unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: UpperCAmelCase_ = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v UpperCAmelCase_ = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# SCREAMING_SNAKE_CASE_: int =[ # (stable-diffusion, HF Diffusers) ('nin_shortcut', 'conv_shortcut'), ('norm_out', 'conv_norm_out'), ('mid.attn_1.', 'mid_block.attentions.0.'), ] for i in range(4): # down_blocks have two resnets for j in range(2): SCREAMING_SNAKE_CASE_: Tuple =f"encoder.down_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: int =f"encoder.down.{i}.block.{j}." vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: SCREAMING_SNAKE_CASE_: int =f"down_blocks.{i}.downsamplers.0." SCREAMING_SNAKE_CASE_: str =f"down.{i}.downsample." vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.upsamplers.0." SCREAMING_SNAKE_CASE_: List[str] =f"up.{3-i}.upsample." vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): SCREAMING_SNAKE_CASE_: List[str] =f"decoder.up_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Dict =f"decoder.up.{3-i}.block.{j}." vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): SCREAMING_SNAKE_CASE_: Any =f"mid_block.resnets.{i}." SCREAMING_SNAKE_CASE_: Tuple =f"mid.block_{i+1}." vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) SCREAMING_SNAKE_CASE_: int =[ # (stable-diffusion, HF Diffusers) ('norm.', 'group_norm.'), ('q.', 'query.'), ('k.', 'key.'), ('v.', 'value.'), ('proj_out.', 'proj_attn.'), ] def lowerCAmelCase_ ( snake_case_ : Tuple ) -> Tuple: '''simple docstring''' return w.reshape(*w.shape , 1 , 1 ) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v UpperCAmelCase_ = {v: vae_state_dict[k] for k, v in mapping.items()} UpperCAmelCase_ = ["q", "k", "v", "proj_out"] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if f"""mid.attn_1.{weight_name}.weight""" in k: print(f"""Reshaping {k} for SD format""" ) UpperCAmelCase_ = reshape_weight_for_sd(snake_case_ ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# SCREAMING_SNAKE_CASE_: List[Any] =[ # (stable-diffusion, HF Diffusers) ('resblocks.', 'text_model.encoder.layers.'), ('ln_1', 'layer_norm1'), ('ln_2', 'layer_norm2'), ('.c_fc.', '.fc1.'), ('.c_proj.', '.fc2.'), ('.attn', '.self_attn'), ('ln_final.', 'transformer.text_model.final_layer_norm.'), ('token_embedding.weight', 'transformer.text_model.embeddings.token_embedding.weight'), ('positional_embedding', 'transformer.text_model.embeddings.position_embedding.weight'), ] SCREAMING_SNAKE_CASE_: Dict ={re.escape(x[1]): x[0] for x in textenc_conversion_lst} SCREAMING_SNAKE_CASE_: str =re.compile('|'.join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp SCREAMING_SNAKE_CASE_: List[Any] ={'q': 0, 'k': 1, 'v': 2} def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = {} UpperCAmelCase_ = {} UpperCAmelCase_ = {} for k, v in text_enc_dict.items(): if ( k.endswith(".self_attn.q_proj.weight" ) or k.endswith(".self_attn.k_proj.weight" ) or k.endswith(".self_attn.v_proj.weight" ) ): UpperCAmelCase_ = k[: -len(".q_proj.weight" )] UpperCAmelCase_ = k[-len("q_proj.weight" )] if k_pre not in capture_qkv_weight: UpperCAmelCase_ = [None, None, None] UpperCAmelCase_ = v continue if ( k.endswith(".self_attn.q_proj.bias" ) or k.endswith(".self_attn.k_proj.bias" ) or k.endswith(".self_attn.v_proj.bias" ) ): UpperCAmelCase_ = k[: -len(".q_proj.bias" )] UpperCAmelCase_ = k[-len("q_proj.bias" )] if k_pre not in capture_qkv_bias: UpperCAmelCase_ = [None, None, None] UpperCAmelCase_ = v continue UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = torch.cat(snake_case_ ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = torch.cat(snake_case_ ) return new_state_dict def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> Union[str, Any]: '''simple docstring''' return text_enc_dict if __name__ == "__main__": SCREAMING_SNAKE_CASE_: str =argparse.ArgumentParser() parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.') parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--use_safetensors', action='store_true', help='Save weights use safetensors, default is ckpt.' ) SCREAMING_SNAKE_CASE_: Dict =parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors SCREAMING_SNAKE_CASE_: Any =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.safetensors') SCREAMING_SNAKE_CASE_: Dict =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.safetensors') SCREAMING_SNAKE_CASE_: Union[str, Any] =osp.join(args.model_path, 'text_encoder', 'model.safetensors') # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): SCREAMING_SNAKE_CASE_: Union[str, Any] =load_file(unet_path, device='cpu') else: SCREAMING_SNAKE_CASE_: int =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.bin') SCREAMING_SNAKE_CASE_: Dict =torch.load(unet_path, map_location='cpu') if osp.exists(vae_path): SCREAMING_SNAKE_CASE_: Tuple =load_file(vae_path, device='cpu') else: SCREAMING_SNAKE_CASE_: List[Any] =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.bin') SCREAMING_SNAKE_CASE_: str =torch.load(vae_path, map_location='cpu') if osp.exists(text_enc_path): SCREAMING_SNAKE_CASE_: Tuple =load_file(text_enc_path, device='cpu') else: SCREAMING_SNAKE_CASE_: List[Any] =osp.join(args.model_path, 'text_encoder', 'pytorch_model.bin') SCREAMING_SNAKE_CASE_: Any =torch.load(text_enc_path, map_location='cpu') # Convert the UNet model SCREAMING_SNAKE_CASE_: List[Any] =convert_unet_state_dict(unet_state_dict) SCREAMING_SNAKE_CASE_: Any ={'model.diffusion_model.' + k: v for k, v in unet_state_dict.items()} # Convert the VAE model SCREAMING_SNAKE_CASE_: List[Any] =convert_vae_state_dict(vae_state_dict) SCREAMING_SNAKE_CASE_: Dict ={'first_stage_model.' + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper SCREAMING_SNAKE_CASE_: Dict ='text_model.encoder.layers.22.layer_norm2.bias' in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm SCREAMING_SNAKE_CASE_: Any ={'transformer.' + k: v for k, v in text_enc_dict.items()} SCREAMING_SNAKE_CASE_: str =convert_text_enc_state_dict_vaa(text_enc_dict) SCREAMING_SNAKE_CASE_: int ={'cond_stage_model.model.' + k: v for k, v in text_enc_dict.items()} else: SCREAMING_SNAKE_CASE_: str =convert_text_enc_state_dict(text_enc_dict) SCREAMING_SNAKE_CASE_: Optional[int] ={'cond_stage_model.transformer.' + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint SCREAMING_SNAKE_CASE_: List[str] ={**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: SCREAMING_SNAKE_CASE_: List[str] ={k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: SCREAMING_SNAKE_CASE_: str ={'state_dict': state_dict} torch.save(state_dict, args.checkpoint_path)
78
0
"""simple docstring""" import numpy as np class _lowerCamelCase : def __init__( self : Union[str, Any] ) -> List[str]: """simple docstring""" lowerCAmelCase__ : Optional[int] = (0, 0) lowerCAmelCase__ : List[Any] = None lowerCAmelCase__ : List[Any] = 0 lowerCAmelCase__ : Dict = 0 lowerCAmelCase__ : Dict = 0 def __eq__( self : List[str] , UpperCamelCase : List[Any] ) -> Optional[int]: """simple docstring""" return self.position == cell.position def _lowerCAmelCase ( self : List[str] ) -> Any: """simple docstring""" print(self.position ) class _lowerCamelCase : def __init__( self : Optional[int] , UpperCamelCase : Tuple=(5, 5) ) -> Dict: """simple docstring""" lowerCAmelCase__ : Union[str, Any] = np.zeros(__a ) lowerCAmelCase__ : Optional[int] = world_size[0] lowerCAmelCase__ : str = world_size[1] def _lowerCAmelCase ( self : str ) -> List[Any]: """simple docstring""" print(self.w ) def _lowerCAmelCase ( self : Any , UpperCamelCase : List[Any] ) -> Optional[int]: """simple docstring""" lowerCAmelCase__ : int = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] lowerCAmelCase__ : str = cell.position[0] lowerCAmelCase__ : Union[str, Any] = cell.position[1] lowerCAmelCase__ : str = [] for n in neughbour_cord: lowerCAmelCase__ : Dict = current_x + n[0] lowerCAmelCase__ : str = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: lowerCAmelCase__ : Dict = Cell() lowerCAmelCase__ : List[str] = (x, y) lowerCAmelCase__ : Union[str, Any] = cell neighbours.append(__a ) return neighbours def lowercase_ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Optional[Any]: lowerCAmelCase__ : Dict = [] lowerCAmelCase__ : Optional[int] = [] _open.append(snake_case_ ) while _open: lowerCAmelCase__ : Optional[int] = np.argmin([n.f for n in _open] ) lowerCAmelCase__ : Union[str, Any] = _open[min_f] _closed.append(_open.pop(snake_case_ ) ) if current == goal: break for n in world.get_neigbours(snake_case_ ): for c in _closed: if c == n: continue lowerCAmelCase__ : Union[str, Any] = current.g + 1 lowerCAmelCase__ , lowerCAmelCase__ : List[Any] = n.position lowerCAmelCase__ , lowerCAmelCase__ : str = goal.position lowerCAmelCase__ : str = (ya - ya) ** 2 + (xa - xa) ** 2 lowerCAmelCase__ : Any = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(snake_case_ ) lowerCAmelCase__ : List[Any] = [] while current.parent is not None: path.append(current.position ) lowerCAmelCase__ : Optional[int] = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": _A = Gridworld() # Start position and goal _A = Cell() _A = (0, 0) _A = Cell() _A = (4, 4) print(f"""path from {start.position} to {goal.position}""") _A = astar(world, start, goal) # Just for visual reasons. for i in s: _A = 1 print(world.w)
299
'''simple docstring''' import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( snake_case_ : ndarray ) -> float: '''simple docstring''' return np.dot(snake_case_ , snake_case_ ) class __A : def __init__(self : int , *, __a : float = np.inf , __a : str = "linear" , __a : float = 0.0 , ): UpperCAmelCase_ = regularization UpperCAmelCase_ = gamma if kernel == "linear": UpperCAmelCase_ = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("rbf kernel requires gamma" ) if not isinstance(self.gamma , (float, int) ): raise ValueError("gamma must be float or int" ) if not self.gamma > 0: raise ValueError("gamma must be > 0" ) UpperCAmelCase_ = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: UpperCAmelCase_ = f"""Unknown kernel: {kernel}""" raise ValueError(__a ) def _lowercase (self : Optional[int] , __a : ndarray , __a : ndarray ): return np.dot(__a , __a ) def _lowercase (self : Optional[int] , __a : ndarray , __a : ndarray ): return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def _lowercase (self : str , __a : list[ndarray] , __a : ndarray ): UpperCAmelCase_ = observations UpperCAmelCase_ = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((UpperCAmelCase_) , ) = np.shape(__a ) def to_minimize(__a : ndarray ) -> float: UpperCAmelCase_ = 0 ((UpperCAmelCase_) , ) = np.shape(__a ) for i in range(__a ): for j in range(__a ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(__a ) UpperCAmelCase_ = LinearConstraint(__a , 0 , 0 ) UpperCAmelCase_ = Bounds(0 , self.regularization ) UpperCAmelCase_ = minimize( __a , np.ones(__a ) , bounds=__a , constraints=[ly_contraint] ).x UpperCAmelCase_ = l_star # calculating mean offset of separation plane to points UpperCAmelCase_ = 0 for i in range(__a ): for j in range(__a ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) UpperCAmelCase_ = s / n def _lowercase (self : Optional[int] , __a : ndarray ): UpperCAmelCase_ = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , __a ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
78
0
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE :Optional[int] = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece class __lowerCAmelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = XLMProphetNetTokenizer _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = True def lowerCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing snake_case_ = XLMProphetNetTokenizer(__a , keep_accents=__a ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" snake_case_ = "[PAD]" snake_case_ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a ) , __a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a ) , __a ) def lowerCAmelCase__ ( self : Any ) -> Optional[int]: """simple docstring""" snake_case_ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "[PAD]" ) self.assertEqual(vocab_keys[1] , "[CLS]" ) self.assertEqual(vocab_keys[-1] , "j" ) self.assertEqual(len(__a ) , 1_0_1_2 ) def lowerCAmelCase__ ( self : int ) -> int: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_0_1_2 ) def lowerCAmelCase__ ( self : int ) -> Union[str, Any]: """simple docstring""" snake_case_ = XLMProphetNetTokenizer(__a , keep_accents=__a ) snake_case_ = tokenizer.tokenize("This is a test" ) self.assertListEqual(__a , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__a ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) snake_case_ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( __a , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) snake_case_ = tokenizer.convert_tokens_to_ids(__a ) self.assertListEqual( __a , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, -9, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, -9, 4] ] , ) snake_case_ = tokenizer.convert_ids_to_tokens(__a ) self.assertListEqual( __a , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "[UNK]", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "[UNK]", ".", ] , ) @cached_property def lowerCAmelCase__ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" return XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased" ) @slow def lowerCAmelCase__ ( self : List[str] ) -> str: """simple docstring""" snake_case_ = "Hello World!" snake_case_ = [3_5_3_8_9, 6_6_7_2, 4_9, 2] self.assertListEqual(__a , self.big_tokenizer.encode(__a ) ) @slow def lowerCAmelCase__ ( self : int ) -> List[str]: """simple docstring""" # fmt: off snake_case_ = {"input_ids": [[1_1_0_7_3, 8_2_7_8_3, 1_8, 2_6, 8_2_7_8_3, 5_4_9, 5_1_5_4_0, 2_4_8, 1_7_2_0_9, 1_3_0_1, 2_1_7, 2_0, 2_1_5_1_8_6, 1_3_2_5, 1_4_7, 1_7_2_0_9, 1_3_0_1, 2_1_7, 2_0, 5_6_3_7_0, 5_3, 1_2_2_0_2_0, 2_0, 1_6_4_7_7, 2_7, 8_7_3_5_5, 4_5_4_8, 2_0, 4_7_2_8, 7_8_3_9_2, 1_7, 1_5_9_9_6_9, 1_8, 2_6, 2_4_4_9_1, 6_2_9, 1_5, 5_3_8, 2_2_7_0_4, 5_4_3_9, 1_5, 2_7_8_8, 2_4_4_9_1, 9_8_8_5, 1_5, 4_3_5_3_4, 6_0_5, 1_5, 8_1_4, 1_8_4_0_3, 3_3_2_0_0, 2_9, 1_5, 4_3_5_3_4, 2_4_4_5_8, 1_2_4_1_0, 1_1_1, 2_4_9_6_6, 8_3_6_6_9, 9_6_3_7, 1_4_4_0_6_8, 2_6, 8_5_0, 2_2_3_4_6, 2_7, 1_4_7, 2_4_9_6_6, 8_3_6_6_9, 8_3_4_9_0, 2_6, 3_9_1_1_3, 7_3_5, 2_7, 6_8_9, 6_5_6, 2_8_0_0, 1_3_3_9, 4_6_0_0, 5_3, 1_2_2_0_2_0, 1_1_5_7_8_5, 3_4, 8_1_6, 1_3_3_9, 4_6_8_8_7, 1_8, 1_4_7, 5_3_9_0_5, 1_9_5_1, 4_2_2_3_8, 4_1_1_7_0, 1_7_7_3_2, 8_3_4, 4_3_6, 1_5, 2_7_5_2_3, 9_8_7_3_3, 2_1_7, 1_4_7, 5_5_4_2, 4_9_8_1, 9_3_0, 1_7_3_4_7, 1_6, 2], [2_0_0_9_1, 6_2_9, 9_4, 8_2_7_8_6, 5_8, 4_9_0, 2_0, 1_5_2_8, 8_4, 5_3_9_0_5, 3_4_4, 8_0_5_9_2, 1_1_0_1_2_8, 1_8_8_2_2, 5_2_6_7, 1_3_0_6, 6_2, 1_5_2_5_3_7, 3_0_8, 7_9_9_7, 4_0_1, 1_2_4_4_2_7, 5_4_9, 3_5_4_4_2, 2_2_5, 1_0_9, 1_5_0_5_5, 2_5_7_4_8, 1_4_7, 7_1_1_9, 4_3_7_1_2, 3_4, 7_6_7, 1_3_5_3_6_6, 1_8, 1_6, 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], [5_9_2, 6_3_7_8_4, 1_1_9_4_6_6, 1_7, 1_4_7_8_0_8, 8_8_2_1_4, 1_8, 6_5_6, 8_1, 3_2, 3_2_9_6, 1_0_2_8_0, 1_6, 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, 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, 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, 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, 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, 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=__a , model_name="microsoft/xprophetnet-large-wiki100-cased" , revision="1acad1643ddd54a44df6a1b797ada8373685d90e" , )
283
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType, logging SCREAMING_SNAKE_CASE_: Optional[Any] =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: List[Any] ={ 'deepmind/language-perceiver': 'https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json', # See all Perceiver models at https://huggingface.co/models?filter=perceiver } class __A ( UpperCamelCase__ ): a__ : List[Any] = """perceiver""" def __init__(self : Optional[int] , __a : Tuple=256 , __a : Optional[Any]=1280 , __a : Optional[int]=768 , __a : Any=1 , __a : List[str]=26 , __a : Dict=8 , __a : List[Any]=8 , __a : Tuple=None , __a : List[str]=None , __a : Optional[int]="kv" , __a : Union[str, Any]=1 , __a : List[str]=1 , __a : List[Any]="gelu" , __a : List[str]=0.1 , __a : str=0.02 , __a : List[str]=1E-12 , __a : Optional[int]=True , __a : Tuple=262 , __a : Dict=2048 , __a : int=56 , __a : Optional[int]=[368, 496] , __a : Any=16 , __a : Optional[Any]=1920 , __a : Any=16 , __a : str=[1, 16, 224, 224] , **__a : Any , ): super().__init__(**__a ) UpperCAmelCase_ = num_latents UpperCAmelCase_ = d_latents UpperCAmelCase_ = d_model UpperCAmelCase_ = num_blocks UpperCAmelCase_ = num_self_attends_per_block UpperCAmelCase_ = num_self_attention_heads UpperCAmelCase_ = num_cross_attention_heads UpperCAmelCase_ = qk_channels UpperCAmelCase_ = v_channels UpperCAmelCase_ = cross_attention_shape_for_attention UpperCAmelCase_ = self_attention_widening_factor UpperCAmelCase_ = cross_attention_widening_factor UpperCAmelCase_ = hidden_act UpperCAmelCase_ = attention_probs_dropout_prob UpperCAmelCase_ = initializer_range UpperCAmelCase_ = layer_norm_eps UpperCAmelCase_ = use_query_residual # masked language modeling attributes UpperCAmelCase_ = vocab_size UpperCAmelCase_ = max_position_embeddings # image classification attributes UpperCAmelCase_ = image_size # flow attributes UpperCAmelCase_ = train_size # multimodal autoencoding attributes UpperCAmelCase_ = num_frames UpperCAmelCase_ = audio_samples_per_frame UpperCAmelCase_ = samples_per_patch UpperCAmelCase_ = output_shape class __A ( UpperCamelCase__ ): @property def _lowercase (self : Dict ): if self.task == "multiple-choice": UpperCAmelCase_ = {0: "batch", 1: "choice", 2: "sequence"} else: UpperCAmelCase_ = {0: "batch", 1: "sequence"} return OrderedDict( [ ("inputs", dynamic_axis), ("attention_mask", dynamic_axis), ] ) @property def _lowercase (self : Optional[Any] ): return 1E-4 def _lowercase (self : Union[str, Any] , __a : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , __a : int = -1 , __a : int = -1 , __a : int = -1 , __a : bool = False , __a : Optional[TensorType] = None , __a : int = 3 , __a : int = 40 , __a : int = 40 , ): # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified if isinstance(__a , __a ): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCAmelCase_ = compute_effective_axis_dimension( __a , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCAmelCase_ = preprocessor.num_special_tokens_to_add(__a ) UpperCAmelCase_ = compute_effective_axis_dimension( __a , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__a ) # Generate dummy inputs according to compute batch and sequence UpperCAmelCase_ = [" ".join(["a"] ) * seq_length] * batch_size UpperCAmelCase_ = dict(preprocessor(__a , return_tensors=__a ) ) UpperCAmelCase_ = inputs.pop("input_ids" ) return inputs elif isinstance(__a , __a ) and preprocessor.model_input_names[0] == "pixel_values": # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCAmelCase_ = compute_effective_axis_dimension(__a , fixed_dimension=OnnxConfig.default_fixed_batch ) UpperCAmelCase_ = self._generate_dummy_images(__a , __a , __a , __a ) UpperCAmelCase_ = dict(preprocessor(images=__a , return_tensors=__a ) ) UpperCAmelCase_ = inputs.pop("pixel_values" ) return inputs else: raise ValueError( "Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor." )
78
0
"""simple docstring""" import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils""")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class A( unittest.TestCase ): """simple docstring""" def _UpperCamelCase( self ) -> Optional[Any]: """simple docstring""" _UpperCamelCase :Optional[int] = 0 def _UpperCamelCase( self ) -> Any: """simple docstring""" _UpperCamelCase :int = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(__a , __a ) def _UpperCamelCase( self ) -> List[str]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: _UpperCamelCase :Optional[int] = Path(__a ) / '''preprocessor_config.json''' _UpperCamelCase :int = Path(__a ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(__a , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(__a , '''w''' ) ) _UpperCamelCase :Any = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _UpperCamelCase( self ) -> Optional[int]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: _UpperCamelCase :Optional[int] = Path(__a ) / '''preprocessor_config.json''' _UpperCamelCase :List[Any] = Path(__a ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(__a , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(__a , '''w''' ) ) _UpperCamelCase :Optional[Any] = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _UpperCamelCase( self ) -> Optional[int]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: _UpperCamelCase :Optional[int] = CLIPConfig() # Create a dummy config file with image_proceesor_type _UpperCamelCase :str = Path(__a ) / '''preprocessor_config.json''' _UpperCamelCase :List[str] = Path(__a ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(__a , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(__a , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally _UpperCamelCase :int = AutoImageProcessor.from_pretrained(__a ).to_dict() config_dict.pop('''image_processor_type''' ) _UpperCamelCase :str = CLIPImageProcessor(**__a ) # save in new folder model_config.save_pretrained(__a ) config.save_pretrained(__a ) _UpperCamelCase :Any = AutoImageProcessor.from_pretrained(__a ) # make sure private variable is not incorrectly saved _UpperCamelCase :Tuple = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(__a , __a ) def _UpperCamelCase( self ) -> List[str]: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: _UpperCamelCase :Any = Path(__a ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(__a , '''w''' ) , ) _UpperCamelCase :Optional[int] = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _UpperCamelCase( self ) -> List[Any]: """simple docstring""" with self.assertRaisesRegex( __a , '''clip-base is not a local folder and is not a valid model identifier''' ): _UpperCamelCase :List[Any] = AutoImageProcessor.from_pretrained('''clip-base''' ) def _UpperCamelCase( self ) -> Optional[int]: """simple docstring""" with self.assertRaisesRegex( __a , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): _UpperCamelCase :Dict = AutoImageProcessor.from_pretrained(__a , revision='''aaaaaa''' ) def _UpperCamelCase( self ) -> int: """simple docstring""" with self.assertRaisesRegex( __a , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): _UpperCamelCase :int = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def _UpperCamelCase( self ) -> str: """simple docstring""" with self.assertRaises(__a ): _UpperCamelCase :int = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(__a ): _UpperCamelCase :List[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=__a ) _UpperCamelCase :Union[str, Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(__a ) _UpperCamelCase :Tuple = AutoImageProcessor.from_pretrained(__a , trust_remote_code=__a ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def _UpperCamelCase( self ) -> List[Any]: """simple docstring""" try: AutoConfig.register('''custom''' , __a ) AutoImageProcessor.register(__a , __a ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__a ): AutoImageProcessor.register(__a , __a ) with tempfile.TemporaryDirectory() as tmpdirname: _UpperCamelCase :Optional[int] = Path(__a ) / '''preprocessor_config.json''' _UpperCamelCase :Union[str, Any] = Path(__a ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(__a , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(__a , '''w''' ) ) _UpperCamelCase :List[Any] = CustomImageProcessor.from_pretrained(__a ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(__a ) _UpperCamelCase :int = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def _UpperCamelCase( self ) -> Tuple: """simple docstring""" class A( UpperCamelCase__ ): """simple docstring""" A = True try: AutoConfig.register('''custom''' , __a ) AutoImageProcessor.register(__a , __a ) # If remote code is not set, the default is to use local _UpperCamelCase :List[Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. _UpperCamelCase :int = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub _UpperCamelCase :List[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(__a , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
355
'''simple docstring''' import requests def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : str ) -> None: '''simple docstring''' UpperCAmelCase_ = {"Content-Type": "application/json"} UpperCAmelCase_ = requests.post(snake_case_ , json={"text": message_body} , headers=snake_case_ ) if response.status_code != 2_00: UpperCAmelCase_ = ( "Request to slack returned an error " f"""{response.status_code}, the response is:\n{response.text}""" ) raise ValueError(snake_case_ ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message('<YOUR MESSAGE BODY>', '<SLACK CHANNEL URL>')
78
0
'''simple docstring''' import collections import inspect import unittest from transformers import FocalNetConfig 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_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, ) from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class SCREAMING_SNAKE_CASE__ : """simple docstring""" def __init__( self , A , A=13 , A=32 , A=2 , A=3 , A=16 , A=[32, 64, 1_28] , A=[1, 2, 1] , A=[2, 2, 4] , A=2 , A=2.0 , A=True , A=0.0 , A=0.0 , A=0.1 , A="gelu" , A=False , A=True , A=0.02 , A=1e-5 , A=True , A=None , A=True , A=10 , A=8 , A=["stage1", "stage2"] , A=[1, 2] , ) -> List[str]: A: int = parent A: Optional[Any] = batch_size A: Any = image_size A: Dict = patch_size A: Optional[int] = num_channels A: Union[str, Any] = embed_dim A: str = hidden_sizes A: Dict = depths A: Union[str, Any] = num_heads A: int = window_size A: Dict = mlp_ratio A: List[Any] = qkv_bias A: List[str] = hidden_dropout_prob A: Dict = attention_probs_dropout_prob A: List[str] = drop_path_rate A: str = hidden_act A: Dict = use_absolute_embeddings A: Union[str, Any] = patch_norm A: Any = layer_norm_eps A: Dict = initializer_range A: str = is_training A: int = scope A: int = use_labels A: Any = type_sequence_label_size A: int = encoder_stride A: Union[str, Any] = out_features A: Tuple = out_indices def a__ ( self ) -> Dict: A: str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A: List[Any] = None if self.use_labels: A: Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A: int = self.get_config() return config, pixel_values, labels def a__ ( self ) -> Optional[Any]: return FocalNetConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , hidden_sizes=self.hidden_sizes , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def a__ ( self , A , A , A ) -> int: A: Dict = FocalNetModel(config=__a ) model.to(__a ) model.eval() A: int = model(__a ) A: Optional[Any] = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) A: int = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def a__ ( self , A , A , A ) -> List[str]: A: Dict = FocalNetBackbone(config=__a ) model.to(__a ) model.eval() A: List[Any] = model(__a ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.image_size, 8, 8] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[:-1] ) # verify backbone works with out_features=None A: Tuple = None A: Optional[int] = FocalNetBackbone(config=__a ) model.to(__a ) model.eval() A: Optional[int] = model(__a ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.image_size * 2, 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def a__ ( self , A , A , A ) -> Tuple: A: Dict = FocalNetForMaskedImageModeling(config=__a ) model.to(__a ) model.eval() A: Union[str, Any] = model(__a ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images A: Union[str, Any] = 1 A: int = FocalNetForMaskedImageModeling(__a ) model.to(__a ) model.eval() A: Optional[int] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A: Dict = model(__a ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def a__ ( self , A , A , A ) -> int: A: int = self.type_sequence_label_size A: int = FocalNetForImageClassification(__a ) model.to(__a ) model.eval() A: str = model(__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images A: Optional[int] = 1 A: int = FocalNetForImageClassification(__a ) model.to(__a ) model.eval() A: Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A: Optional[int] = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a__ ( self ) -> Optional[int]: A: Tuple = self.prepare_config_and_inputs() A , A , A: Union[str, Any] = config_and_inputs A: Optional[int] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): """simple docstring""" A__ : Tuple = ( ( FocalNetModel, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetBackbone, ) if is_torch_available() else () ) A__ : List[str] = ( {"""feature-extraction""": FocalNetModel, """image-classification""": FocalNetForImageClassification} if is_torch_available() else {} ) A__ : Union[str, Any] = False A__ : str = False A__ : List[str] = False A__ : int = False A__ : Optional[Any] = False def a__ ( self ) -> Optional[int]: A: Optional[Any] = FocalNetModelTester(self ) A: str = ConfigTester(self , config_class=__a , embed_dim=37 , has_text_modality=__a ) def a__ ( self ) -> Optional[Any]: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def a__ ( self ) -> Union[str, Any]: return def a__ ( self ) -> Union[str, Any]: A: List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def a__ ( self ) -> Dict: A: List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*__a ) def a__ ( self ) -> Union[str, Any]: A: List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__a ) def a__ ( self ) -> List[str]: A: str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a ) @unittest.skip(reason="""FocalNet does not use inputs_embeds""" ) def a__ ( self ) -> str: pass @unittest.skip(reason="""FocalNet does not use feedforward chunking""" ) def a__ ( self ) -> List[Any]: pass def a__ ( self ) -> Tuple: A , A: List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: A: Dict = model_class(__a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) A: Any = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__a , nn.Linear ) ) def a__ ( self ) -> Tuple: A , A: int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: A: Optional[int] = model_class(__a ) A: List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A: List[Any] = [*signature.parameters.keys()] A: List[str] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __a ) def a__ ( self , A , A , A , A ) -> int: A: Any = model_class(__a ) model.to(__a ) model.eval() with torch.no_grad(): A: List[str] = model(**self._prepare_for_class(__a , __a ) ) A: List[Any] = outputs.hidden_states A: Dict = getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(__a ) , __a ) # FocalNet has a different seq_length A: Any = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) A: List[Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) A: Any = outputs.reshaped_hidden_states self.assertEqual(len(__a ) , __a ) A , A , A , A: Dict = reshaped_hidden_states[0].shape A: Tuple = ( reshaped_hidden_states[0].view(__a , __a , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def a__ ( self ) -> Union[str, Any]: A , A: List[str] = self.model_tester.prepare_config_and_inputs_for_common() A: Tuple = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes[:-1]: A: List[Any] = True self.check_hidden_states_output(__a , __a , __a , __a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A: int = True self.check_hidden_states_output(__a , __a , __a , __a ) def a__ ( self ) -> int: A , A: int = self.model_tester.prepare_config_and_inputs_for_common() A: int = 3 A: List[str] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) A: List[Any] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) A: Optional[Any] = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) A: Optional[int] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes[:-1]: A: Union[str, Any] = True self.check_hidden_states_output(__a , __a , __a , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A: str = True self.check_hidden_states_output(__a , __a , __a , (padded_height, padded_width) ) @slow def a__ ( self ) -> Any: for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A: str = FocalNetModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def a__ ( self ) -> Any: A , A: Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() A: Optional[int] = _config_zero_init(__a ) for model_class in self.all_model_classes: A: Tuple = model_class(config=__a ) for name, param in model.named_parameters(): if "embeddings" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f'Parameter {name} of model {model_class} seems not properly initialized' , ) @require_vision @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): """simple docstring""" @cached_property def a__ ( self ) -> List[Any]: # TODO update organization return AutoImageProcessor.from_pretrained("""microsoft/focalnet-tiny""" ) if is_vision_available() else None @slow def a__ ( self ) -> Optional[Any]: A: Tuple = FocalNetForImageClassification.from_pretrained("""microsoft/focalnet-tiny""" ).to(__a ) A: Optional[Any] = self.default_image_processor A: List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) A: Optional[int] = image_processor(images=__a , return_tensors="""pt""" ).to(__a ) # forward pass with torch.no_grad(): A: List[Any] = model(**__a ) # verify the logits A: List[Any] = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape , __a ) A: int = torch.tensor([0.2166, -0.4368, 0.2191] ).to(__a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __a , atol=1e-4 ) ) self.assertTrue(outputs.logits.argmax(dim=-1 ).item() , 2_81 ) @require_torch class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" A__ : Tuple = (FocalNetBackbone,) if is_torch_available() else () A__ : int = FocalNetConfig A__ : List[Any] = False def a__ ( self ) -> Dict: A: Any = FocalNetModelTester(self )
135
'''simple docstring''' from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging SCREAMING_SNAKE_CASE_: Optional[int] =logging.get_logger(__name__) # pylint: disable=invalid-name class __A ( UpperCamelCase__ ): def __init__(self : Any , __a : CLIPSegForImageSegmentation , __a : CLIPSegProcessor , __a : AutoencoderKL , __a : CLIPTextModel , __a : CLIPTokenizer , __a : UNetaDConditionModel , __a : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __a : StableDiffusionSafetyChecker , __a : CLIPImageProcessor , ): super().__init__() if hasattr(scheduler.config , "steps_offset" ) and scheduler.config.steps_offset != 1: UpperCAmelCase_ = ( f"""The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`""" f""" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure """ "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1" , "1.0.0" , __a , standard_warn=__a ) UpperCAmelCase_ = dict(scheduler.config ) UpperCAmelCase_ = 1 UpperCAmelCase_ = FrozenDict(__a ) if hasattr(scheduler.config , "skip_prk_steps" ) and scheduler.config.skip_prk_steps is False: UpperCAmelCase_ = ( f"""The configuration file of this scheduler: {scheduler} has not set the configuration""" " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" " Hub, it would be very nice if you could open a Pull request for the" " `scheduler/scheduler_config.json` file" ) deprecate("skip_prk_steps not set" , "1.0.0" , __a , standard_warn=__a ) UpperCAmelCase_ = dict(scheduler.config ) UpperCAmelCase_ = True UpperCAmelCase_ = FrozenDict(__a ) if safety_checker is None: logger.warning( f"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure""" " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." ) self.register_modules( segmentation_model=__a , segmentation_processor=__a , vae=__a , text_encoder=__a , tokenizer=__a , unet=__a , scheduler=__a , safety_checker=__a , feature_extractor=__a , ) def _lowercase (self : str , __a : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCAmelCase_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__a ) def _lowercase (self : int ): self.enable_attention_slicing(__a ) def _lowercase (self : Optional[Any] ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) UpperCAmelCase_ = torch.device("cuda" ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(__a , __a ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _lowercase (self : Optional[int] ): if self.device != torch.device("meta" ) or not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(__a , "_hf_hook" ) and hasattr(module._hf_hook , "execution_device" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__(self : Dict , __a : Union[str, List[str]] , __a : Union[torch.FloatTensor, PIL.Image.Image] , __a : str , __a : int = 512 , __a : int = 512 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : int , ): UpperCAmelCase_ = self.segmentation_processor( text=[text] , images=[image] , padding="max_length" , return_tensors="pt" ).to(self.device ) UpperCAmelCase_ = self.segmentation_model(**__a ) UpperCAmelCase_ = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() UpperCAmelCase_ = self.numpy_to_pil(__a )[0].resize(image.size ) # Run inpainting pipeline with the generated mask UpperCAmelCase_ = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=__a , image=__a , mask_image=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , )
78
0
import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def _lowerCAmelCase ( ) -> Any: """simple docstring""" raise RuntimeError("""CUDA out of memory.""" ) class _UpperCamelCase ( nn.Module ): """simple docstring""" def __init__( self ) -> str: super().__init__() A = nn.Linear(3 , 4 ) A = nn.BatchNormad(4 ) A = nn.Linear(4 , 5 ) def _UpperCAmelCase ( self , a__ ) -> List[Any]: return self.lineara(self.batchnorm(self.lineara(__a ) ) ) class _UpperCamelCase ( unittest.TestCase ): """simple docstring""" def _UpperCAmelCase ( self ) -> List[Any]: A = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(a__ ): nonlocal batch_sizes batch_sizes.append(__a ) if batch_size != 8: raise_fake_out_of_memory() mock_training_loop_function() self.assertListEqual(__a , [128, 64, 32, 16, 8] ) def _UpperCAmelCase ( self ) -> Union[str, Any]: A = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(a__ , a__ ): nonlocal batch_sizes batch_sizes.append(__a ) if batch_size != 8: raise_fake_out_of_memory() return batch_size, arga A , A = mock_training_loop_function("""hello""" ) self.assertListEqual(__a , [128, 64, 32, 16, 8] ) self.assertListEqual([bs, arga] , [8, """hello"""] ) def _UpperCAmelCase ( self ) -> Dict: @find_executable_batch_size(starting_batch_size=0 ) def mock_training_loop_function(a__ ): pass with self.assertRaises(__a ) as cm: mock_training_loop_function() self.assertIn("""No executable batch size found, reached zero.""" , cm.exception.args[0] ) def _UpperCAmelCase ( self ) -> Tuple: @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(a__ ): if batch_size > 0: raise_fake_out_of_memory() pass with self.assertRaises(__a ) as cm: mock_training_loop_function() self.assertIn("""No executable batch size found, reached zero.""" , cm.exception.args[0] ) def _UpperCAmelCase ( self ) -> Optional[int]: @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(a__ , a__ , a__ ): if batch_size != 8: raise raise_fake_out_of_memory() with self.assertRaises(__a ) as cm: mock_training_loop_function(128 , """hello""" , """world""" ) self.assertIn("""Batch size was passed into `f`""" , cm.exception.args[0] ) self.assertIn("""`f(arg1='hello', arg2='world')""" , cm.exception.args[0] ) def _UpperCAmelCase ( self ) -> List[Any]: @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(a__ ): raise ValueError("""Oops, we had an error!""" ) with self.assertRaises(__a ) as cm: mock_training_loop_function() self.assertIn("""Oops, we had an error!""" , cm.exception.args[0] ) @require_cuda def _UpperCAmelCase ( self ) -> Tuple: A = torch.cuda.memory_allocated() A = ModelForTest() model.cuda() self.assertGreater(torch.cuda.memory_allocated() , __a ) A = release_memory(__a ) self.assertEqual(torch.cuda.memory_allocated() , __a )
641
'''simple docstring''' def lowerCAmelCase_ ( snake_case_ : int ) -> bool: '''simple docstring''' if number < 0: raise ValueError("number must not be negative" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
78
0
"""simple docstring""" from torch import nn class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : int ): super().__init__() lowerCamelCase__ = class_size lowerCamelCase__ = embed_size # self.mlp1 = nn.Linear(embed_size, embed_size) # self.mlp2 = (nn.Linear(embed_size, class_size)) lowerCamelCase__ = nn.Linear(__a , __a ) def __UpperCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] ): # hidden_state = nn.functional.relu(self.mlp1(hidden_state)) # hidden_state = self.mlp2(hidden_state) lowerCamelCase__ = self.mlp(__a ) return logits
129
'''simple docstring''' from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class __A : a__ : int a__ : TreeNode | None = None a__ : TreeNode | None = None SCREAMING_SNAKE_CASE_: Union[str, Any] =namedtuple('CoinsDistribResult', 'moves excess') def lowerCAmelCase_ ( snake_case_ : TreeNode | None ) -> int: '''simple docstring''' if root is None: return 0 # Validation def count_nodes(snake_case_ : TreeNode | None ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(snake_case_ : TreeNode | None ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(snake_case_ ) != count_coins(snake_case_ ): raise ValueError("The nodes number should be same as the number of coins" ) # Main calculation def get_distrib(snake_case_ : TreeNode | None ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) UpperCAmelCase_ , UpperCAmelCase_ = get_distrib(node.left ) UpperCAmelCase_ , UpperCAmelCase_ = get_distrib(node.right ) UpperCAmelCase_ = 1 - left_distrib_excess UpperCAmelCase_ = 1 - right_distrib_excess UpperCAmelCase_ = ( left_distrib_moves + right_distrib_moves + abs(snake_case_ ) + abs(snake_case_ ) ) UpperCAmelCase_ = node.data - coins_to_left - coins_to_right return CoinsDistribResult(snake_case_ , snake_case_ ) return get_distrib(snake_case_ )[0] if __name__ == "__main__": import doctest doctest.testmod()
78
0
"""simple docstring""" from __future__ import annotations def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> None: if (direction == 1 and array[indexa] > array[indexa]) or ( direction == 0 and array[indexa] < array[indexa] ): __lowerCAmelCase , __lowerCAmelCase: Dict = array[indexa], array[indexa] def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> None: if length > 1: __lowerCAmelCase: Tuple = int(length / 2 ) for i in range(snake_case_ , low + middle ): comp_and_swap(snake_case_ , snake_case_ , i + middle , snake_case_ ) bitonic_merge(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) bitonic_merge(snake_case_ , low + middle , snake_case_ , snake_case_ ) def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> None: if length > 1: __lowerCAmelCase: List[str] = int(length / 2 ) bitonic_sort(snake_case_ , snake_case_ , snake_case_ , 1 ) bitonic_sort(snake_case_ , low + middle , snake_case_ , 0 ) bitonic_merge(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) if __name__ == "__main__": __A = input("Enter numbers separated by a comma:\n").strip() __A = [int(item.strip()) for item in user_input.split(",")] bitonic_sort(unsorted, 0, len(unsorted), 1) print("\nSorted array in ascending order is: ", end="") print(*unsorted, sep=", ") bitonic_merge(unsorted, 0, len(unsorted), 0) print("Sorted array in descending order is: ", end="") print(*unsorted, sep=", ")
346
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) SCREAMING_SNAKE_CASE_: int =logging.getLogger() def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = argparse.ArgumentParser() parser.add_argument("-f" ) UpperCAmelCase_ = parser.parse_args() return args.f def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> str: '''simple docstring''' UpperCAmelCase_ = {} UpperCAmelCase_ = os.path.join(snake_case_ , "all_results.json" ) if os.path.exists(snake_case_ ): with open(snake_case_ , "r" ) as f: UpperCAmelCase_ = json.load(snake_case_ ) else: raise ValueError(f"""can't find {path}""" ) return results def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = torch.cuda.is_available() and torch_device == "cuda" return is_using_cuda and is_apex_available() SCREAMING_SNAKE_CASE_: Any =logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class __A ( UpperCamelCase__ ): @classmethod def _lowercase (cls : Any ): # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU UpperCAmelCase_ = tempfile.mkdtemp() UpperCAmelCase_ = os.path.join(cls.tmpdir , "default_config.yml" ) write_basic_config(save_location=cls.configPath ) UpperCAmelCase_ = ["accelerate", "launch", "--config_file", cls.configPath] @classmethod def _lowercase (cls : int ): shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking """.split() if is_cuda_and_apex_available(): testargs.append("--fp16" ) run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "glue_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking """.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertLess(result["perplexity"] , 100 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "clm_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertLess(result["perplexity"] , 42 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "mlm_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Optional[Any] ): # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu UpperCAmelCase_ = 7 if get_gpu_count() > 1 else 2 UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) self.assertLess(result["train_loss"] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "ner_no_trainer" ) ) ) @unittest.skip(reason="Fix me @muellerzr" ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : int ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result["eval_f1"] , 28 ) self.assertGreaterEqual(result["eval_exact"] , 28 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "qa_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : str ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_accuracy"] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__a , "swag_no_trainer" ) ) ) @slow @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Optional[int] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_rouge1"] , 10 ) self.assertGreaterEqual(result["eval_rouge2"] , 2 ) self.assertGreaterEqual(result["eval_rougeL"] , 7 ) self.assertGreaterEqual(result["eval_rougeLsum"] , 7 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "summarization_no_trainer" ) ) ) @slow @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : List[str] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_bleu"] , 30 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "translation_no_trainer" ) ) ) @slow def _lowercase (self : Dict ): UpperCAmelCase_ = logging.StreamHandler(sys.stdout ) logger.addHandler(__a ) UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_overall_accuracy"] , 0.10 ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Any ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 """.split() if is_cuda_and_apex_available(): testargs.append("--fp16" ) run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) # The base model scores a 25% self.assertGreaterEqual(result["eval_accuracy"] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__a , "step_1" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "image_classification_no_trainer" ) ) )
78
0
import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def lowercase__ ( _UpperCamelCase) -> Union[str, Any]: """simple docstring""" UpperCamelCase = FileLock(str(tmpdir / 'foo.lock')) UpperCamelCase = FileLock(str(tmpdir / 'foo.lock')) UpperCamelCase = 0.0_1 with locka.acquire(): with pytest.raises(snake_case_): UpperCamelCase = time.time() locka.acquire(snake_case_) assert time.time() - _start > timeout def lowercase__ ( _UpperCamelCase) -> List[str]: """simple docstring""" UpperCamelCase = 'a' * 10_00 + '.lock' UpperCamelCase = FileLock(str(tmpdir / filename)) assert locka._lock_file.endswith('.lock') assert not locka._lock_file.endswith(snake_case_) assert len(os.path.basename(locka._lock_file)) <= 2_55 UpperCamelCase = FileLock(tmpdir / filename) with locka.acquire(): with pytest.raises(snake_case_): locka.acquire(0)
280
'''simple docstring''' import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP SCREAMING_SNAKE_CASE_: Any =False try: SCREAMING_SNAKE_CASE_: Optional[Any] =_is_package_available('google.colab') except ModuleNotFoundError: pass @input.register class __A : def __init__(self : int , __a : str = None , __a : list = [] ): UpperCAmelCase_ = 0 UpperCAmelCase_ = choices UpperCAmelCase_ = prompt if sys.platform == "win32": UpperCAmelCase_ = "*" else: UpperCAmelCase_ = "➔ " def _lowercase (self : Union[str, Any] , __a : Optional[int] , __a : str = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 32 , __a ) else: forceWrite(self.choices[index] , __a ) def _lowercase (self : Any , __a : int ): if index == self.position: forceWrite(f""" {self.arrow_char} """ ) self.write_choice(__a ) else: forceWrite(f""" {self.choices[index]}""" ) reset_cursor() def _lowercase (self : Optional[Any] , __a : Direction , __a : int = 1 ): UpperCAmelCase_ = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(__a ) move_cursor(__a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP["up"] ) def _lowercase (self : Dict ): self.move_direction(Direction.UP ) @input.mark(KEYMAP["down"] ) def _lowercase (self : Any ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP["newline"] ) def _lowercase (self : Optional[Any] ): move_cursor(len(self.choices ) - self.position , "DOWN" ) return self.position @input.mark(KEYMAP["interrupt"] ) def _lowercase (self : str ): move_cursor(len(self.choices ) - self.position , "DOWN" ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(__a )] for number in range(10 )] ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = int(chr(self.current_selection ) ) UpperCAmelCase_ = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , __a ) else: return else: return def _lowercase (self : Optional[Any] , __a : int = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , "\n" ) if in_colab: forceWrite("Please input a choice index (starting from 0), and press enter" , "\n" ) else: forceWrite("Please select a choice using the arrow or number keys, and selecting with enter" , "\n" ) UpperCAmelCase_ = default_choice for i in range(len(self.choices ) ): self.print_choice(__a ) forceWrite("\n" ) move_cursor(len(self.choices ) - self.position , "UP" ) with cursor.hide(): while True: if in_colab: try: UpperCAmelCase_ = int(builtins.input() ) except ValueError: UpperCAmelCase_ = default_choice else: UpperCAmelCase_ = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , "UP" ) clear_line() self.write_choice(__a , "\n" ) return choice
78
0
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase : Optional[int] = logging.get_logger(__name__) __UpperCamelCase : List[str] = { 'asapp/sew-d-tiny-100k': 'https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json', # See all SEW-D models at https://huggingface.co/models?filter=sew-d } class _UpperCamelCase ( UpperCamelCase__ ): '''simple docstring''' a_ : Optional[Any] = """sew-d""" def __init__( self : Union[str, Any] , _lowerCamelCase : int=3_2 , _lowerCamelCase : int=7_6_8 , _lowerCamelCase : int=1_2 , _lowerCamelCase : str=1_2 , _lowerCamelCase : List[Any]=3_0_7_2 , _lowerCamelCase : Optional[Any]=2 , _lowerCamelCase : Optional[Any]=5_1_2 , _lowerCamelCase : Tuple=2_5_6 , _lowerCamelCase : Optional[int]=True , _lowerCamelCase : int=True , _lowerCamelCase : Dict=("p2c", "c2p") , _lowerCamelCase : Dict="layer_norm" , _lowerCamelCase : Tuple="gelu_python" , _lowerCamelCase : List[str]=0.1 , _lowerCamelCase : Any=0.1 , _lowerCamelCase : Union[str, Any]=0.1 , _lowerCamelCase : Union[str, Any]=0.0 , _lowerCamelCase : Any=0.1 , _lowerCamelCase : Any=0.02 , _lowerCamelCase : int=1E-7 , _lowerCamelCase : Tuple=1E-5 , _lowerCamelCase : Union[str, Any]="group" , _lowerCamelCase : str="gelu" , _lowerCamelCase : Tuple=(6_4, 1_2_8, 1_2_8, 1_2_8, 1_2_8, 2_5_6, 2_5_6, 2_5_6, 2_5_6, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , _lowerCamelCase : Optional[int]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , _lowerCamelCase : Optional[Any]=(1_0, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , _lowerCamelCase : int=False , _lowerCamelCase : List[Any]=1_2_8 , _lowerCamelCase : List[Any]=1_6 , _lowerCamelCase : Optional[Any]=True , _lowerCamelCase : Dict=0.05 , _lowerCamelCase : List[Any]=1_0 , _lowerCamelCase : Any=2 , _lowerCamelCase : Tuple=0.0 , _lowerCamelCase : Dict=1_0 , _lowerCamelCase : Tuple=0 , _lowerCamelCase : Optional[Any]="mean" , _lowerCamelCase : Optional[int]=False , _lowerCamelCase : Dict=False , _lowerCamelCase : Any=2_5_6 , _lowerCamelCase : str=0 , _lowerCamelCase : Optional[Any]=1 , _lowerCamelCase : Any=2 , **_lowerCamelCase : Any , ): '''simple docstring''' super().__init__(**__a , pad_token_id=__a , bos_token_id=__a , eos_token_id=__a ) __lowerCamelCase : Optional[Any] = hidden_size __lowerCamelCase : Optional[Any] = feat_extract_norm __lowerCamelCase : int = feat_extract_activation __lowerCamelCase : Dict = list(__a ) __lowerCamelCase : Optional[Any] = list(__a ) __lowerCamelCase : List[str] = list(__a ) __lowerCamelCase : str = conv_bias __lowerCamelCase : Tuple = num_conv_pos_embeddings __lowerCamelCase : Optional[int] = num_conv_pos_embedding_groups __lowerCamelCase : str = len(self.conv_dim ) __lowerCamelCase : Optional[int] = num_hidden_layers __lowerCamelCase : Any = intermediate_size __lowerCamelCase : Any = squeeze_factor __lowerCamelCase : str = max_position_embeddings __lowerCamelCase : Optional[int] = position_buckets __lowerCamelCase : Optional[int] = share_att_key __lowerCamelCase : int = relative_attention __lowerCamelCase : Union[str, Any] = norm_rel_ebd __lowerCamelCase : str = list(__a ) __lowerCamelCase : Union[str, Any] = hidden_act __lowerCamelCase : int = num_attention_heads __lowerCamelCase : Any = hidden_dropout __lowerCamelCase : List[str] = attention_dropout __lowerCamelCase : Optional[Any] = activation_dropout __lowerCamelCase : int = feat_proj_dropout __lowerCamelCase : Any = final_dropout __lowerCamelCase : int = layer_norm_eps __lowerCamelCase : Optional[Any] = feature_layer_norm_eps __lowerCamelCase : str = initializer_range __lowerCamelCase : List[Any] = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect.""" """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,""" F"""but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)""" F"""= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.""" ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __lowerCamelCase : str = apply_spec_augment __lowerCamelCase : Tuple = mask_time_prob __lowerCamelCase : Tuple = mask_time_length __lowerCamelCase : Any = mask_time_min_masks __lowerCamelCase : int = mask_feature_prob __lowerCamelCase : int = mask_feature_length __lowerCamelCase : Optional[int] = mask_feature_min_masks # ctc loss __lowerCamelCase : int = ctc_loss_reduction __lowerCamelCase : Optional[Any] = ctc_zero_infinity # sequence classification __lowerCamelCase : Any = use_weighted_layer_sum __lowerCamelCase : Tuple = classifier_proj_size @property def _snake_case ( self : str ): '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
519
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE_: Optional[int] ={'configuration_beit': ['BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BeitConfig', 'BeitOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[int] =['BeitFeatureExtractor'] SCREAMING_SNAKE_CASE_: int =['BeitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[int] =[ 'BEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BeitForImageClassification', 'BeitForMaskedImageModeling', 'BeitForSemanticSegmentation', 'BeitModel', 'BeitPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: int =[ 'FlaxBeitForImageClassification', 'FlaxBeitForMaskedImageModeling', 'FlaxBeitModel', 'FlaxBeitPreTrainedModel', ] if TYPE_CHECKING: from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_beit import BeitFeatureExtractor from .image_processing_beit import BeitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_beit import ( BEIT_PRETRAINED_MODEL_ARCHIVE_LIST, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, BeitPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_beit import ( FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel, FlaxBeitPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_: Dict =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
78
0
"""simple docstring""" import qiskit def lowerCAmelCase_( lowercase_ : int , lowercase_ : int ) -> qiskit.result.counts.Counts: _lowerCamelCase = qiskit.Aer.get_backend('''aer_simulator''' ) # Create a Quantum Circuit acting on the q register _lowerCamelCase = qiskit.QuantumCircuit(snake_case_ , snake_case_ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator _lowerCamelCase = qiskit.execute(snake_case_ , snake_case_ , shots=10_00 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(snake_case_ ) if __name__ == "__main__": print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
661
'''simple docstring''' import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed SCREAMING_SNAKE_CASE_: Any ={ 'distilbert': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), 'roberta': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), 'bert': (BertConfig, BertForMaskedLM, BertTokenizer), 'gpt2': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def lowerCAmelCase_ ( snake_case_ : Any ) -> str: '''simple docstring''' assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def lowerCAmelCase_ ( snake_case_ : Optional[Any] , snake_case_ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' if args.student_type == "roberta": UpperCAmelCase_ = False elif args.student_type == "gpt2": UpperCAmelCase_ = False def lowerCAmelCase_ ( snake_case_ : Optional[int] , snake_case_ : List[Any] ) -> Tuple: '''simple docstring''' if args.student_type == "roberta": UpperCAmelCase_ = False def lowerCAmelCase_ ( ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = argparse.ArgumentParser(description="Training" ) parser.add_argument("--force" , action="store_true" , help="Overwrite dump_path if it already exists." ) parser.add_argument( "--dump_path" , type=snake_case_ , required=snake_case_ , help="The output directory (log, checkpoints, parameters, etc.)" ) parser.add_argument( "--data_file" , type=snake_case_ , required=snake_case_ , help="The binarized file (tokenized + tokens_to_ids) and grouped by sequence." , ) parser.add_argument( "--student_type" , type=snake_case_ , choices=["distilbert", "roberta", "gpt2"] , required=snake_case_ , help="The student type (DistilBERT, RoBERTa)." , ) parser.add_argument("--student_config" , type=snake_case_ , required=snake_case_ , help="Path to the student configuration." ) parser.add_argument( "--student_pretrained_weights" , default=snake_case_ , type=snake_case_ , help="Load student initialization checkpoint." ) parser.add_argument( "--teacher_type" , choices=["bert", "roberta", "gpt2"] , required=snake_case_ , help="Teacher type (BERT, RoBERTa)." ) parser.add_argument("--teacher_name" , type=snake_case_ , required=snake_case_ , help="The teacher model." ) parser.add_argument("--temperature" , default=2.0 , type=snake_case_ , help="Temperature for the softmax temperature." ) parser.add_argument( "--alpha_ce" , default=0.5 , type=snake_case_ , help="Linear weight for the distillation loss. Must be >=0." ) parser.add_argument( "--alpha_mlm" , default=0.0 , type=snake_case_ , help="Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag." , ) parser.add_argument("--alpha_clm" , default=0.5 , type=snake_case_ , help="Linear weight for the CLM loss. Must be >=0." ) parser.add_argument("--alpha_mse" , default=0.0 , type=snake_case_ , help="Linear weight of the MSE loss. Must be >=0." ) parser.add_argument( "--alpha_cos" , default=0.0 , type=snake_case_ , help="Linear weight of the cosine embedding loss. Must be >=0." ) parser.add_argument( "--mlm" , action="store_true" , help="The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM." ) parser.add_argument( "--mlm_mask_prop" , default=0.15 , type=snake_case_ , help="Proportion of tokens for which we need to make a prediction." , ) parser.add_argument("--word_mask" , default=0.8 , type=snake_case_ , help="Proportion of tokens to mask out." ) parser.add_argument("--word_keep" , default=0.1 , type=snake_case_ , help="Proportion of tokens to keep." ) parser.add_argument("--word_rand" , default=0.1 , type=snake_case_ , help="Proportion of tokens to randomly replace." ) parser.add_argument( "--mlm_smoothing" , default=0.7 , type=snake_case_ , help="Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec)." , ) parser.add_argument("--token_counts" , type=snake_case_ , help="The token counts in the data_file for MLM." ) parser.add_argument( "--restrict_ce_to_mask" , action="store_true" , help="If true, compute the distillation loss only the [MLM] prediction distribution." , ) parser.add_argument( "--freeze_pos_embs" , action="store_true" , help="Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only." , ) parser.add_argument( "--freeze_token_type_embds" , action="store_true" , help="Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only." , ) parser.add_argument("--n_epoch" , type=snake_case_ , default=3 , help="Number of pass on the whole dataset." ) parser.add_argument("--batch_size" , type=snake_case_ , default=5 , help="Batch size (for each process)." ) parser.add_argument( "--group_by_size" , action="store_false" , help="If true, group sequences that have similar length into the same batch. Default is true." , ) parser.add_argument( "--gradient_accumulation_steps" , type=snake_case_ , default=50 , help="Gradient accumulation for larger training batches." , ) parser.add_argument("--warmup_prop" , default=0.05 , type=snake_case_ , help="Linear warmup proportion." ) parser.add_argument("--weight_decay" , default=0.0 , type=snake_case_ , help="Weight decay if we apply some." ) parser.add_argument("--learning_rate" , default=5E-4 , type=snake_case_ , help="The initial learning rate for Adam." ) parser.add_argument("--adam_epsilon" , default=1E-6 , type=snake_case_ , help="Epsilon for Adam optimizer." ) parser.add_argument("--max_grad_norm" , default=5.0 , type=snake_case_ , help="Max gradient norm." ) parser.add_argument("--initializer_range" , default=0.02 , type=snake_case_ , help="Random initialization range." ) parser.add_argument( "--fp16" , action="store_true" , help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit" , ) parser.add_argument( "--fp16_opt_level" , type=snake_case_ , default="O1" , help=( "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html" ) , ) parser.add_argument("--n_gpu" , type=snake_case_ , default=1 , help="Number of GPUs in the node." ) parser.add_argument("--local_rank" , type=snake_case_ , default=-1 , help="Distributed training - Local rank" ) parser.add_argument("--seed" , type=snake_case_ , default=56 , help="Random seed" ) parser.add_argument("--log_interval" , type=snake_case_ , default=5_00 , help="Tensorboard logging interval." ) parser.add_argument("--checkpoint_interval" , type=snake_case_ , default=40_00 , help="Checkpoint interval." ) UpperCAmelCase_ = parser.parse_args() sanity_checks(snake_case_ ) # ARGS # init_gpu_params(snake_case_ ) set_seed(snake_case_ ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f"""Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite""" " itUse `--force` if you want to overwrite it" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f"""Experiment will be dumped and logged in {args.dump_path}""" ) # SAVE PARAMS # logger.info(f"""Param: {args}""" ) with open(os.path.join(args.dump_path , "parameters.json" ) , "w" ) as f: json.dump(vars(snake_case_ ) , snake_case_ , indent=4 ) git_log(args.dump_path ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = MODEL_CLASSES[args.student_type] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = MODEL_CLASSES[args.teacher_type] # TOKENIZER # UpperCAmelCase_ = teacher_tokenizer_class.from_pretrained(args.teacher_name ) UpperCAmelCase_ = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): UpperCAmelCase_ = tokenizer.all_special_tokens.index(snake_case_ ) UpperCAmelCase_ = tokenizer.all_special_ids[idx] logger.info(f"""Special tokens {special_tok_ids}""" ) UpperCAmelCase_ = special_tok_ids UpperCAmelCase_ = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f"""Loading data from {args.data_file}""" ) with open(args.data_file , "rb" ) as fp: UpperCAmelCase_ = pickle.load(snake_case_ ) if args.mlm: logger.info(f"""Loading token counts from {args.token_counts} (already pre-computed)""" ) with open(args.token_counts , "rb" ) as fp: UpperCAmelCase_ = pickle.load(snake_case_ ) UpperCAmelCase_ = np.maximum(snake_case_ , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): UpperCAmelCase_ = 0.0 # do not predict special tokens UpperCAmelCase_ = torch.from_numpy(snake_case_ ) else: UpperCAmelCase_ = None UpperCAmelCase_ = LmSeqsDataset(params=snake_case_ , data=snake_case_ ) logger.info("Data loader created." ) # STUDENT # logger.info(f"""Loading student config from {args.student_config}""" ) UpperCAmelCase_ = student_config_class.from_pretrained(args.student_config ) UpperCAmelCase_ = True if args.student_pretrained_weights is not None: logger.info(f"""Loading pretrained weights from {args.student_pretrained_weights}""" ) UpperCAmelCase_ = student_model_class.from_pretrained(args.student_pretrained_weights , config=snake_case_ ) else: UpperCAmelCase_ = student_model_class(snake_case_ ) if args.n_gpu > 0: student.to(f"""cuda:{args.local_rank}""" ) logger.info("Student loaded." ) # TEACHER # UpperCAmelCase_ = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=snake_case_ ) if args.n_gpu > 0: teacher.to(f"""cuda:{args.local_rank}""" ) logger.info(f"""Teacher loaded from {args.teacher_name}.""" ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(snake_case_ , snake_case_ ) if args.freeze_token_type_embds: freeze_token_type_embeddings(snake_case_ , snake_case_ ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() UpperCAmelCase_ = Distiller( params=snake_case_ , dataset=snake_case_ , token_probs=snake_case_ , student=snake_case_ , teacher=snake_case_ ) distiller.train() logger.info("Let's go get some drinks." ) if __name__ == "__main__": main()
78
0
import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def __lowerCAmelCase ( A_ : Union[str, Any] , A_ : Optional[int]=7 ) -> Any: __UpperCAmelCase = None if token is not None: __UpperCAmelCase = {"Accept": "application/vnd.github+json", "Authorization": F'''Bearer {token}'''} # The id of a workflow (not of a workflow run) __UpperCAmelCase = "636036" __UpperCAmelCase = F'''https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs''' # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F'''?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}''' __UpperCAmelCase = requests.get(snake_case_ , headers=snake_case_ ).json() return result["workflow_runs"] def __lowerCAmelCase ( A_ : Any ) -> Optional[Any]: __UpperCAmelCase = get_daily_ci_runs(snake_case_ ) __UpperCAmelCase = None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": __UpperCAmelCase = workflow_run["id"] break return workflow_run_id def __lowerCAmelCase ( A_ : str , A_ : str , A_ : Union[str, Any] ) -> Optional[int]: __UpperCAmelCase = get_last_daily_ci_runs(snake_case_ ) if workflow_run_id is not None: __UpperCAmelCase = get_artifacts_links(worflow_run_id=snake_case_ , token=snake_case_ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: __UpperCAmelCase = artifacts_links[artifact_name] download_artifact( artifact_name=snake_case_ , artifact_url=snake_case_ , output_dir=snake_case_ , token=snake_case_ ) def __lowerCAmelCase ( A_ : Dict , A_ : Tuple , A_ : Union[str, Any] ) -> int: get_last_daily_ci_artifacts(snake_case_ , snake_case_ , snake_case_ ) __UpperCAmelCase = {} for artifact_name in artifact_names: __UpperCAmelCase = os.path.join(snake_case_ , F'''{artifact_name}.zip''' ) if os.path.isfile(snake_case_ ): __UpperCAmelCase = {} with zipfile.ZipFile(snake_case_ ) as z: for filename in z.namelist(): if not os.path.isdir(snake_case_ ): # read the file with z.open(snake_case_ ) as f: __UpperCAmelCase = f.read().decode("UTF-8" ) return results
221
'''simple docstring''' import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __A ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): a__ : int = AutoencoderKL a__ : Optional[Any] = """sample""" a__ : Union[str, Any] = 1e-2 @property def _lowercase (self : Optional[int] ): UpperCAmelCase_ = 4 UpperCAmelCase_ = 3 UpperCAmelCase_ = (32, 32) UpperCAmelCase_ = floats_tensor((batch_size, num_channels) + sizes ).to(__a ) return {"sample": image} @property def _lowercase (self : Any ): return (3, 32, 32) @property def _lowercase (self : Dict ): return (3, 32, 32) def _lowercase (self : int ): UpperCAmelCase_ = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } UpperCAmelCase_ = self.dummy_input return init_dict, inputs_dict def _lowercase (self : int ): pass def _lowercase (self : int ): pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def _lowercase (self : List[Any] ): # enable deterministic behavior for gradient checkpointing UpperCAmelCase_ , UpperCAmelCase_ = self.prepare_init_args_and_inputs_for_common() UpperCAmelCase_ = self.model_class(**__a ) model.to(__a ) assert not model.is_gradient_checkpointing and model.training UpperCAmelCase_ = model(**__a ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() UpperCAmelCase_ = torch.randn_like(__a ) UpperCAmelCase_ = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing UpperCAmelCase_ = self.model_class(**__a ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(__a ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training UpperCAmelCase_ = model_a(**__a ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() UpperCAmelCase_ = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) UpperCAmelCase_ = dict(model.named_parameters() ) UpperCAmelCase_ = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def _lowercase (self : Any ): UpperCAmelCase_ , UpperCAmelCase_ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=__a ) self.assertIsNotNone(__a ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(__a ) UpperCAmelCase_ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def _lowercase (self : List[str] ): UpperCAmelCase_ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) UpperCAmelCase_ = model.to(__a ) model.eval() if torch_device == "mps": UpperCAmelCase_ = torch.manual_seed(0 ) else: UpperCAmelCase_ = torch.Generator(device=__a ).manual_seed(0 ) UpperCAmelCase_ = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) UpperCAmelCase_ = image.to(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , sample_posterior=__a , generator=__a ).sample UpperCAmelCase_ = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": UpperCAmelCase_ = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": UpperCAmelCase_ = torch.tensor( [-0.13_52, 0.08_78, 0.04_19, -0.08_18, -0.10_69, 0.06_88, -0.14_58, -0.44_46, -0.00_26] ) else: UpperCAmelCase_ = torch.tensor( [-0.24_21, 0.46_42, 0.25_07, -0.04_38, 0.06_82, 0.31_60, -0.20_18, -0.07_27, 0.24_85] ) self.assertTrue(torch_all_close(__a , __a , rtol=1E-2 ) ) @slow class __A ( unittest.TestCase ): def _lowercase (self : Dict , __a : Dict , __a : int ): return f"""gaussian_noise_s={seed}_shape={"_".join([str(__a ) for s in shape] )}.npy""" def _lowercase (self : str ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self : Optional[Any] , __a : Optional[Any]=0 , __a : str=(4, 3, 512, 512) , __a : List[str]=False ): UpperCAmelCase_ = torch.floataa if fpaa else torch.floataa UpperCAmelCase_ = torch.from_numpy(load_hf_numpy(self.get_file_format(__a , __a ) ) ).to(__a ).to(__a ) return image def _lowercase (self : List[Any] , __a : Union[str, Any]="CompVis/stable-diffusion-v1-4" , __a : List[Any]=False ): UpperCAmelCase_ = "fp16" if fpaa else None UpperCAmelCase_ = torch.floataa if fpaa else torch.floataa UpperCAmelCase_ = AutoencoderKL.from_pretrained( __a , subfolder="vae" , torch_dtype=__a , revision=__a , ) model.to(__a ).eval() return model def _lowercase (self : List[Any] , __a : List[Any]=0 ): if torch_device == "mps": return torch.manual_seed(__a ) return torch.Generator(device=__a ).manual_seed(__a ) @parameterized.expand( [ # fmt: off [33, [-0.16_03, 0.98_78, -0.04_95, -0.07_90, -0.27_09, 0.83_75, -0.20_60, -0.08_24], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_76, 0.11_68, 0.13_32, -0.48_40, -0.25_08, -0.07_91, -0.04_93, -0.40_89], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def _lowercase (self : List[Any] , __a : Dict , __a : Optional[int] , __a : List[str] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , generator=__a , sample_posterior=__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, -2:, :2].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(__a , __a , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.05_13, 0.02_89, 1.37_99, 0.21_66, -0.25_73, -0.08_71, 0.51_03, -0.09_99]], [47, [-0.41_28, -0.13_20, -0.37_04, 0.19_65, -0.41_16, -0.23_32, -0.33_40, 0.22_47]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : Dict , __a : Optional[int] , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , fpaa=__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , generator=__a , sample_posterior=__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.16_09, 0.98_66, -0.04_87, -0.07_77, -0.27_16, 0.83_68, -0.20_55, -0.08_14], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_77, 0.11_47, 0.13_33, -0.48_41, -0.25_06, -0.08_05, -0.04_91, -0.40_85], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def _lowercase (self : str , __a : int , __a : Union[str, Any] , __a : List[Any] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, -2:, :2].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(__a , __a , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.20_51, -0.18_03, -0.23_11, -0.21_14, -0.32_92, -0.35_74, -0.29_53, -0.33_23]], [37, [-0.26_32, -0.26_25, -0.21_99, -0.27_41, -0.45_39, -0.49_90, -0.37_20, -0.49_25]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : int , __a : int , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.03_69, 0.02_07, -0.07_76, -0.06_82, -0.17_47, -0.19_30, -0.14_65, -0.20_39]], [16, [-0.16_28, -0.21_34, -0.27_47, -0.26_42, -0.37_74, -0.44_04, -0.36_87, -0.42_77]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : Union[str, Any] , __a : List[str] , __a : Optional[Any] ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) , fpaa=__a ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , atol=5E-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def _lowercase (self : List[str] , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) , fpaa=__a ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__a , __a , atol=1E-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def _lowercase (self : Union[str, Any] , __a : Dict ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__a , __a , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.30_01, 0.09_18, -2.69_84, -3.97_20, -3.20_99, -5.03_53, 1.73_38, -0.20_65, 3.42_67]], [47, [-1.50_30, -4.38_71, -6.03_55, -9.11_57, -1.66_61, -2.78_53, 2.16_07, -5.08_23, 2.56_33]], # fmt: on ] ) def _lowercase (self : Tuple , __a : List[Any] , __a : List[Any] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model.encode(__a ).latent_dist UpperCAmelCase_ = dist.sample(generator=__a ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] UpperCAmelCase_ = sample[0, -1, -3:, -3:].flatten().cpu() UpperCAmelCase_ = torch.tensor(__a ) UpperCAmelCase_ = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(__a , __a , atol=__a )
78
0
"""simple docstring""" import math import os import sys def lowercase_ ( __UpperCAmelCase ) -> str: lowerCAmelCase__ : Tuple = """""" try: with open(snake_case_ , """rb""" ) as binary_file: lowerCAmelCase__ : Optional[int] = binary_file.read() for dat in data: lowerCAmelCase__ : Dict = f"""{dat:08b}""" result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def lowercase_ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> None: lexicon.pop(snake_case_ ) lowerCAmelCase__ : List[Any] = last_match_id if math.loga(snake_case_ ).is_integer(): for curr_key in lexicon: lowerCAmelCase__ : int = """0""" + lexicon[curr_key] lowerCAmelCase__ : List[Any] = bin(snake_case_ )[2:] def lowercase_ ( __UpperCAmelCase ) -> str: lowerCAmelCase__ : str = {"""0""": """0""", """1""": """1"""} lowerCAmelCase__ , lowerCAmelCase__ : str = """""", """""" lowerCAmelCase__ : Tuple = len(snake_case_ ) for i in range(len(snake_case_ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue lowerCAmelCase__ : Optional[int] = lexicon[curr_string] result += last_match_id add_key_to_lexicon(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) index += 1 lowerCAmelCase__ : str = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": lowerCAmelCase__ : int = lexicon[curr_string] result += last_match_id return result def lowercase_ ( __UpperCAmelCase , __UpperCAmelCase ) -> str: lowerCAmelCase__ : Any = os.path.getsize(snake_case_ ) lowerCAmelCase__ : int = bin(snake_case_ )[2:] lowerCAmelCase__ : List[Any] = len(snake_case_ ) return "0" * (length_length - 1) + file_length_binary + compressed def lowercase_ ( __UpperCAmelCase , __UpperCAmelCase ) -> None: lowerCAmelCase__ : int = 8 try: with open(snake_case_ , """wb""" ) as opened_file: lowerCAmelCase__ : int = [ to_write[i : i + byte_length] for i in range(0 , len(snake_case_ ) , snake_case_ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(snake_case_ , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def lowercase_ ( __UpperCAmelCase , __UpperCAmelCase ) -> None: lowerCAmelCase__ : int = read_file_binary(snake_case_ ) lowerCAmelCase__ : Union[str, Any] = compress_data(snake_case_ ) lowerCAmelCase__ : Optional[Any] = add_file_length(snake_case_ , snake_case_ ) write_file_binary(snake_case_ , snake_case_ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
299
'''simple docstring''' import logging from transformers import PretrainedConfig SCREAMING_SNAKE_CASE_: Any =logging.getLogger(__name__) SCREAMING_SNAKE_CASE_: Any ={ 'bertabs-finetuned-cnndm': 'https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json', } class __A ( UpperCamelCase__ ): a__ : List[Any] = """bertabs""" def __init__(self : Any , __a : int=30522 , __a : Tuple=512 , __a : Tuple=6 , __a : Dict=512 , __a : int=8 , __a : List[Any]=512 , __a : List[str]=0.2 , __a : List[Any]=6 , __a : int=768 , __a : Any=8 , __a : Dict=2048 , __a : Tuple=0.2 , **__a : Optional[int] , ): super().__init__(**__a ) UpperCAmelCase_ = vocab_size UpperCAmelCase_ = max_pos UpperCAmelCase_ = enc_layers UpperCAmelCase_ = enc_hidden_size UpperCAmelCase_ = enc_heads UpperCAmelCase_ = enc_ff_size UpperCAmelCase_ = enc_dropout UpperCAmelCase_ = dec_layers UpperCAmelCase_ = dec_hidden_size UpperCAmelCase_ = dec_heads UpperCAmelCase_ = dec_ff_size UpperCAmelCase_ = dec_dropout
78
0
from typing import Any import numpy as np def _lowerCAmelCase ( lowerCAmelCase_ :np.ndarray )->bool: '''simple docstring''' return np.array_equal(snake_case_ , matrix.conjugate().T ) def _lowerCAmelCase ( lowerCAmelCase_ :np.ndarray , lowerCAmelCase_ :np.ndarray )->Any: '''simple docstring''' snake_case_ = v.conjugate().T snake_case_ = v_star.dot(snake_case_ ) assert isinstance(snake_case_ , np.ndarray ) return (v_star_dot.dot(snake_case_ )) / (v_star.dot(snake_case_ )) def _lowerCAmelCase ( )->None: '''simple docstring''' snake_case_ = np.array([[2, 2 + 1J, 4], [2 - 1J, 3, 1J], [4, -1J, 1]] ) snake_case_ = np.array([[1], [2], [3]] ) assert is_hermitian(snake_case_ ), F'''{a} is not hermitian.''' print(rayleigh_quotient(snake_case_ , snake_case_ ) ) snake_case_ = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(snake_case_ ), F'''{a} is not hermitian.''' assert rayleigh_quotient(snake_case_ , snake_case_ ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
283
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE_: Tuple =logging.get_logger(__name__) def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> int: '''simple docstring''' UpperCAmelCase_ = "huggingface/label-files" UpperCAmelCase_ = "imagenet-1k-id2label.json" UpperCAmelCase_ = json.load(open(hf_hub_download(snake_case_ , snake_case_ , repo_type="dataset" ) , "r" ) ) UpperCAmelCase_ = {int(snake_case_ ): v for k, v in idalabel.items()} UpperCAmelCase_ = {v: k for k, v in idalabel.items()} UpperCAmelCase_ = "std_conv" if "bit" in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" UpperCAmelCase_ = BitConfig( conv_layer=snake_case_ , num_labels=10_00 , idalabel=snake_case_ , labelaid=snake_case_ , ) return config def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' if "stem.conv" in name: UpperCAmelCase_ = name.replace("stem.conv" , "bit.embedder.convolution" ) if "blocks" in name: UpperCAmelCase_ = name.replace("blocks" , "layers" ) if "head.fc" in name: UpperCAmelCase_ = name.replace("head.fc" , "classifier.1" ) if name.startswith("norm" ): UpperCAmelCase_ = "bit." + name if "bit" not in name and "classifier" not in name: UpperCAmelCase_ = "bit.encoder." + name return name def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = "http://images.cocodataset.org/val2017/000000039769.jpg" UpperCAmelCase_ = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : Tuple , snake_case_ : Optional[Any] , snake_case_ : int=False ) -> List[Any]: '''simple docstring''' UpperCAmelCase_ = get_config(snake_case_ ) # load original model from timm UpperCAmelCase_ = create_model(snake_case_ , pretrained=snake_case_ ) timm_model.eval() # load state_dict of original model UpperCAmelCase_ = timm_model.state_dict() for key in state_dict.copy().keys(): UpperCAmelCase_ = state_dict.pop(snake_case_ ) UpperCAmelCase_ = val.squeeze() if "head" in key else val # load HuggingFace model UpperCAmelCase_ = BitForImageClassification(snake_case_ ) model.eval() model.load_state_dict(snake_case_ ) # create image processor UpperCAmelCase_ = create_transform(**resolve_data_config({} , model=snake_case_ ) ) UpperCAmelCase_ = transform.transforms UpperCAmelCase_ = { "bilinear": PILImageResampling.BILINEAR, "bicubic": PILImageResampling.BICUBIC, "nearest": PILImageResampling.NEAREST, } UpperCAmelCase_ = BitImageProcessor( do_resize=snake_case_ , size={"shortest_edge": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=snake_case_ , crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]} , do_normalize=snake_case_ , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = transform(snake_case_ ).unsqueeze(0 ) UpperCAmelCase_ = processor(snake_case_ , return_tensors="pt" ).pixel_values # verify pixel values assert torch.allclose(snake_case_ , snake_case_ ) # verify logits with torch.no_grad(): UpperCAmelCase_ = model(snake_case_ ) UpperCAmelCase_ = outputs.logits print("Logits:" , logits[0, :3] ) print("Predicted class:" , model.config.idalabel[logits.argmax(-1 ).item()] ) UpperCAmelCase_ = timm_model(snake_case_ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(snake_case_ , outputs.logits , atol=1E-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) print(f"""Saving model {model_name} and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(snake_case_ ) processor.save_pretrained(snake_case_ ) if push_to_hub: print(f"""Pushing model {model_name} and processor to the hub""" ) model.push_to_hub(f"""ybelkada/{model_name}""" ) processor.push_to_hub(f"""ybelkada/{model_name}""" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: int =argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='resnetv2_50x1_bitm', type=str, help='Name of the BiT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model to the hub.', ) SCREAMING_SNAKE_CASE_: Union[str, Any] =parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
78
0
"""simple docstring""" import re import time from typing import Optional import IPython.display as disp from ..trainer_callback import TrainerCallback from ..trainer_utils import IntervalStrategy, has_length def A_ ( snake_case__ ) -> int: _UpperCamelCase :str = int(snake_case_ ) _UpperCamelCase , _UpperCamelCase , _UpperCamelCase :Optional[Any] = t // 36_00, (t // 60) % 60, t % 60 return f"{h}:{m:02d}:{s:02d}" if h != 0 else f"{m:02d}:{s:02d}" def A_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__=3_00 ) -> str: return f"\n <div>\n {prefix}\n <progress value='{value}' max='{total}' style='width:{width}px; height:20px; vertical-align: middle;'></progress>\n {label}\n </div>\n " def A_ ( snake_case__ ) -> Optional[Any]: _UpperCamelCase :int = '''<table border=\"1\" class=\"dataframe\">\n''' html_code += """ <thead>\n <tr style="text-align: left;">\n""" for i in items[0]: html_code += f" <th>{i}</th>\n" html_code += " </tr>\n </thead>\n <tbody>\n" for line in items[1:]: html_code += " <tr>\n" for elt in line: _UpperCamelCase :Union[str, Any] = f"{elt:.6f}" if isinstance(snake_case_ , snake_case_ ) else str(snake_case_ ) html_code += f" <td>{elt}</td>\n" html_code += " </tr>\n" html_code += " </tbody>\n</table><p>" return html_code class A: """simple docstring""" A = 5 A = 0.2 def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 3_00 , ) -> List[Any]: """simple docstring""" _UpperCamelCase :List[Any] = total _UpperCamelCase :int = '''''' if prefix is None else prefix _UpperCamelCase :str = leave _UpperCamelCase :List[Any] = parent _UpperCamelCase :List[str] = width _UpperCamelCase :str = None _UpperCamelCase :Union[str, Any] = None _UpperCamelCase :Optional[Any] = None def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = None ) -> List[str]: """simple docstring""" _UpperCamelCase :Union[str, Any] = value if comment is not None: _UpperCamelCase :Dict = comment if self.last_value is None: _UpperCamelCase :List[Any] = time.time() _UpperCamelCase :Optional[Any] = value _UpperCamelCase :List[Any] = None _UpperCamelCase :Union[str, Any] = self.warmup _UpperCamelCase :Optional[int] = 1 self.update_bar(__a ) elif value <= self.last_value and not force_update: return elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for , self.total ): if self.first_calls > 0: self.first_calls -= 1 _UpperCamelCase :Any = time.time() _UpperCamelCase :str = current_time - self.start_time # We could have value = self.start_value if the update is called twixe with the same start value. if value > self.start_value: _UpperCamelCase :Union[str, Any] = self.elapsed_time / (value - self.start_value) else: _UpperCamelCase :List[Any] = None if value >= self.total: _UpperCamelCase :Dict = self.total _UpperCamelCase :List[str] = None if not self.leave: self.close() elif self.average_time_per_item is not None: _UpperCamelCase :str = self.average_time_per_item * (self.total - value) self.update_bar(__a ) _UpperCamelCase :Optional[Any] = value _UpperCamelCase :List[Any] = current_time if self.average_time_per_item is None: _UpperCamelCase :Optional[int] = 1 else: _UpperCamelCase :Any = max(int(self.update_every / self.average_time_per_item ) , 1 ) def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ) -> Tuple: """simple docstring""" _UpperCamelCase :Dict = ''' ''' * (len(str(self.total ) ) - len(str(__a ) )) + str(__a ) if self.elapsed_time is None: _UpperCamelCase :Optional[Any] = f"[{spaced_value}/{self.total} : < :" elif self.predicted_remaining is None: _UpperCamelCase :Optional[Any] = f"[{spaced_value}/{self.total} {format_time(self.elapsed_time )}" else: _UpperCamelCase :List[Any] = ( f"[{spaced_value}/{self.total} {format_time(self.elapsed_time )} <" f" {format_time(self.predicted_remaining )}" ) self.label += f", {1/self.average_time_per_item:.2f} it/s" self.label += "]" if self.comment is None or len(self.comment ) == 0 else f", {self.comment}]" self.display() def _UpperCamelCase( self ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase :str = html_progress_bar(self.value , self.total , self.prefix , self.label , self.width ) if self.parent is not None: # If this is a child bar, the parent will take care of the display. self.parent.display() return if self.output is None: _UpperCamelCase :int = disp.display(disp.HTML(self.html_code ) , display_id=__a ) else: self.output.update(disp.HTML(self.html_code ) ) def _UpperCamelCase( self ) -> Optional[int]: """simple docstring""" if self.parent is None and self.output is not None: self.output.update(disp.HTML('''''' ) ) class A( UpperCamelCase__ ): """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ) -> Tuple: """simple docstring""" super().__init__(__a ) _UpperCamelCase :Dict = None if column_names is None else [column_names] _UpperCamelCase :Dict = None def _UpperCamelCase( self ) -> List[str]: """simple docstring""" _UpperCamelCase :Tuple = html_progress_bar(self.value , self.total , self.prefix , self.label , self.width ) if self.inner_table is not None: self.html_code += text_to_html_table(self.inner_table ) if self.child_bar is not None: self.html_code += self.child_bar.html_code if self.output is None: _UpperCamelCase :Union[str, Any] = disp.display(disp.HTML(self.html_code ) , display_id=__a ) else: self.output.update(disp.HTML(self.html_code ) ) def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ ) -> List[str]: """simple docstring""" if self.inner_table is None: _UpperCamelCase :Optional[Any] = [list(values.keys() ), list(values.values() )] else: _UpperCamelCase :Optional[int] = self.inner_table[0] if len(self.inner_table ) == 1: # We give a chance to update the column names at the first iteration for key in values.keys(): if key not in columns: columns.append(__a ) _UpperCamelCase :Optional[Any] = columns self.inner_table.append([values[c] for c in columns] ) def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=3_00 ) -> Tuple: """simple docstring""" _UpperCamelCase :Union[str, Any] = NotebookProgressBar(__a , prefix=__a , parent=self , width=__a ) return self.child_bar def _UpperCamelCase( self ) -> Dict: """simple docstring""" _UpperCamelCase :Tuple = None self.display() class A( UpperCamelCase__ ): """simple docstring""" def __init__( self ) -> str: """simple docstring""" _UpperCamelCase :Optional[Any] = None _UpperCamelCase :Optional[Any] = None _UpperCamelCase :int = False def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> Any: """simple docstring""" _UpperCamelCase :int = '''Epoch''' if args.evaluation_strategy == IntervalStrategy.EPOCH else '''Step''' _UpperCamelCase :Tuple = 0 _UpperCamelCase :Dict = 0 _UpperCamelCase :Optional[Any] = [self.first_column] + ['''Training Loss'''] if args.evaluation_strategy != IntervalStrategy.NO: column_names.append('''Validation Loss''' ) _UpperCamelCase :int = NotebookTrainingTracker(state.max_steps , __a ) def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> Optional[int]: """simple docstring""" _UpperCamelCase :str = int(state.epoch ) if int(state.epoch ) == state.epoch else f"{state.epoch:.2f}" self.training_tracker.update( state.global_step + 1 , comment=f"Epoch {epoch}/{state.num_train_epochs}" , force_update=self._force_next_update , ) _UpperCamelCase :Any = False def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None , **SCREAMING_SNAKE_CASE__ ) -> Dict: """simple docstring""" if not has_length(__a ): return if self.prediction_bar is None: if self.training_tracker is not None: _UpperCamelCase :Any = self.training_tracker.add_child(len(__a ) ) else: _UpperCamelCase :Optional[Any] = NotebookProgressBar(len(__a ) ) self.prediction_bar.update(1 ) else: self.prediction_bar.update(self.prediction_bar.value + 1 ) def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> Optional[int]: """simple docstring""" if self.prediction_bar is not None: self.prediction_bar.close() _UpperCamelCase :Dict = None def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None , **SCREAMING_SNAKE_CASE__ ) -> Union[str, Any]: """simple docstring""" if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs: _UpperCamelCase :str = {'''Training Loss''': logs['''loss''']} # First column is necessarily Step sine we're not in epoch eval strategy _UpperCamelCase :Tuple = state.global_step self.training_tracker.write_line(__a ) def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None , **SCREAMING_SNAKE_CASE__ ) -> Tuple: """simple docstring""" if self.training_tracker is not None: _UpperCamelCase :str = {'''Training Loss''': '''No log''', '''Validation Loss''': '''No log'''} for log in reversed(state.log_history ): if "loss" in log: _UpperCamelCase :str = log['''loss'''] break if self.first_column == "Epoch": _UpperCamelCase :Optional[Any] = int(state.epoch ) else: _UpperCamelCase :Tuple = state.global_step _UpperCamelCase :Optional[Any] = '''eval''' for k in metrics: if k.endswith('''_loss''' ): _UpperCamelCase :str = re.sub(r'''\_loss$''' , '''''' , __a ) _UpperCamelCase :List[str] = metrics.pop('''total_flos''' , __a ) _UpperCamelCase :Tuple = metrics.pop('''epoch''' , __a ) _UpperCamelCase :Optional[Any] = metrics.pop(f"{metric_key_prefix}_runtime" , __a ) _UpperCamelCase :Dict = metrics.pop(f"{metric_key_prefix}_samples_per_second" , __a ) _UpperCamelCase :List[str] = metrics.pop(f"{metric_key_prefix}_steps_per_second" , __a ) _UpperCamelCase :Optional[Any] = metrics.pop(f"{metric_key_prefix}_jit_compilation_time" , __a ) for k, v in metrics.items(): if k == f"{metric_key_prefix}_loss": _UpperCamelCase :str = v else: _UpperCamelCase :List[Any] = k.split('''_''' ) _UpperCamelCase :Dict = ''' '''.join([part.capitalize() for part in splits[1:]] ) _UpperCamelCase :List[str] = v self.training_tracker.write_line(__a ) self.training_tracker.remove_child() _UpperCamelCase :str = None # Evaluation takes a long time so we should force the next update. _UpperCamelCase :Optional[Any] = True def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> Any: """simple docstring""" self.training_tracker.update( state.global_step , comment=f"Epoch {int(state.epoch )}/{state.num_train_epochs}" , force_update=__a ) _UpperCamelCase :int = None
355
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class __A ( unittest.TestCase ): def _lowercase (self : List[str] ): UpperCAmelCase_ = 0 def _lowercase (self : Tuple ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("openai/clip-vit-base-patch32" ) self.assertIsInstance(__a , __a ) def _lowercase (self : str ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : Dict ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : List[str] ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = CLIPConfig() # Create a dummy config file with image_proceesor_type UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ).to_dict() config_dict.pop("image_processor_type" ) UpperCAmelCase_ = CLIPImageProcessor(**__a ) # save in new folder model_config.save_pretrained(__a ) config.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) # make sure private variable is not incorrectly saved UpperCAmelCase_ = json.loads(config.to_json_string() ) self.assertTrue("_processor_class" not in dict_as_saved ) self.assertIsInstance(__a , __a ) def _lowercase (self : int ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : Tuple ): with self.assertRaisesRegex( __a , "clip-base is not a local folder and is not a valid model identifier" ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("clip-base" ) def _lowercase (self : Optional[int] ): with self.assertRaisesRegex( __a , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a , revision="aaaaaa" ) def _lowercase (self : Union[str, Any] ): with self.assertRaisesRegex( __a , "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json." , ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/config-no-model" ) def _lowercase (self : List[Any] ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(__a ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" ) # If remote code is disabled, we can't load this config. with self.assertRaises(__a ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a , trust_remote_code=__a ) self.assertEqual(reloaded_image_processor.__class__.__name__ , "NewImageProcessor" ) def _lowercase (self : Optional[int] ): try: AutoConfig.register("custom" , __a ) AutoImageProcessor.register(__a , __a ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__a ): AutoImageProcessor.register(__a , __a ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = CustomImageProcessor.from_pretrained(__a ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def _lowercase (self : Optional[int] ): class __A ( UpperCamelCase__ ): a__ : str = True try: AutoConfig.register("custom" , __a ) AutoImageProcessor.register(__a , __a ) # If remote code is not set, the default is to use local UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(not hasattr(__a , "is_local" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
78
0
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( lowerCamelCase__ : int , lowerCamelCase__ : int ): '''simple docstring''' if b == 0: return 1 if (b % 2) == 0: return actual_power(snake_case_ , int(b / 2 ) ) * actual_power(snake_case_ , int(b / 2 ) ) else: return a * actual_power(snake_case_ , int(b / 2 ) ) * actual_power(snake_case_ , int(b / 2 ) ) def _SCREAMING_SNAKE_CASE ( lowerCamelCase__ : int , lowerCamelCase__ : int ): '''simple docstring''' if b < 0: return 1 / actual_power(snake_case_ , snake_case_ ) return actual_power(snake_case_ , snake_case_ ) if __name__ == "__main__": print(power(-2, -3))
135
'''simple docstring''' import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..utils.py_utils import no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: from .features import FeatureType SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_: Tuple =False, False, False @dataclass class __A : a__ : Optional[int] = None a__ : bool = True a__ : bool = True a__ : Optional[str] = None # Automatically constructed a__ : ClassVar[str] = "dict" a__ : ClassVar[Any] = pa.struct({"""bytes""": pa.binary(), """path""": pa.string()} ) a__ : str = field(default="""Audio""" , init=UpperCamelCase__ , repr=UpperCamelCase__ ) def __call__(self : Optional[Any] ): return self.pa_type def _lowercase (self : str , __a : Union[str, bytes, dict] ): try: import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files. except ImportError as err: raise ImportError("To support encoding audio data, please install 'soundfile'." ) from err if isinstance(__a , __a ): return {"bytes": None, "path": value} elif isinstance(__a , __a ): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes UpperCAmelCase_ = BytesIO() sf.write(__a , value["array"] , value["sampling_rate"] , format="wav" ) return {"bytes": buffer.getvalue(), "path": None} elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally if value["path"].endswith("pcm" ): # "PCM" only has raw audio bytes if value.get("sampling_rate" ) is None: # At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate raise KeyError("To use PCM files, please specify a 'sampling_rate' in Audio object" ) if value.get("bytes" ): # If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!) UpperCAmelCase_ = np.frombuffer(value["bytes"] , dtype=np.intaa ).astype(np.floataa ) / 32767 else: UpperCAmelCase_ = np.memmap(value["path"] , dtype="h" , mode="r" ).astype(np.floataa ) / 32767 UpperCAmelCase_ = BytesIO(bytes() ) sf.write(__a , __a , value["sampling_rate"] , format="wav" ) return {"bytes": buffer.getvalue(), "path": None} else: return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the audio bytes, and path is used to infer the audio format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( f"""An audio sample should have one of 'path' or 'bytes' but they are missing or None in {value}.""" ) def _lowercase (self : Dict , __a : dict , __a : Optional[Dict[str, Union[str, bool, None]]] = None ): if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Audio(decode=True) instead." ) UpperCAmelCase_ , UpperCAmelCase_ = (value["path"], BytesIO(value["bytes"] )) if value["bytes"] is not None else (value["path"], None) if path is None and file is None: raise ValueError(f"""An audio sample should have one of 'path' or 'bytes' but both are None in {value}.""" ) try: import librosa import soundfile as sf except ImportError as err: raise ImportError("To support decoding audio files, please install 'librosa' and 'soundfile'." ) from err UpperCAmelCase_ = xsplitext(__a )[1][1:].lower() if path is not None else None if not config.IS_OPUS_SUPPORTED and audio_format == "opus": raise RuntimeError( "Decoding 'opus' files requires system library 'libsndfile'>=1.0.31, " "You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. " ) elif not config.IS_MP3_SUPPORTED and audio_format == "mp3": raise RuntimeError( "Decoding 'mp3' files requires system library 'libsndfile'>=1.1.0, " "You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. " ) if file is None: UpperCAmelCase_ = token_per_repo_id or {} UpperCAmelCase_ = path.split("::" )[-1] try: UpperCAmelCase_ = string_to_dict(__a , config.HUB_DATASETS_URL )["repo_id"] UpperCAmelCase_ = token_per_repo_id[repo_id] except (ValueError, KeyError): UpperCAmelCase_ = None with xopen(__a , "rb" , use_auth_token=__a ) as f: UpperCAmelCase_ , UpperCAmelCase_ = sf.read(__a ) else: UpperCAmelCase_ , UpperCAmelCase_ = sf.read(__a ) UpperCAmelCase_ = array.T if self.mono: UpperCAmelCase_ = librosa.to_mono(__a ) if self.sampling_rate and self.sampling_rate != sampling_rate: UpperCAmelCase_ = librosa.resample(__a , orig_sr=__a , target_sr=self.sampling_rate ) UpperCAmelCase_ = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def _lowercase (self : Dict ): from .features import Value if self.decode: raise ValueError("Cannot flatten a decoded Audio feature." ) return { "bytes": Value("binary" ), "path": Value("string" ), } def _lowercase (self : Optional[Any] , __a : Union[pa.StringArray, pa.StructArray] ): if pa.types.is_string(storage.type ): UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.binary() ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.string() ) UpperCAmelCase_ = pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ) and storage.type.get_all_field_indices("array" ): UpperCAmelCase_ = pa.array([Audio().encode_example(__a ) if x is not None else None for x in storage.to_pylist()] ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: UpperCAmelCase_ = storage.field("bytes" ) else: UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: UpperCAmelCase_ = storage.field("path" ) else: UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.string() ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) return array_cast(__a , self.pa_type ) def _lowercase (self : Dict , __a : pa.StructArray ): @no_op_if_value_is_null def path_to_bytes(__a : Tuple ): with xopen(__a , "rb" ) as f: UpperCAmelCase_ = f.read() return bytes_ UpperCAmelCase_ = pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) UpperCAmelCase_ = pa.array( [os.path.basename(__a ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(__a , self.pa_type )
78
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) _lowercase : Optional[int] = {'configuration_beit': ['BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BeitConfig', 'BeitOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Optional[int] = ['BeitFeatureExtractor'] _lowercase : int = ['BeitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Optional[int] = [ 'BEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BeitForImageClassification', 'BeitForMaskedImageModeling', 'BeitForSemanticSegmentation', 'BeitModel', 'BeitPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : int = [ 'FlaxBeitForImageClassification', 'FlaxBeitForMaskedImageModeling', 'FlaxBeitModel', 'FlaxBeitPreTrainedModel', ] if TYPE_CHECKING: from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_beit import BeitFeatureExtractor from .image_processing_beit import BeitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_beit import ( BEIT_PRETRAINED_MODEL_ARCHIVE_LIST, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, BeitPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_beit import ( FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel, FlaxBeitPreTrainedModel, ) else: import sys _lowercase : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
641
'''simple docstring''' import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def lowerCAmelCase_ ( snake_case_ : Any , snake_case_ : Optional[int] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg" UpperCAmelCase_ = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ).convert("RGB" ) UpperCAmelCase_ = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.4814_5466, 0.457_8275, 0.4082_1073) , (0.2686_2954, 0.2613_0258, 0.2757_7711) ), ] ) UpperCAmelCase_ = transform(snake_case_ ).unsqueeze(0 ).to(snake_case_ ) return image def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' if "visual_encoder" in key: UpperCAmelCase_ = re.sub("visual_encoder*" , "vision_model.encoder" , snake_case_ ) if "blocks" in key: UpperCAmelCase_ = re.sub(R"blocks" , "layers" , snake_case_ ) if "attn" in key: UpperCAmelCase_ = re.sub(R"attn" , "self_attn" , snake_case_ ) if "norm1" in key: UpperCAmelCase_ = re.sub(R"norm1" , "layer_norm1" , snake_case_ ) if "norm2" in key: UpperCAmelCase_ = re.sub(R"norm2" , "layer_norm2" , snake_case_ ) if "encoder.norm" in key: UpperCAmelCase_ = re.sub(R"encoder.norm" , "post_layernorm" , snake_case_ ) if "encoder.patch_embed.proj" in key: UpperCAmelCase_ = re.sub(R"encoder.patch_embed.proj" , "embeddings.patch_embedding" , snake_case_ ) if "encoder.pos_embed" in key: UpperCAmelCase_ = re.sub(R"encoder.pos_embed" , "embeddings.position_embedding" , snake_case_ ) if "encoder.cls_token" in key: UpperCAmelCase_ = re.sub(R"encoder.cls_token" , "embeddings.class_embedding" , snake_case_ ) if "self_attn" in key: UpperCAmelCase_ = re.sub(R"self_attn.proj" , "self_attn.projection" , snake_case_ ) return key @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : Any=None ) -> Union[str, Any]: '''simple docstring''' if config_path is not None: UpperCAmelCase_ = BlipConfig.from_pretrained(snake_case_ ) else: UpperCAmelCase_ = BlipConfig(projection_dim=5_12 , text_config={} , vision_config={} ) UpperCAmelCase_ = BlipForConditionalGeneration(snake_case_ ).eval() UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth" UpperCAmelCase_ = blip_decoder(pretrained=snake_case_ , image_size=3_84 , vit="base" ) UpperCAmelCase_ = pt_model.eval() UpperCAmelCase_ = pt_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value hf_model.load_state_dict(snake_case_ ) UpperCAmelCase_ = 3_84 UpperCAmelCase_ = load_demo_image(image_size=snake_case_ , device="cpu" ) UpperCAmelCase_ = BertTokenizer.from_pretrained("bert-base-uncased" ) UpperCAmelCase_ = tokenizer(["a picture of"] ).input_ids UpperCAmelCase_ = hf_model.generate(snake_case_ , snake_case_ ) assert out[0].tolist() == [3_05_22, 10_37, 38_61, 19_97, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] UpperCAmelCase_ = hf_model.generate(snake_case_ ) assert out[0].tolist() == [3_05_22, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(snake_case_ ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' UpperCAmelCase_ = ( "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth" ) UpperCAmelCase_ = blip_vqa(pretrained=snake_case_ , image_size=snake_case_ , vit="base" ) vqa_model.eval() UpperCAmelCase_ = vqa_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value UpperCAmelCase_ = BlipForQuestionAnswering(snake_case_ ) hf_vqa_model.load_state_dict(snake_case_ ) UpperCAmelCase_ = ["How many dogs are in this image?"] UpperCAmelCase_ = tokenizer(snake_case_ , return_tensors="pt" ).input_ids UpperCAmelCase_ = hf_vqa_model.generate(snake_case_ , snake_case_ ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + "_vqa" ) UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth" UpperCAmelCase_ = blip_itm(pretrained=snake_case_ , image_size=snake_case_ , vit="base" ) itm_model.eval() UpperCAmelCase_ = itm_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value UpperCAmelCase_ = BlipForImageTextRetrieval(snake_case_ ) UpperCAmelCase_ = ["A picture of a woman with a dog sitting in a beach"] UpperCAmelCase_ = tokenizer( snake_case_ , return_tensors="pt" , padding="max_length" , truncation=snake_case_ , max_length=35 , ).input_ids hf_itm_model.load_state_dict(snake_case_ ) hf_itm_model.eval() UpperCAmelCase_ = hf_itm_model(snake_case_ , snake_case_ , use_itm_head=snake_case_ ) UpperCAmelCase_ = hf_itm_model(snake_case_ , snake_case_ , use_itm_head=snake_case_ ) assert out[0].item() == 0.2110_6874_9427_7954 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.4_5698_8453_8650_5127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + "_itm" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Optional[Any] =argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') SCREAMING_SNAKE_CASE_: int =parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
78
0
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __magic_name__ = logging.get_logger(__name__) __magic_name__ = { 'BridgeTower/bridgetower-base': 'https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json', 'BridgeTower/bridgetower-base-itm-mlm': ( 'https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json' ), } class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ ): snake_case = """bridgetower_vision_model""" def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE_ : str=768 , SCREAMING_SNAKE_CASE_ : Dict=12 , SCREAMING_SNAKE_CASE_ : Optional[Any]=3 , SCREAMING_SNAKE_CASE_ : Dict=16 , SCREAMING_SNAKE_CASE_ : Dict=288 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=1 , SCREAMING_SNAKE_CASE_ : Any=1e-05 , SCREAMING_SNAKE_CASE_ : Optional[Any]=False , SCREAMING_SNAKE_CASE_ : Optional[Any]=True , SCREAMING_SNAKE_CASE_ : Dict=False , **SCREAMING_SNAKE_CASE_ : Optional[int] , ): super().__init__(**__a ) lowerCamelCase__ = hidden_size lowerCamelCase__ = num_hidden_layers lowerCamelCase__ = num_channels lowerCamelCase__ = patch_size lowerCamelCase__ = image_size lowerCamelCase__ = initializer_factor lowerCamelCase__ = layer_norm_eps lowerCamelCase__ = stop_gradient lowerCamelCase__ = share_layernorm lowerCamelCase__ = remove_last_layer @classmethod def __UpperCAmelCase ( cls : List[str] , SCREAMING_SNAKE_CASE_ : Union[str, os.PathLike] , **SCREAMING_SNAKE_CASE_ : List[str] ): lowerCamelCase__ , lowerCamelCase__ = cls.get_config_dict(__a , **__a ) if config_dict.get("""model_type""" ) == "bridgetower": lowerCamelCase__ = config_dict["""text_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(__a , **__a ) class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ ): snake_case = """bridgetower_text_model""" def __init__( self : Tuple , SCREAMING_SNAKE_CASE_ : List[Any]=5_0265 , SCREAMING_SNAKE_CASE_ : int=768 , SCREAMING_SNAKE_CASE_ : int=12 , SCREAMING_SNAKE_CASE_ : str=12 , SCREAMING_SNAKE_CASE_ : Any=1 , SCREAMING_SNAKE_CASE_ : Dict=3072 , SCREAMING_SNAKE_CASE_ : int="gelu" , SCREAMING_SNAKE_CASE_ : Tuple=0.1 , SCREAMING_SNAKE_CASE_ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE_ : Tuple=514 , SCREAMING_SNAKE_CASE_ : List[Any]=1 , SCREAMING_SNAKE_CASE_ : Tuple=1e-05 , SCREAMING_SNAKE_CASE_ : Any=1 , SCREAMING_SNAKE_CASE_ : Any=0 , SCREAMING_SNAKE_CASE_ : Dict=2 , SCREAMING_SNAKE_CASE_ : Optional[Any]="absolute" , SCREAMING_SNAKE_CASE_ : str=True , **SCREAMING_SNAKE_CASE_ : int , ): super().__init__(**__a ) lowerCamelCase__ = vocab_size lowerCamelCase__ = hidden_size lowerCamelCase__ = num_hidden_layers lowerCamelCase__ = num_attention_heads lowerCamelCase__ = hidden_act lowerCamelCase__ = initializer_factor lowerCamelCase__ = intermediate_size lowerCamelCase__ = hidden_dropout_prob lowerCamelCase__ = attention_probs_dropout_prob lowerCamelCase__ = max_position_embeddings lowerCamelCase__ = type_vocab_size lowerCamelCase__ = layer_norm_eps lowerCamelCase__ = position_embedding_type lowerCamelCase__ = use_cache lowerCamelCase__ = pad_token_id lowerCamelCase__ = bos_token_id lowerCamelCase__ = eos_token_id @classmethod def __UpperCAmelCase ( cls : Optional[int] , SCREAMING_SNAKE_CASE_ : Union[str, os.PathLike] , **SCREAMING_SNAKE_CASE_ : List[str] ): lowerCamelCase__ , lowerCamelCase__ = cls.get_config_dict(__a , **__a ) if config_dict.get("""model_type""" ) == "bridgetower": lowerCamelCase__ = config_dict["""text_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(__a , **__a ) class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ ): snake_case = """bridgetower""" def __init__( self : int , SCREAMING_SNAKE_CASE_ : Optional[Any]=True , SCREAMING_SNAKE_CASE_ : Optional[Any]="gelu" , SCREAMING_SNAKE_CASE_ : str=768 , SCREAMING_SNAKE_CASE_ : Optional[Any]=1 , SCREAMING_SNAKE_CASE_ : List[str]=1e-05 , SCREAMING_SNAKE_CASE_ : List[Any]=False , SCREAMING_SNAKE_CASE_ : int="add" , SCREAMING_SNAKE_CASE_ : Optional[int]=12 , SCREAMING_SNAKE_CASE_ : List[str]=6 , SCREAMING_SNAKE_CASE_ : Dict=False , SCREAMING_SNAKE_CASE_ : Optional[int]=False , SCREAMING_SNAKE_CASE_ : Optional[int]=None , SCREAMING_SNAKE_CASE_ : Tuple=None , **SCREAMING_SNAKE_CASE_ : str , ): # TODO: remove this once the Hub files are updated. lowerCamelCase__ = kwargs.pop("""text_config_dict""" , __a ) lowerCamelCase__ = kwargs.pop("""vision_config_dict""" , __a ) super().__init__(**__a ) lowerCamelCase__ = share_cross_modal_transformer_layers lowerCamelCase__ = hidden_act lowerCamelCase__ = hidden_size lowerCamelCase__ = initializer_factor lowerCamelCase__ = layer_norm_eps lowerCamelCase__ = share_link_tower_layers lowerCamelCase__ = link_tower_type lowerCamelCase__ = num_attention_heads lowerCamelCase__ = num_hidden_layers lowerCamelCase__ = tie_word_embeddings lowerCamelCase__ = init_layernorm_from_vision_encoder if text_config is None: lowerCamelCase__ = {} logger.info("""`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values.""" ) if vision_config is None: lowerCamelCase__ = {} logger.info("""`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.""" ) lowerCamelCase__ = BridgeTowerTextConfig(**__a ) lowerCamelCase__ = BridgeTowerVisionConfig(**__a ) @classmethod def __UpperCAmelCase ( cls : str , SCREAMING_SNAKE_CASE_ : BridgeTowerTextConfig , SCREAMING_SNAKE_CASE_ : BridgeTowerVisionConfig , **SCREAMING_SNAKE_CASE_ : Union[str, Any] ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__a ) def __UpperCAmelCase ( self : Union[str, Any] ): lowerCamelCase__ = copy.deepcopy(self.__dict__ ) lowerCamelCase__ = self.text_config.to_dict() lowerCamelCase__ = self.vision_config.to_dict() lowerCamelCase__ = self.__class__.model_type return output
129
'''simple docstring''' import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowerCAmelCase_ ( snake_case_ : List[Any] , snake_case_ : Union[str, Any]=0.999 , snake_case_ : Tuple="cosine" , ) -> Optional[Any]: '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(snake_case_ : Optional[int] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(snake_case_ : Optional[Any] ): return math.exp(t * -12.0 ) else: raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) UpperCAmelCase_ = [] for i in range(snake_case_ ): UpperCAmelCase_ = i / num_diffusion_timesteps UpperCAmelCase_ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(snake_case_ ) / alpha_bar_fn(snake_case_ ) , snake_case_ ) ) return torch.tensor(snake_case_ , dtype=torch.floataa ) class __A ( UpperCamelCase__ , UpperCamelCase__ ): a__ : Tuple = [e.name for e in KarrasDiffusionSchedulers] a__ : Optional[Any] = 2 @register_to_config def __init__(self : Union[str, Any] , __a : int = 1000 , __a : float = 0.0_00_85 , __a : float = 0.0_12 , __a : str = "linear" , __a : Optional[Union[np.ndarray, List[float]]] = None , __a : str = "epsilon" , __a : Optional[bool] = False , __a : Optional[bool] = False , __a : float = 1.0 , __a : str = "linspace" , __a : int = 0 , ): if trained_betas is not None: UpperCAmelCase_ = torch.tensor(__a , dtype=torch.floataa ) elif beta_schedule == "linear": UpperCAmelCase_ = torch.linspace(__a , __a , __a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. UpperCAmelCase_ = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , __a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule UpperCAmelCase_ = betas_for_alpha_bar(__a , alpha_transform_type="cosine" ) elif beta_schedule == "exp": UpperCAmelCase_ = betas_for_alpha_bar(__a , alpha_transform_type="exp" ) else: raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}""" ) UpperCAmelCase_ = 1.0 - self.betas UpperCAmelCase_ = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(__a , __a , __a ) UpperCAmelCase_ = use_karras_sigmas def _lowercase (self : Optional[Any] , __a : Union[str, Any] , __a : Tuple=None ): if schedule_timesteps is None: UpperCAmelCase_ = self.timesteps UpperCAmelCase_ = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: UpperCAmelCase_ = 1 if len(__a ) > 1 else 0 else: UpperCAmelCase_ = timestep.cpu().item() if torch.is_tensor(__a ) else timestep UpperCAmelCase_ = self._index_counter[timestep_int] return indices[pos].item() @property def _lowercase (self : List[Any] ): # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _lowercase (self : Optional[Any] , __a : torch.FloatTensor , __a : Union[float, torch.FloatTensor] , ): UpperCAmelCase_ = self.index_for_timestep(__a ) UpperCAmelCase_ = self.sigmas[step_index] UpperCAmelCase_ = sample / ((sigma**2 + 1) ** 0.5) return sample def _lowercase (self : Any , __a : int , __a : Union[str, torch.device] = None , __a : Optional[int] = None , ): UpperCAmelCase_ = num_inference_steps UpperCAmelCase_ = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": UpperCAmelCase_ = np.linspace(0 , num_train_timesteps - 1 , __a , dtype=__a )[::-1].copy() elif self.config.timestep_spacing == "leading": UpperCAmelCase_ = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 UpperCAmelCase_ = (np.arange(0 , __a ) * step_ratio).round()[::-1].copy().astype(__a ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": UpperCAmelCase_ = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 UpperCAmelCase_ = (np.arange(__a , 0 , -step_ratio )).round().copy().astype(__a ) timesteps -= 1 else: raise ValueError( f"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.""" ) UpperCAmelCase_ = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) UpperCAmelCase_ = np.log(__a ) UpperCAmelCase_ = np.interp(__a , np.arange(0 , len(__a ) ) , __a ) if self.config.use_karras_sigmas: UpperCAmelCase_ = self._convert_to_karras(in_sigmas=__a , num_inference_steps=self.num_inference_steps ) UpperCAmelCase_ = np.array([self._sigma_to_t(__a , __a ) for sigma in sigmas] ) UpperCAmelCase_ = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) UpperCAmelCase_ = torch.from_numpy(__a ).to(device=__a ) UpperCAmelCase_ = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) UpperCAmelCase_ = torch.from_numpy(__a ) UpperCAmelCase_ = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(__a ).startswith("mps" ): # mps does not support float64 UpperCAmelCase_ = timesteps.to(__a , dtype=torch.floataa ) else: UpperCAmelCase_ = timesteps.to(device=__a ) # empty dt and derivative UpperCAmelCase_ = None UpperCAmelCase_ = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter UpperCAmelCase_ = defaultdict(__a ) def _lowercase (self : int , __a : Optional[Any] , __a : List[str] ): # get log sigma UpperCAmelCase_ = np.log(__a ) # get distribution UpperCAmelCase_ = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range UpperCAmelCase_ = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) UpperCAmelCase_ = low_idx + 1 UpperCAmelCase_ = log_sigmas[low_idx] UpperCAmelCase_ = log_sigmas[high_idx] # interpolate sigmas UpperCAmelCase_ = (low - log_sigma) / (low - high) UpperCAmelCase_ = np.clip(__a , 0 , 1 ) # transform interpolation to time range UpperCAmelCase_ = (1 - w) * low_idx + w * high_idx UpperCAmelCase_ = t.reshape(sigma.shape ) return t def _lowercase (self : Dict , __a : torch.FloatTensor , __a : Optional[int] ): UpperCAmelCase_ = in_sigmas[-1].item() UpperCAmelCase_ = in_sigmas[0].item() UpperCAmelCase_ = 7.0 # 7.0 is the value used in the paper UpperCAmelCase_ = np.linspace(0 , 1 , __a ) UpperCAmelCase_ = sigma_min ** (1 / rho) UpperCAmelCase_ = sigma_max ** (1 / rho) UpperCAmelCase_ = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _lowercase (self : List[str] ): return self.dt is None def _lowercase (self : List[Any] , __a : Union[torch.FloatTensor, np.ndarray] , __a : Union[float, torch.FloatTensor] , __a : Union[torch.FloatTensor, np.ndarray] , __a : bool = True , ): UpperCAmelCase_ = self.index_for_timestep(__a ) # advance index counter by 1 UpperCAmelCase_ = timestep.cpu().item() if torch.is_tensor(__a ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: UpperCAmelCase_ = self.sigmas[step_index] UpperCAmelCase_ = self.sigmas[step_index + 1] else: # 2nd order / Heun's method UpperCAmelCase_ = self.sigmas[step_index - 1] UpperCAmelCase_ = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API UpperCAmelCase_ = 0 UpperCAmelCase_ = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": UpperCAmelCase_ = sigma_hat if self.state_in_first_order else sigma_next UpperCAmelCase_ = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": UpperCAmelCase_ = sigma_hat if self.state_in_first_order else sigma_next UpperCAmelCase_ = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": UpperCAmelCase_ = model_output else: raise ValueError( f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""" ) if self.config.clip_sample: UpperCAmelCase_ = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order UpperCAmelCase_ = (sample - pred_original_sample) / sigma_hat # 3. delta timestep UpperCAmelCase_ = sigma_next - sigma_hat # store for 2nd order step UpperCAmelCase_ = derivative UpperCAmelCase_ = dt UpperCAmelCase_ = sample else: # 2. 2nd order / Heun's method UpperCAmelCase_ = (sample - pred_original_sample) / sigma_next UpperCAmelCase_ = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample UpperCAmelCase_ = self.dt UpperCAmelCase_ = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=__a ) def _lowercase (self : Any , __a : torch.FloatTensor , __a : torch.FloatTensor , __a : torch.FloatTensor , ): # Make sure sigmas and timesteps have the same device and dtype as original_samples UpperCAmelCase_ = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(__a ): # mps does not support float64 UpperCAmelCase_ = self.timesteps.to(original_samples.device , dtype=torch.floataa ) UpperCAmelCase_ = timesteps.to(original_samples.device , dtype=torch.floataa ) else: UpperCAmelCase_ = self.timesteps.to(original_samples.device ) UpperCAmelCase_ = timesteps.to(original_samples.device ) UpperCAmelCase_ = [self.index_for_timestep(__a , __a ) for t in timesteps] UpperCAmelCase_ = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): UpperCAmelCase_ = sigma.unsqueeze(-1 ) UpperCAmelCase_ = original_samples + noise * sigma return noisy_samples def __len__(self : str ): return self.config.num_train_timesteps
78
0
"""simple docstring""" def a__ ( __SCREAMING_SNAKE_CASE ) -> int: assert isinstance(snake_case_ , snake_case_ ), F"The input value of [n={number}] is not an integer" if number == 1: return 2 elif number < 1: __lowerCAmelCase: List[str] = F"The input value of [n={number}] has to be > 0" raise ValueError(snake_case_ ) else: __lowerCAmelCase: Optional[int] = sylvester(number - 1 ) __lowerCAmelCase: int = num - 1 __lowerCAmelCase: int = num return lower * upper + 1 if __name__ == "__main__": print(F'''The 8th number in Sylvester\'s sequence: {sylvester(8)}''')
346
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __A ( UpperCamelCase__ ): a__ : List[str] = """Salesforce/blip-image-captioning-base""" a__ : Optional[Any] = ( """This is a tool that generates a description of an image. It takes an input named `image` which should be the """ """image to caption, and returns a text that contains the description in English.""" ) a__ : str = """image_captioner""" a__ : List[str] = AutoModelForVisionaSeq a__ : int = ["""image"""] a__ : Optional[Any] = ["""text"""] def __init__(self : Any , *__a : Dict , **__a : Union[str, Any] ): requires_backends(self , ["vision"] ) super().__init__(*__a , **__a ) def _lowercase (self : Union[str, Any] , __a : "Image" ): return self.pre_processor(images=__a , return_tensors="pt" ) def _lowercase (self : List[str] , __a : Dict ): return self.model.generate(**__a ) def _lowercase (self : int , __a : Optional[Any] ): return self.pre_processor.batch_decode(__a , skip_special_tokens=__a )[0].strip()
78
0
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class A__ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Tuple , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Optional[Any]=7 , _SCREAMING_SNAKE_CASE : Union[str, Any]=3 , _SCREAMING_SNAKE_CASE : Union[str, Any]=18 , _SCREAMING_SNAKE_CASE : List[Any]=30 , _SCREAMING_SNAKE_CASE : List[str]=400 , _SCREAMING_SNAKE_CASE : Optional[int]=True , _SCREAMING_SNAKE_CASE : List[str]=None , _SCREAMING_SNAKE_CASE : Any=True , _SCREAMING_SNAKE_CASE : Any=None , _SCREAMING_SNAKE_CASE : Any=True , ): """simple docstring""" UpperCamelCase = size if size is not None else {'shortest_edge': 20} UpperCamelCase = crop_size if crop_size is not None else {'height': 18, 'width': 18} UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = num_channels UpperCamelCase = image_size UpperCamelCase = min_resolution UpperCamelCase = max_resolution UpperCamelCase = do_resize UpperCamelCase = size UpperCamelCase = do_center_crop UpperCamelCase = crop_size UpperCamelCase = do_flip_channel_order def _SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class A__ ( UpperCamelCase__ , unittest.TestCase ): '''simple docstring''' snake_case__ = MobileViTImageProcessor if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" UpperCamelCase = MobileViTImageProcessingTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__a , 'do_resize' ) ) self.assertTrue(hasattr(__a , 'size' ) ) self.assertTrue(hasattr(__a , 'do_center_crop' ) ) self.assertTrue(hasattr(__a , 'center_crop' ) ) self.assertTrue(hasattr(__a , 'do_flip_channel_order' ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 20} ) self.assertEqual(image_processor.crop_size , {'height': 18, 'width': 18} ) UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'shortest_edge': 42} ) self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84} ) def _SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" pass def _SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a ) for image in image_inputs: self.assertIsInstance(__a , Image.Image ) # Test not batched input UpperCamelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched UpperCamelCase = image_processing(__a , 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 _SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , numpify=__a ) for image in image_inputs: self.assertIsInstance(__a , np.ndarray ) # Test not batched input UpperCamelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched UpperCamelCase = image_processing(__a , 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 _SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , torchify=__a ) for image in image_inputs: self.assertIsInstance(__a , torch.Tensor ) # Test not batched input UpperCamelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched UpperCamelCase = image_processing(__a , 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'], ) , )
280
'''simple docstring''' import logging import math from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union import torch from .tensor_utils import tensor_tree_map, tree_map def lowerCAmelCase_ ( snake_case_ : Union[dict, list, tuple, torch.Tensor] ) -> List[Tuple[int, ...]]: '''simple docstring''' UpperCAmelCase_ = [] if isinstance(snake_case_ , snake_case_ ): for v in tree.values(): shapes.extend(_fetch_dims(snake_case_ ) ) elif isinstance(snake_case_ , (list, tuple) ): for t in tree: shapes.extend(_fetch_dims(snake_case_ ) ) elif isinstance(snake_case_ , torch.Tensor ): shapes.append(tree.shape ) else: raise ValueError("Not supported" ) return shapes @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : Tuple[int, ...] ) -> Tuple[int, ...]: '''simple docstring''' UpperCAmelCase_ = [] for d in reversed(snake_case_ ): idx.append(flat_idx % d ) UpperCAmelCase_ = flat_idx // d return tuple(reversed(snake_case_ ) ) @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : Sequence[int] , snake_case_ : Sequence[int] , snake_case_ : Sequence[int] , snake_case_ : Optional[Sequence[bool]] = None , snake_case_ : Optional[Sequence[bool]] = None , ) -> List[Tuple[slice, ...]]: '''simple docstring''' def reduce_edge_list(snake_case_ : List[bool] ) -> None: UpperCAmelCase_ = True for i in range(len(snake_case_ ) ): UpperCAmelCase_ = -1 * (i + 1) l[reversed_idx] &= tally UpperCAmelCase_ = l[reversed_idx] if start_edges is None: UpperCAmelCase_ = [s == 0 for s in start] reduce_edge_list(snake_case_ ) if end_edges is None: UpperCAmelCase_ = [e == (d - 1) for e, d in zip(snake_case_ , snake_case_ )] reduce_edge_list(snake_case_ ) # Base cases. Either start/end are empty and we're done, or the final, # one-dimensional tensor can be simply sliced if len(snake_case_ ) == 0: return [()] elif len(snake_case_ ) == 1: return [(slice(start[0] , end[0] + 1 ),)] UpperCAmelCase_ = [] UpperCAmelCase_ = [] # Dimensions common to start and end can be selected directly for s, e in zip(snake_case_ , snake_case_ ): if s == e: path_list.append(slice(snake_case_ , s + 1 ) ) else: break UpperCAmelCase_ = tuple(snake_case_ ) UpperCAmelCase_ = len(snake_case_ ) # start == end, and we're done if divergence_idx == len(snake_case_ ): return [path] def upper() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None UpperCAmelCase_ = start[divergence_idx] return tuple( path + (slice(snake_case_ , sdi + 1 ),) + s for s in _get_minimal_slice_set( start[divergence_idx + 1 :] , [d - 1 for d in dims[divergence_idx + 1 :]] , dims[divergence_idx + 1 :] , start_edges=start_edges[divergence_idx + 1 :] , end_edges=[True for _ in end_edges[divergence_idx + 1 :]] , ) ) def lower() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None UpperCAmelCase_ = end[divergence_idx] return tuple( path + (slice(snake_case_ , edi + 1 ),) + s for s in _get_minimal_slice_set( [0 for _ in start[divergence_idx + 1 :]] , end[divergence_idx + 1 :] , dims[divergence_idx + 1 :] , start_edges=[True for _ in start_edges[divergence_idx + 1 :]] , end_edges=end_edges[divergence_idx + 1 :] , ) ) # If both start and end are at the edges of the subtree rooted at # divergence_idx, we can just select the whole subtree at once if start_edges[divergence_idx] and end_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] + 1 ),) ) # If just start is at the edge, we can grab almost all of the subtree, # treating only the ragged bottom edge as an edge case elif start_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] ),) ) slices.extend(lower() ) # Analogous to the previous case, but the top is ragged this time elif end_edges[divergence_idx]: slices.extend(upper() ) slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] + 1 ),) ) # If both sides of the range are ragged, we need to handle both sides # separately. If there's contiguous meat in between them, we can index it # in one big chunk else: slices.extend(upper() ) UpperCAmelCase_ = end[divergence_idx] - start[divergence_idx] if middle_ground > 1: slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] ),) ) slices.extend(lower() ) return slices @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : torch.Tensor , snake_case_ : int , snake_case_ : int , snake_case_ : int ) -> torch.Tensor: '''simple docstring''' UpperCAmelCase_ = t.shape[:no_batch_dims] UpperCAmelCase_ = list(_flat_idx_to_idx(snake_case_ , snake_case_ ) ) # _get_minimal_slice_set is inclusive UpperCAmelCase_ = list(_flat_idx_to_idx(flat_end - 1 , snake_case_ ) ) # Get an ordered list of slices to perform UpperCAmelCase_ = _get_minimal_slice_set( snake_case_ , snake_case_ , snake_case_ , ) UpperCAmelCase_ = [t[s] for s in slices] return torch.cat([s.view((-1,) + t.shape[no_batch_dims:] ) for s in sliced_tensors] ) def lowerCAmelCase_ ( snake_case_ : Callable , snake_case_ : Dict[str, Any] , snake_case_ : int , snake_case_ : int , snake_case_ : bool = False , snake_case_ : Any = None , snake_case_ : bool = False , ) -> Any: '''simple docstring''' if not (len(snake_case_ ) > 0): raise ValueError("Must provide at least one input" ) UpperCAmelCase_ = [shape[:no_batch_dims] for shape in _fetch_dims(snake_case_ )] UpperCAmelCase_ = tuple([max(snake_case_ ) for s in zip(*snake_case_ )] ) def _prep_inputs(snake_case_ : torch.Tensor ) -> torch.Tensor: if not low_mem: if not sum(t.shape[:no_batch_dims] ) == no_batch_dims: UpperCAmelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) UpperCAmelCase_ = t.reshape(-1 , *t.shape[no_batch_dims:] ) else: UpperCAmelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) return t UpperCAmelCase_ = tensor_tree_map(_prep_inputs , snake_case_ ) UpperCAmelCase_ = None if _out is not None: UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.view([-1] + list(t.shape[no_batch_dims:] ) ) , _out ) UpperCAmelCase_ = 1 for d in orig_batch_dims: flat_batch_dim *= d UpperCAmelCase_ = flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0) def _select_chunk(snake_case_ : torch.Tensor ) -> torch.Tensor: return t[i : i + chunk_size] if t.shape[0] != 1 else t UpperCAmelCase_ = 0 UpperCAmelCase_ = prepped_outputs for _ in range(snake_case_ ): # Chunk the input if not low_mem: UpperCAmelCase_ = _select_chunk else: UpperCAmelCase_ = partial( _chunk_slice , flat_start=snake_case_ , flat_end=min(snake_case_ , i + chunk_size ) , no_batch_dims=len(snake_case_ ) , ) UpperCAmelCase_ = tensor_tree_map(snake_case_ , snake_case_ ) # Run the layer on the chunk UpperCAmelCase_ = layer(**snake_case_ ) # Allocate space for the output if out is None: UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.new_zeros((flat_batch_dim,) + t.shape[1:] ) , snake_case_ ) # Put the chunk in its pre-allocated space if isinstance(snake_case_ , snake_case_ ): def assign(snake_case_ : dict , snake_case_ : dict ) -> None: for k, v in da.items(): if isinstance(snake_case_ , snake_case_ ): assign(snake_case_ , da[k] ) else: if _add_into_out: v[i : i + chunk_size] += da[k] else: UpperCAmelCase_ = da[k] assign(snake_case_ , snake_case_ ) elif isinstance(snake_case_ , snake_case_ ): for xa, xa in zip(snake_case_ , snake_case_ ): if _add_into_out: xa[i : i + chunk_size] += xa else: UpperCAmelCase_ = xa elif isinstance(snake_case_ , torch.Tensor ): if _add_into_out: out[i : i + chunk_size] += output_chunk else: UpperCAmelCase_ = output_chunk else: raise ValueError("Not supported" ) i += chunk_size UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.view(orig_batch_dims + t.shape[1:] ) , snake_case_ ) return out class __A : def __init__(self : Dict , __a : int = 512 , ): UpperCAmelCase_ = max_chunk_size UpperCAmelCase_ = None UpperCAmelCase_ = None def _lowercase (self : List[Any] , __a : Callable , __a : tuple , __a : int ): logging.info("Tuning chunk size..." ) if min_chunk_size >= self.max_chunk_size: return min_chunk_size UpperCAmelCase_ = [2**l for l in range(int(math.log(self.max_chunk_size , 2 ) ) + 1 )] UpperCAmelCase_ = [c for c in candidates if c > min_chunk_size] UpperCAmelCase_ = [min_chunk_size] + candidates candidates[-1] += 4 def test_chunk_size(__a : int ) -> bool: try: with torch.no_grad(): fn(*__a , chunk_size=__a ) return True except RuntimeError: return False UpperCAmelCase_ = 0 UpperCAmelCase_ = len(__a ) - 1 while i > min_viable_chunk_size_index: UpperCAmelCase_ = test_chunk_size(candidates[i] ) if not viable: UpperCAmelCase_ = (min_viable_chunk_size_index + i) // 2 else: UpperCAmelCase_ = i UpperCAmelCase_ = (i + len(__a ) - 1) // 2 return candidates[min_viable_chunk_size_index] def _lowercase (self : int , __a : Iterable , __a : Iterable ): UpperCAmelCase_ = True for aa, aa in zip(__a , __a ): assert type(__a ) == type(__a ) if isinstance(__a , (list, tuple) ): consistent &= self._compare_arg_caches(__a , __a ) elif isinstance(__a , __a ): UpperCAmelCase_ = [v for _, v in sorted(aa.items() , key=lambda __a : x[0] )] UpperCAmelCase_ = [v for _, v in sorted(aa.items() , key=lambda __a : x[0] )] consistent &= self._compare_arg_caches(__a , __a ) else: consistent &= aa == aa return consistent def _lowercase (self : List[str] , __a : Callable , __a : tuple , __a : int , ): UpperCAmelCase_ = True UpperCAmelCase_ = tree_map(lambda __a : a.shape if isinstance(__a , torch.Tensor ) else a , __a , __a ) if self.cached_arg_data is not None: # If args have changed shape/value, we need to re-tune assert len(self.cached_arg_data ) == len(__a ) UpperCAmelCase_ = self._compare_arg_caches(self.cached_arg_data , __a ) else: # Otherwise, we can reuse the precomputed value UpperCAmelCase_ = False if not consistent: UpperCAmelCase_ = self._determine_favorable_chunk_size( __a , __a , __a , ) UpperCAmelCase_ = arg_data assert self.cached_chunk_size is not None return self.cached_chunk_size
78
0
import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration from transformers.models.ta.modeling_flax_ta import shift_tokens_right @require_torch @require_sentencepiece @require_tokenizers @require_flax class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' @slow def _snake_case ( self : List[str] ): '''simple docstring''' __lowerCamelCase : Dict = FlaxMTaForConditionalGeneration.from_pretrained("""google/mt5-small""" ) __lowerCamelCase : Tuple = AutoTokenizer.from_pretrained("""google/mt5-small""" ) __lowerCamelCase : Optional[int] = tokenizer("""Hello there""" , return_tensors="""np""" ).input_ids __lowerCamelCase : List[Any] = tokenizer("""Hi I am""" , return_tensors="""np""" ).input_ids __lowerCamelCase : Optional[int] = shift_tokens_right(__a , model.config.pad_token_id , model.config.decoder_start_token_id ) __lowerCamelCase : int = model(__a , decoder_input_ids=__a ).logits __lowerCamelCase : Union[str, Any] = optax.softmax_cross_entropy(__a , onehot(__a , logits.shape[-1] ) ).mean() __lowerCamelCase : int = -(labels.shape[-1] * loss.item()) __lowerCamelCase : Any = -84.9_127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
519
'''simple docstring''' import copy import re class __A : a__ : Optional[int] = """hp""" a__ : Optional[Any] = {} a__ : List[Any] = None @classmethod def _lowercase (cls : Optional[int] , __a : str , __a : Tuple ): UpperCAmelCase_ = prefix UpperCAmelCase_ = defaults cls.build_naming_info() @staticmethod def _lowercase (__a : List[Any] , __a : List[str] ): if len(__a ) == 0: return "" UpperCAmelCase_ = None if any(char.isdigit() for char in word ): raise Exception(f"""Parameters should not contain numbers: '{word}' contains a number""" ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(__a ) + 1 ): UpperCAmelCase_ = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: UpperCAmelCase_ = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(__a : Union[str, Any] ): UpperCAmelCase_ = "" while integer != 0: UpperCAmelCase_ = chr(ord("A" ) + integer % 10 ) + s integer //= 10 return s UpperCAmelCase_ = 0 while True: UpperCAmelCase_ = word + "#" + int_to_alphabetic(__a ) if sword in info["reverse_short_word"]: continue else: UpperCAmelCase_ = sword break UpperCAmelCase_ = short_word UpperCAmelCase_ = word return short_word @staticmethod def _lowercase (__a : List[str] , __a : Union[str, Any] ): UpperCAmelCase_ = param_name.split("_" ) UpperCAmelCase_ = [TrialShortNamer.shortname_for_word(__a , __a ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name UpperCAmelCase_ = ["", "_"] for separator in separators: UpperCAmelCase_ = separator.join(__a ) if shortname not in info["reverse_short_param"]: UpperCAmelCase_ = shortname UpperCAmelCase_ = param_name return shortname return param_name @staticmethod def _lowercase (__a : int , __a : Union[str, Any] ): UpperCAmelCase_ = TrialShortNamer.shortname_for_key(__a , __a ) UpperCAmelCase_ = short_name UpperCAmelCase_ = param_name @classmethod def _lowercase (cls : Any ): if cls.NAMING_INFO is not None: return UpperCAmelCase_ = { "short_word": {}, "reverse_short_word": {}, "short_param": {}, "reverse_short_param": {}, } UpperCAmelCase_ = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(__a , __a ) UpperCAmelCase_ = info @classmethod def _lowercase (cls : int , __a : Optional[int] ): cls.build_naming_info() assert cls.PREFIX is not None UpperCAmelCase_ = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(f"""You should provide a default value for the param name {k} with value {v}""" ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue UpperCAmelCase_ = cls.NAMING_INFO["short_param"][k] if isinstance(__a , __a ): UpperCAmelCase_ = 1 if v else 0 UpperCAmelCase_ = "" if isinstance(__a , (int, float) ) else "-" UpperCAmelCase_ = f"""{key}{sep}{v}""" name.append(__a ) return "_".join(__a ) @classmethod def _lowercase (cls : Dict , __a : Dict ): UpperCAmelCase_ = repr[len(cls.PREFIX ) + 1 :] if repr == "": UpperCAmelCase_ = [] else: UpperCAmelCase_ = repr.split("_" ) UpperCAmelCase_ = {} for value in values: if "-" in value: UpperCAmelCase_ , UpperCAmelCase_ = value.split("-" ) else: UpperCAmelCase_ = re.sub("[0-9.]" , "" , __a ) UpperCAmelCase_ = float(re.sub("[^0-9.]" , "" , __a ) ) UpperCAmelCase_ = cls.NAMING_INFO["reverse_short_param"][p_k] UpperCAmelCase_ = p_v for k in cls.DEFAULTS: if k not in parameters: UpperCAmelCase_ = cls.DEFAULTS[k] return parameters
78
0
"""simple docstring""" import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness __SCREAMING_SNAKE_CASE : Union[str, Any] = '\\n@misc{chen2021evaluating,\n title={Evaluating Large Language Models Trained on Code},\n author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \\nand Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \\nand Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \\nand Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \\nand Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \\nand Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \\nand Mohammad Bavarian and Clemens Winter and Philippe Tillet \\nand Felipe Petroski Such and Dave Cummings and Matthias Plappert \\nand Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \\nand William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \\nand Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \\nand William Saunders and Christopher Hesse and Andrew N. Carr \\nand Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \\nand Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \\nand Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \\nand Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},\n year={2021},\n eprint={2107.03374},\n archivePrefix={arXiv},\n primaryClass={cs.LG}\n}\n' __SCREAMING_SNAKE_CASE : str = '\\nThis metric implements the evaluation harness for the HumanEval problem solving dataset\ndescribed in the paper "Evaluating Large Language Models Trained on Code"\n(https://arxiv.org/abs/2107.03374).\n' __SCREAMING_SNAKE_CASE : Tuple = '\nCalculates how good are predictions given some references, using certain scores\nArgs:\n predictions: list of candidates to evaluate. Each candidates should be a list\n of strings with several code candidates to solve the problem.\n references: a list with a test for each prediction. Each test should evaluate the\n correctness of a code candidate.\n k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])\n num_workers: number of workers used to evaluate the canidate programs (Default: 4).\n timeout:\nReturns:\n pass_at_k: dict with pass rates for each k\n results: dict with granular results of each unittest\nExamples:\n >>> code_eval = datasets.load_metric("code_eval")\n >>> test_cases = ["assert add(2,3)==5"]\n >>> candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]]\n >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])\n >>> print(pass_at_k)\n {\'pass@1\': 0.5, \'pass@2\': 1.0}\n' __SCREAMING_SNAKE_CASE : Optional[int] = '\n################################################################################\n !!!WARNING!!!\n################################################################################\nThe "code_eval" metric executes untrusted model-generated code in Python.\nAlthough it is highly unlikely that model-generated code will do something\novertly malicious in response to this test suite, model-generated code may act\ndestructively due to a lack of model capability or alignment.\nUsers are strongly encouraged to sandbox this evaluation suite so that it\ndoes not perform destructive actions on their host or network. For more\ninformation on how OpenAI sandboxes its code, see the paper "Evaluating Large\nLanguage Models Trained on Code" (https://arxiv.org/abs/2107.03374).\n\nOnce you have read this disclaimer and taken appropriate precautions,\nset the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this\nwith:\n\n>>> import os\n>>> os.environ["HF_ALLOW_CODE_EVAL"] = "1"\n\n################################################################################\\n' __SCREAMING_SNAKE_CASE : Optional[Any] = 'The MIT License\n\nCopyright (c) OpenAI (https://openai.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class lowerCamelCase_( datasets.Metric ): '''simple docstring''' def snake_case__ ( self ): return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''' ) ), '''references''': datasets.Value('''string''' ), } ) , homepage='''https://github.com/openai/human-eval''' , codebase_urls=['''https://github.com/openai/human-eval'''] , reference_urls=['''https://github.com/openai/human-eval'''] , license=_LICENSE , ) def snake_case__ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=[1, 1_0, 1_0_0] , lowerCamelCase__=4 , lowerCamelCase__=3.0 ): if os.getenv('''HF_ALLOW_CODE_EVAL''' , 0 ) != "1": raise ValueError(_WARNING ) if os.name == "nt": raise NotImplementedError('''This metric is currently not supported on Windows.''' ) with ThreadPoolExecutor(max_workers=__a ) as executor: _lowerCamelCase = [] _lowerCamelCase = Counter() _lowerCamelCase = 0 _lowerCamelCase = defaultdict(__a ) for task_id, (candidates, test_case) in enumerate(zip(__a , __a ) ): for candidate in candidates: _lowerCamelCase = candidate + '''\n''' + test_case _lowerCamelCase = (test_program, timeout, task_id, completion_id[task_id]) _lowerCamelCase = executor.submit(__a , *__a ) futures.append(__a ) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(__a ): _lowerCamelCase = future.result() results[result["task_id"]].append((result['''completion_id'''], result) ) _lowerCamelCase , _lowerCamelCase = [], [] for result in results.values(): result.sort() _lowerCamelCase = [r[1]['''passed'''] for r in result] total.append(len(__a ) ) correct.append(sum(__a ) ) _lowerCamelCase = np.array(__a ) _lowerCamelCase = np.array(__a ) _lowerCamelCase = k _lowerCamelCase = {F"""pass@{k}""": estimate_pass_at_k(__a , __a , __a ).mean() for k in ks if (total >= k).all()} return pass_at_k, results def lowerCAmelCase_( lowercase_ : Tuple , lowercase_ : Dict , lowercase_ : Optional[int] ) -> Tuple: def estimator(lowercase_ : int , lowercase_ : int , lowercase_ : int ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) ) if isinstance(snake_case_ , snake_case_ ): _lowerCamelCase = itertools.repeat(snake_case_ , len(snake_case_ ) ) else: assert len(snake_case_ ) == len(snake_case_ ) _lowerCamelCase = iter(snake_case_ ) return np.array([estimator(int(snake_case_ ) , int(snake_case_ ) , snake_case_ ) for n, c in zip(snake_case_ , snake_case_ )] )
661
'''simple docstring''' from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging SCREAMING_SNAKE_CASE_: int =logging.get_logger(__name__) class __A ( UpperCamelCase__ ): a__ : Tuple = ["""pixel_values"""] def __init__(self : int , __a : bool = True , __a : Union[int, float] = 1 / 255 , __a : bool = True , __a : int = 8 , **__a : int , ): super().__init__(**__a ) UpperCAmelCase_ = do_rescale UpperCAmelCase_ = rescale_factor UpperCAmelCase_ = do_pad UpperCAmelCase_ = pad_size def _lowercase (self : Optional[int] , __a : np.ndarray , __a : float , __a : Optional[Union[str, ChannelDimension]] = None , **__a : Optional[int] ): return rescale(__a , scale=__a , data_format=__a , **__a ) def _lowercase (self : Optional[int] , __a : np.ndarray , __a : int , __a : Optional[Union[str, ChannelDimension]] = None ): UpperCAmelCase_ , UpperCAmelCase_ = get_image_size(__a ) UpperCAmelCase_ = (old_height // size + 1) * size - old_height UpperCAmelCase_ = (old_width // size + 1) * size - old_width return pad(__a , ((0, pad_height), (0, pad_width)) , mode="symmetric" , data_format=__a ) def _lowercase (self : Tuple , __a : ImageInput , __a : Optional[bool] = None , __a : Optional[float] = None , __a : Optional[bool] = None , __a : Optional[int] = None , __a : Optional[Union[str, TensorType]] = None , __a : Union[str, ChannelDimension] = ChannelDimension.FIRST , **__a : List[str] , ): 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_pad if do_pad is not None else self.do_pad UpperCAmelCase_ = pad_size if pad_size is not None else self.pad_size UpperCAmelCase_ = make_list_of_images(__a ) if not valid_images(__a ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) # All transformations expect numpy arrays. UpperCAmelCase_ = [to_numpy_array(__a ) for image in images] if do_rescale: UpperCAmelCase_ = [self.rescale(image=__a , scale=__a ) for image in images] if do_pad: UpperCAmelCase_ = [self.pad(__a , size=__a ) for image in images] UpperCAmelCase_ = [to_channel_dimension_format(__a , __a ) for image in images] UpperCAmelCase_ = {"pixel_values": images} return BatchFeature(data=__a , tensor_type=__a )
78
0
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging a_ = logging.get_logger(__name__) class UpperCAmelCase__ ( UpperCamelCase__ ): """simple docstring""" lowerCAmelCase__ : Tuple = ["""pixel_values"""] def __init__( self: int , __lowerCAmelCase: bool = True , __lowerCAmelCase: Union[int, float] = 1 / 255 , __lowerCAmelCase: bool = True , __lowerCAmelCase: int = 8 , **__lowerCAmelCase: int , ) -> List[str]: '''simple docstring''' super().__init__(**__a ) __UpperCAmelCase = do_rescale __UpperCAmelCase = rescale_factor __UpperCAmelCase = do_pad __UpperCAmelCase = pad_size def _UpperCAmelCase ( self: Optional[int] , __lowerCAmelCase: np.ndarray , __lowerCAmelCase: float , __lowerCAmelCase: Optional[Union[str, ChannelDimension]] = None , **__lowerCAmelCase: Optional[int] ) -> Tuple: '''simple docstring''' return rescale(__a , scale=__a , data_format=__a , **__a ) def _UpperCAmelCase ( self: Optional[int] , __lowerCAmelCase: np.ndarray , __lowerCAmelCase: int , __lowerCAmelCase: Optional[Union[str, ChannelDimension]] = None ) -> int: '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase = get_image_size(__a ) __UpperCAmelCase = (old_height // size + 1) * size - old_height __UpperCAmelCase = (old_width // size + 1) * size - old_width return pad(__a , ((0, pad_height), (0, pad_width)) , mode="symmetric" , data_format=__a ) def _UpperCAmelCase ( self: Tuple , __lowerCAmelCase: ImageInput , __lowerCAmelCase: Optional[bool] = None , __lowerCAmelCase: Optional[float] = None , __lowerCAmelCase: Optional[bool] = None , __lowerCAmelCase: Optional[int] = None , __lowerCAmelCase: Optional[Union[str, TensorType]] = None , __lowerCAmelCase: Union[str, ChannelDimension] = ChannelDimension.FIRST , **__lowerCAmelCase: List[str] , ) -> List[str]: '''simple docstring''' __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_pad if do_pad is not None else self.do_pad __UpperCAmelCase = pad_size if pad_size is not None else self.pad_size __UpperCAmelCase = make_list_of_images(__a ) if not valid_images(__a ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) # All transformations expect numpy arrays. __UpperCAmelCase = [to_numpy_array(__a ) for image in images] if do_rescale: __UpperCAmelCase = [self.rescale(image=__a , scale=__a ) for image in images] if do_pad: __UpperCAmelCase = [self.pad(__a , size=__a ) for image in images] __UpperCAmelCase = [to_channel_dimension_format(__a , __a ) for image in images] __UpperCAmelCase = {"pixel_values": images} return BatchFeature(data=__a , tensor_type=__a )
221
'''simple docstring''' import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# SCREAMING_SNAKE_CASE_: Dict =[ # (stable-diffusion, HF Diffusers) ('time_embed.0.weight', 'time_embedding.linear_1.weight'), ('time_embed.0.bias', 'time_embedding.linear_1.bias'), ('time_embed.2.weight', 'time_embedding.linear_2.weight'), ('time_embed.2.bias', 'time_embedding.linear_2.bias'), ('input_blocks.0.0.weight', 'conv_in.weight'), ('input_blocks.0.0.bias', 'conv_in.bias'), ('out.0.weight', 'conv_norm_out.weight'), ('out.0.bias', 'conv_norm_out.bias'), ('out.2.weight', 'conv_out.weight'), ('out.2.bias', 'conv_out.bias'), ] SCREAMING_SNAKE_CASE_: List[Any] =[ # (stable-diffusion, HF Diffusers) ('in_layers.0', 'norm1'), ('in_layers.2', 'conv1'), ('out_layers.0', 'norm2'), ('out_layers.3', 'conv2'), ('emb_layers.1', 'time_emb_proj'), ('skip_connection', 'conv_shortcut'), ] SCREAMING_SNAKE_CASE_: Union[str, Any] =[] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks SCREAMING_SNAKE_CASE_: Any =f"down_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Tuple =f"input_blocks.{3*i + j + 1}.0." unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 SCREAMING_SNAKE_CASE_: Optional[Any] =f"down_blocks.{i}.attentions.{j}." SCREAMING_SNAKE_CASE_: List[str] =f"input_blocks.{3*i + j + 1}.1." unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks SCREAMING_SNAKE_CASE_: Union[str, Any] =f"up_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Any =f"output_blocks.{3*i + j}.0." unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.attentions.{j}." SCREAMING_SNAKE_CASE_: Optional[int] =f"output_blocks.{3*i + j}.1." unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 SCREAMING_SNAKE_CASE_: Union[str, Any] =f"down_blocks.{i}.downsamplers.0.conv." SCREAMING_SNAKE_CASE_: Union[str, Any] =f"input_blocks.{3*(i+1)}.0.op." unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.upsamplers.0." SCREAMING_SNAKE_CASE_: List[Any] =f"output_blocks.{3*i + 2}.{1 if i == 0 else 2}." unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) SCREAMING_SNAKE_CASE_: int ='mid_block.attentions.0.' SCREAMING_SNAKE_CASE_: List[Any] ='middle_block.1.' unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): SCREAMING_SNAKE_CASE_: Tuple =f"mid_block.resnets.{j}." SCREAMING_SNAKE_CASE_: Tuple =f"middle_block.{2*j}." unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: UpperCAmelCase_ = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v UpperCAmelCase_ = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# SCREAMING_SNAKE_CASE_: int =[ # (stable-diffusion, HF Diffusers) ('nin_shortcut', 'conv_shortcut'), ('norm_out', 'conv_norm_out'), ('mid.attn_1.', 'mid_block.attentions.0.'), ] for i in range(4): # down_blocks have two resnets for j in range(2): SCREAMING_SNAKE_CASE_: Tuple =f"encoder.down_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: int =f"encoder.down.{i}.block.{j}." vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: SCREAMING_SNAKE_CASE_: int =f"down_blocks.{i}.downsamplers.0." SCREAMING_SNAKE_CASE_: str =f"down.{i}.downsample." vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.upsamplers.0." SCREAMING_SNAKE_CASE_: List[str] =f"up.{3-i}.upsample." vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): SCREAMING_SNAKE_CASE_: List[str] =f"decoder.up_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Dict =f"decoder.up.{3-i}.block.{j}." vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): SCREAMING_SNAKE_CASE_: Any =f"mid_block.resnets.{i}." SCREAMING_SNAKE_CASE_: Tuple =f"mid.block_{i+1}." vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) SCREAMING_SNAKE_CASE_: int =[ # (stable-diffusion, HF Diffusers) ('norm.', 'group_norm.'), ('q.', 'query.'), ('k.', 'key.'), ('v.', 'value.'), ('proj_out.', 'proj_attn.'), ] def lowerCAmelCase_ ( snake_case_ : Tuple ) -> Tuple: '''simple docstring''' return w.reshape(*w.shape , 1 , 1 ) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v UpperCAmelCase_ = {v: vae_state_dict[k] for k, v in mapping.items()} UpperCAmelCase_ = ["q", "k", "v", "proj_out"] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if f"""mid.attn_1.{weight_name}.weight""" in k: print(f"""Reshaping {k} for SD format""" ) UpperCAmelCase_ = reshape_weight_for_sd(snake_case_ ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# SCREAMING_SNAKE_CASE_: List[Any] =[ # (stable-diffusion, HF Diffusers) ('resblocks.', 'text_model.encoder.layers.'), ('ln_1', 'layer_norm1'), ('ln_2', 'layer_norm2'), ('.c_fc.', '.fc1.'), ('.c_proj.', '.fc2.'), ('.attn', '.self_attn'), ('ln_final.', 'transformer.text_model.final_layer_norm.'), ('token_embedding.weight', 'transformer.text_model.embeddings.token_embedding.weight'), ('positional_embedding', 'transformer.text_model.embeddings.position_embedding.weight'), ] SCREAMING_SNAKE_CASE_: Dict ={re.escape(x[1]): x[0] for x in textenc_conversion_lst} SCREAMING_SNAKE_CASE_: str =re.compile('|'.join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp SCREAMING_SNAKE_CASE_: List[Any] ={'q': 0, 'k': 1, 'v': 2} def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = {} UpperCAmelCase_ = {} UpperCAmelCase_ = {} for k, v in text_enc_dict.items(): if ( k.endswith(".self_attn.q_proj.weight" ) or k.endswith(".self_attn.k_proj.weight" ) or k.endswith(".self_attn.v_proj.weight" ) ): UpperCAmelCase_ = k[: -len(".q_proj.weight" )] UpperCAmelCase_ = k[-len("q_proj.weight" )] if k_pre not in capture_qkv_weight: UpperCAmelCase_ = [None, None, None] UpperCAmelCase_ = v continue if ( k.endswith(".self_attn.q_proj.bias" ) or k.endswith(".self_attn.k_proj.bias" ) or k.endswith(".self_attn.v_proj.bias" ) ): UpperCAmelCase_ = k[: -len(".q_proj.bias" )] UpperCAmelCase_ = k[-len("q_proj.bias" )] if k_pre not in capture_qkv_bias: UpperCAmelCase_ = [None, None, None] UpperCAmelCase_ = v continue UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = torch.cat(snake_case_ ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = torch.cat(snake_case_ ) return new_state_dict def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> Union[str, Any]: '''simple docstring''' return text_enc_dict if __name__ == "__main__": SCREAMING_SNAKE_CASE_: str =argparse.ArgumentParser() parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.') parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--use_safetensors', action='store_true', help='Save weights use safetensors, default is ckpt.' ) SCREAMING_SNAKE_CASE_: Dict =parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors SCREAMING_SNAKE_CASE_: Any =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.safetensors') SCREAMING_SNAKE_CASE_: Dict =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.safetensors') SCREAMING_SNAKE_CASE_: Union[str, Any] =osp.join(args.model_path, 'text_encoder', 'model.safetensors') # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): SCREAMING_SNAKE_CASE_: Union[str, Any] =load_file(unet_path, device='cpu') else: SCREAMING_SNAKE_CASE_: int =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.bin') SCREAMING_SNAKE_CASE_: Dict =torch.load(unet_path, map_location='cpu') if osp.exists(vae_path): SCREAMING_SNAKE_CASE_: Tuple =load_file(vae_path, device='cpu') else: SCREAMING_SNAKE_CASE_: List[Any] =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.bin') SCREAMING_SNAKE_CASE_: str =torch.load(vae_path, map_location='cpu') if osp.exists(text_enc_path): SCREAMING_SNAKE_CASE_: Tuple =load_file(text_enc_path, device='cpu') else: SCREAMING_SNAKE_CASE_: List[Any] =osp.join(args.model_path, 'text_encoder', 'pytorch_model.bin') SCREAMING_SNAKE_CASE_: Any =torch.load(text_enc_path, map_location='cpu') # Convert the UNet model SCREAMING_SNAKE_CASE_: List[Any] =convert_unet_state_dict(unet_state_dict) SCREAMING_SNAKE_CASE_: Any ={'model.diffusion_model.' + k: v for k, v in unet_state_dict.items()} # Convert the VAE model SCREAMING_SNAKE_CASE_: List[Any] =convert_vae_state_dict(vae_state_dict) SCREAMING_SNAKE_CASE_: Dict ={'first_stage_model.' + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper SCREAMING_SNAKE_CASE_: Dict ='text_model.encoder.layers.22.layer_norm2.bias' in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm SCREAMING_SNAKE_CASE_: Any ={'transformer.' + k: v for k, v in text_enc_dict.items()} SCREAMING_SNAKE_CASE_: str =convert_text_enc_state_dict_vaa(text_enc_dict) SCREAMING_SNAKE_CASE_: int ={'cond_stage_model.model.' + k: v for k, v in text_enc_dict.items()} else: SCREAMING_SNAKE_CASE_: str =convert_text_enc_state_dict(text_enc_dict) SCREAMING_SNAKE_CASE_: Optional[int] ={'cond_stage_model.transformer.' + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint SCREAMING_SNAKE_CASE_: List[str] ={**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: SCREAMING_SNAKE_CASE_: List[str] ={k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: SCREAMING_SNAKE_CASE_: str ={'state_dict': state_dict} torch.save(state_dict, args.checkpoint_path)
78
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import tensorflow as tf from transformers import AutoTokenizer, TFAutoModelForSeqaSeqLM @require_tf @require_sentencepiece @require_tokenizers class _lowerCamelCase ( unittest.TestCase ): @slow def _lowerCAmelCase ( self : List[Any] ) -> Tuple: """simple docstring""" lowerCAmelCase__ : List[Any] = TFAutoModelForSeqaSeqLM.from_pretrained("""google/mt5-small""" ) lowerCAmelCase__ : List[str] = AutoTokenizer.from_pretrained("""google/mt5-small""" ) lowerCAmelCase__ : Union[str, Any] = tokenizer("""Hello there""" , return_tensors="""tf""" ).input_ids lowerCAmelCase__ : int = tokenizer("""Hi I am""" , return_tensors="""tf""" ).input_ids lowerCAmelCase__ : Any = model(__a , labels=__a ).loss lowerCAmelCase__ : str = -tf.math.reduce_mean(__a ).numpy() lowerCAmelCase__ : Optional[Any] = -21.22_8168 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 2E-4 )
299
'''simple docstring''' import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( snake_case_ : ndarray ) -> float: '''simple docstring''' return np.dot(snake_case_ , snake_case_ ) class __A : def __init__(self : int , *, __a : float = np.inf , __a : str = "linear" , __a : float = 0.0 , ): UpperCAmelCase_ = regularization UpperCAmelCase_ = gamma if kernel == "linear": UpperCAmelCase_ = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("rbf kernel requires gamma" ) if not isinstance(self.gamma , (float, int) ): raise ValueError("gamma must be float or int" ) if not self.gamma > 0: raise ValueError("gamma must be > 0" ) UpperCAmelCase_ = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: UpperCAmelCase_ = f"""Unknown kernel: {kernel}""" raise ValueError(__a ) def _lowercase (self : Optional[int] , __a : ndarray , __a : ndarray ): return np.dot(__a , __a ) def _lowercase (self : Optional[int] , __a : ndarray , __a : ndarray ): return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def _lowercase (self : str , __a : list[ndarray] , __a : ndarray ): UpperCAmelCase_ = observations UpperCAmelCase_ = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((UpperCAmelCase_) , ) = np.shape(__a ) def to_minimize(__a : ndarray ) -> float: UpperCAmelCase_ = 0 ((UpperCAmelCase_) , ) = np.shape(__a ) for i in range(__a ): for j in range(__a ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(__a ) UpperCAmelCase_ = LinearConstraint(__a , 0 , 0 ) UpperCAmelCase_ = Bounds(0 , self.regularization ) UpperCAmelCase_ = minimize( __a , np.ones(__a ) , bounds=__a , constraints=[ly_contraint] ).x UpperCAmelCase_ = l_star # calculating mean offset of separation plane to points UpperCAmelCase_ = 0 for i in range(__a ): for j in range(__a ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) UpperCAmelCase_ = s / n def _lowercase (self : Optional[int] , __a : ndarray ): UpperCAmelCase_ = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , __a ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
78
0
from importlib import import_module from .logging import get_logger SCREAMING_SNAKE_CASE :Any = get_logger(__name__) class __lowerCAmelCase : """simple docstring""" def __init__( self : str , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : int=None ) -> Any: """simple docstring""" snake_case_ = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith("__" ): setattr(self , __a , getattr(__a , __a ) ) snake_case_ = module._original_module if isinstance(__a , _PatchedModuleObj ) else module class __lowerCAmelCase : """simple docstring""" _SCREAMING_SNAKE_CASE = [] def __init__( self : Dict , _lowerCAmelCase : List[Any] , _lowerCAmelCase : str , _lowerCAmelCase : Dict , _lowerCAmelCase : int=None ) -> Tuple: """simple docstring""" snake_case_ = obj snake_case_ = target snake_case_ = new snake_case_ = target.split("." )[0] snake_case_ = {} snake_case_ = attrs or [] def __enter__( self : Union[str, Any] ) -> int: """simple docstring""" *snake_case_ , snake_case_ = self.target.split("." ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(__a ) ): try: snake_case_ = import_module(".".join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): snake_case_ = getattr(self.obj , __a ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(__a , _PatchedModuleObj ) and obj_attr._original_module is submodule) ): snake_case_ = obj_attr # patch at top level setattr(self.obj , __a , _PatchedModuleObj(__a , attrs=self.attrs ) ) snake_case_ = getattr(self.obj , __a ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(__a , __a , _PatchedModuleObj(getattr(__a , __a , __a ) , attrs=self.attrs ) ) snake_case_ = getattr(__a , __a ) # finally set the target attribute setattr(__a , __a , self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: snake_case_ = getattr(import_module(".".join(__a ) ) , __a ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj , __a ) is attr_value: snake_case_ = getattr(self.obj , __a ) setattr(self.obj , __a , self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" snake_case_ = globals()["__builtins__"][target_attr] setattr(self.obj , __a , self.new ) else: raise RuntimeError(F'''Tried to patch attribute {target_attr} instead of a submodule.''' ) def __exit__( self : str , *_lowerCAmelCase : Optional[int] ) -> Any: """simple docstring""" for attr in list(self.original ): setattr(self.obj , __a , self.original.pop(__a ) ) def lowerCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" self.__enter__() self._active_patches.append(self ) def lowerCAmelCase__ ( self : int ) -> Union[str, Any]: """simple docstring""" try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
283
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType, logging SCREAMING_SNAKE_CASE_: Optional[Any] =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: List[Any] ={ 'deepmind/language-perceiver': 'https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json', # See all Perceiver models at https://huggingface.co/models?filter=perceiver } class __A ( UpperCamelCase__ ): a__ : List[Any] = """perceiver""" def __init__(self : Optional[int] , __a : Tuple=256 , __a : Optional[Any]=1280 , __a : Optional[int]=768 , __a : Any=1 , __a : List[str]=26 , __a : Dict=8 , __a : List[Any]=8 , __a : Tuple=None , __a : List[str]=None , __a : Optional[int]="kv" , __a : Union[str, Any]=1 , __a : List[str]=1 , __a : List[Any]="gelu" , __a : List[str]=0.1 , __a : str=0.02 , __a : List[str]=1E-12 , __a : Optional[int]=True , __a : Tuple=262 , __a : Dict=2048 , __a : int=56 , __a : Optional[int]=[368, 496] , __a : Any=16 , __a : Optional[Any]=1920 , __a : Any=16 , __a : str=[1, 16, 224, 224] , **__a : Any , ): super().__init__(**__a ) UpperCAmelCase_ = num_latents UpperCAmelCase_ = d_latents UpperCAmelCase_ = d_model UpperCAmelCase_ = num_blocks UpperCAmelCase_ = num_self_attends_per_block UpperCAmelCase_ = num_self_attention_heads UpperCAmelCase_ = num_cross_attention_heads UpperCAmelCase_ = qk_channels UpperCAmelCase_ = v_channels UpperCAmelCase_ = cross_attention_shape_for_attention UpperCAmelCase_ = self_attention_widening_factor UpperCAmelCase_ = cross_attention_widening_factor UpperCAmelCase_ = hidden_act UpperCAmelCase_ = attention_probs_dropout_prob UpperCAmelCase_ = initializer_range UpperCAmelCase_ = layer_norm_eps UpperCAmelCase_ = use_query_residual # masked language modeling attributes UpperCAmelCase_ = vocab_size UpperCAmelCase_ = max_position_embeddings # image classification attributes UpperCAmelCase_ = image_size # flow attributes UpperCAmelCase_ = train_size # multimodal autoencoding attributes UpperCAmelCase_ = num_frames UpperCAmelCase_ = audio_samples_per_frame UpperCAmelCase_ = samples_per_patch UpperCAmelCase_ = output_shape class __A ( UpperCamelCase__ ): @property def _lowercase (self : Dict ): if self.task == "multiple-choice": UpperCAmelCase_ = {0: "batch", 1: "choice", 2: "sequence"} else: UpperCAmelCase_ = {0: "batch", 1: "sequence"} return OrderedDict( [ ("inputs", dynamic_axis), ("attention_mask", dynamic_axis), ] ) @property def _lowercase (self : Optional[Any] ): return 1E-4 def _lowercase (self : Union[str, Any] , __a : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , __a : int = -1 , __a : int = -1 , __a : int = -1 , __a : bool = False , __a : Optional[TensorType] = None , __a : int = 3 , __a : int = 40 , __a : int = 40 , ): # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified if isinstance(__a , __a ): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCAmelCase_ = compute_effective_axis_dimension( __a , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCAmelCase_ = preprocessor.num_special_tokens_to_add(__a ) UpperCAmelCase_ = compute_effective_axis_dimension( __a , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__a ) # Generate dummy inputs according to compute batch and sequence UpperCAmelCase_ = [" ".join(["a"] ) * seq_length] * batch_size UpperCAmelCase_ = dict(preprocessor(__a , return_tensors=__a ) ) UpperCAmelCase_ = inputs.pop("input_ids" ) return inputs elif isinstance(__a , __a ) and preprocessor.model_input_names[0] == "pixel_values": # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCAmelCase_ = compute_effective_axis_dimension(__a , fixed_dimension=OnnxConfig.default_fixed_batch ) UpperCAmelCase_ = self._generate_dummy_images(__a , __a , __a , __a ) UpperCAmelCase_ = dict(preprocessor(images=__a , return_tensors=__a ) ) UpperCAmelCase_ = inputs.pop("pixel_values" ) return inputs else: raise ValueError( "Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor." )
78
0
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridConfig, ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel, ) from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase__ :str = logging.get_logger(__name__) def A_ ( snake_case__ , snake_case__=False ) -> Optional[Any]: _UpperCamelCase :List[Any] = [] # fmt: off # stem: rename_keys.append(('''cls_token''', '''vit.embeddings.cls_token''') ) rename_keys.append(('''pos_embed''', '''vit.embeddings.position_embeddings''') ) rename_keys.append(('''patch_embed.proj.weight''', '''vit.embeddings.patch_embeddings.projection.weight''') ) rename_keys.append(('''patch_embed.proj.bias''', '''vit.embeddings.patch_embeddings.projection.bias''') ) # backbone rename_keys.append(('''patch_embed.backbone.stem.conv.weight''', '''vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight''') ) rename_keys.append(('''patch_embed.backbone.stem.norm.weight''', '''vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight''') ) rename_keys.append(('''patch_embed.backbone.stem.norm.bias''', '''vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias''') ) for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias") ) # transformer encoder for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"blocks.{i}.norm1.weight", f"vit.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((f"blocks.{i}.norm1.bias", f"vit.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append((f"blocks.{i}.attn.proj.weight", f"vit.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append((f"blocks.{i}.attn.proj.bias", f"vit.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((f"blocks.{i}.norm2.weight", f"vit.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((f"blocks.{i}.norm2.bias", f"vit.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append((f"blocks.{i}.mlp.fc1.weight", f"vit.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((f"blocks.{i}.mlp.fc1.bias", f"vit.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((f"blocks.{i}.mlp.fc2.weight", f"vit.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((f"blocks.{i}.mlp.fc2.bias", f"vit.encoder.layer.{i}.output.dense.bias") ) if base_model: # layernorm + pooler rename_keys.extend( [ ('''norm.weight''', '''layernorm.weight'''), ('''norm.bias''', '''layernorm.bias'''), ('''pre_logits.fc.weight''', '''pooler.dense.weight'''), ('''pre_logits.fc.bias''', '''pooler.dense.bias'''), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" _UpperCamelCase :List[str] = [(pair[0], pair[1][4:]) if pair[1].startswith('''vit''' ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ('''norm.weight''', '''vit.layernorm.weight'''), ('''norm.bias''', '''vit.layernorm.bias'''), ('''head.weight''', '''classifier.weight'''), ('''head.bias''', '''classifier.bias'''), ] ) # fmt: on return rename_keys def A_ ( snake_case__ , snake_case__ , snake_case__=False ) -> Any: for i in range(config.num_hidden_layers ): if base_model: _UpperCamelCase :List[str] = '''''' else: _UpperCamelCase :str = '''vit.''' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _UpperCamelCase :Union[str, Any] = state_dict.pop(f"blocks.{i}.attn.qkv.weight" ) _UpperCamelCase :str = state_dict.pop(f"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict _UpperCamelCase :int = in_proj_weight[ : config.hidden_size, : ] _UpperCamelCase :Dict = in_proj_bias[: config.hidden_size] _UpperCamelCase :str = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _UpperCamelCase :Union[str, Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _UpperCamelCase :Tuple = in_proj_weight[ -config.hidden_size :, : ] _UpperCamelCase :Dict = in_proj_bias[-config.hidden_size :] def A_ ( snake_case__ ) -> List[str]: _UpperCamelCase :Any = ['''head.weight''', '''head.bias'''] for k in ignore_keys: state_dict.pop(snake_case_ , snake_case_ ) def A_ ( snake_case__ , snake_case__ , snake_case__ ) -> List[Any]: _UpperCamelCase :List[Any] = dct.pop(snake_case_ ) _UpperCamelCase :int = val def A_ ( ) -> int: _UpperCamelCase :Dict = '''http://images.cocodataset.org/val2017/000000039769.jpg''' _UpperCamelCase :Optional[int] = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ) return im @torch.no_grad() def A_ ( snake_case__ , snake_case__ , snake_case__=False ) -> List[Any]: _UpperCamelCase :Dict = BitConfig( global_padding='''same''' , layer_type='''bottleneck''' , depths=(3, 4, 9) , out_features=['''stage3'''] , embedding_dynamic_padding=snake_case_ , ) _UpperCamelCase :int = ViTHybridConfig(backbone_config=snake_case_ , image_size=3_84 , num_labels=10_00 ) _UpperCamelCase :List[str] = False # load original model from timm _UpperCamelCase :Optional[Any] = timm.create_model(snake_case_ , pretrained=snake_case_ ) timm_model.eval() # load state_dict of original model, remove and rename some keys _UpperCamelCase :List[Any] = timm_model.state_dict() if base_model: remove_classification_head_(snake_case_ ) _UpperCamelCase :str = create_rename_keys(snake_case_ , snake_case_ ) for src, dest in rename_keys: rename_key(snake_case_ , snake_case_ , snake_case_ ) read_in_q_k_v(snake_case_ , snake_case_ , snake_case_ ) _UpperCamelCase :str = '''huggingface/label-files''' _UpperCamelCase :str = '''imagenet-1k-id2label.json''' _UpperCamelCase :int = json.load(open(hf_hub_download(snake_case_ , snake_case_ , repo_type='''dataset''' ) , '''r''' ) ) _UpperCamelCase :Optional[Any] = {int(snake_case_ ): v for k, v in idalabel.items()} _UpperCamelCase :Any = idalabel _UpperCamelCase :Union[str, Any] = {v: k for k, v in idalabel.items()} # load HuggingFace model if vit_name[-5:] == "in21k": _UpperCamelCase :str = ViTHybridModel(snake_case_ ).eval() else: _UpperCamelCase :Dict = ViTHybridForImageClassification(snake_case_ ).eval() model.load_state_dict(snake_case_ ) # create image processor _UpperCamelCase :Dict = create_transform(**resolve_data_config({} , model=snake_case_ ) ) _UpperCamelCase :str = transform.transforms _UpperCamelCase :List[str] = { '''bilinear''': PILImageResampling.BILINEAR, '''bicubic''': PILImageResampling.BICUBIC, '''nearest''': PILImageResampling.NEAREST, } _UpperCamelCase :int = ViTHybridImageProcessor( do_resize=snake_case_ , size={'''shortest_edge''': timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=snake_case_ , crop_size={'''height''': timm_transforms[1].size[0], '''width''': timm_transforms[1].size[1]} , do_normalize=snake_case_ , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) _UpperCamelCase :Tuple = prepare_img() _UpperCamelCase :int = transform(snake_case_ ).unsqueeze(0 ) _UpperCamelCase :str = processor(snake_case_ , return_tensors='''pt''' ).pixel_values # verify pixel values assert torch.allclose(snake_case_ , snake_case_ ) # verify logits with torch.no_grad(): _UpperCamelCase :List[str] = model(snake_case_ ) _UpperCamelCase :List[Any] = outputs.logits print('''Predicted class:''' , logits.argmax(-1 ).item() ) if base_model: _UpperCamelCase :Dict = timm_model.forward_features(snake_case_ ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(snake_case_ , outputs.pooler_output , atol=1E-3 ) else: _UpperCamelCase :Optional[int] = timm_model(snake_case_ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(snake_case_ , outputs.logits , atol=1E-3 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) print(f"Saving model {vit_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(snake_case_ ) print(f"Saving processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(snake_case_ ) if push_to_hub: print(f"Pushing model and processor to the hub {vit_name}" ) model.push_to_hub(f"ybelkada/{vit_name}" ) processor.push_to_hub(f"ybelkada/{vit_name}" ) if __name__ == "__main__": UpperCamelCase__ :int = argparse.ArgumentParser() # Required parameters parser.add_argument( """--vit_name""", default="""vit_base_r50_s16_384""", type=str, help="""Name of the hybrid ViT timm model you\'d like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether to upload the model to the HuggingFace hub.""" ) UpperCamelCase__ :Optional[int] = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
355
'''simple docstring''' import requests def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : str ) -> None: '''simple docstring''' UpperCAmelCase_ = {"Content-Type": "application/json"} UpperCAmelCase_ = requests.post(snake_case_ , json={"text": message_body} , headers=snake_case_ ) if response.status_code != 2_00: UpperCAmelCase_ = ( "Request to slack returned an error " f"""{response.status_code}, the response is:\n{response.text}""" ) raise ValueError(snake_case_ ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message('<YOUR MESSAGE BODY>', '<SLACK CHANNEL URL>')
78
0
'''simple docstring''' from .constants import ( MODEL_NAME, OPTIMIZER_NAME, RNG_STATE_NAME, SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, SCALER_NAME, SCHEDULER_NAME, TORCH_LAUNCH_PARAMS, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ) from .dataclasses import ( BnbQuantizationConfig, ComputeEnvironment, CustomDtype, DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, DynamoBackend, FPaRecipeKwargs, FullyShardedDataParallelPlugin, GradientAccumulationPlugin, GradScalerKwargs, InitProcessGroupKwargs, KwargsHandler, LoggerType, MegatronLMPlugin, PrecisionType, ProjectConfiguration, RNGType, SageMakerDistributedType, TensorInformation, TorchDynamoPlugin, ) from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env from .imports import ( get_ccl_version, is_abit_bnb_available, is_abit_bnb_available, is_aim_available, is_bfaa_available, is_bnb_available, is_botoa_available, is_ccl_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_fpa_available, is_ipex_available, is_megatron_lm_available, is_mlflow_available, is_mps_available, is_npu_available, is_rich_available, is_safetensors_available, is_sagemaker_available, is_tensorboard_available, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) from .modeling import ( check_device_map, check_tied_parameters_in_config, check_tied_parameters_on_same_device, compute_module_sizes, convert_file_size_to_int, dtype_byte_size, find_tied_parameters, get_balanced_memory, get_max_layer_size, get_max_memory, get_mixed_precision_context_manager, id_tensor_storage, infer_auto_device_map, load_checkpoint_in_model, load_offloaded_weights, load_state_dict, named_module_tensors, retie_parameters, set_module_tensor_to_device, shard_checkpoint, ) from .offload import ( OffloadedWeightsLoader, PrefixedDataset, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, save_offload_index, ) from .operations import ( broadcast, broadcast_object_list, concatenate, convert_outputs_to_fpaa, convert_to_fpaa, find_batch_size, find_device, gather, gather_object, get_data_structure, honor_type, initialize_tensors, is_namedtuple, is_tensor_information, is_torch_tensor, listify, pad_across_processes, recursively_apply, reduce, send_to_device, slice_tensors, ) from .versions import compare_versions, is_torch_version if is_deepspeed_available(): from .deepspeed import ( DeepSpeedEngineWrapper, DeepSpeedOptimizerWrapper, DeepSpeedSchedulerWrapper, DummyOptim, DummyScheduler, HfDeepSpeedConfig, ) from .bnb import has_abit_bnb_layers, load_and_quantize_model from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer from .launch import ( PrepareForLaunch, _filter_args, prepare_deepspeed_cmd_env, prepare_multi_gpu_env, prepare_sagemager_args_inputs, prepare_simple_launcher_cmd_env, prepare_tpu, ) from .megatron_lm import ( AbstractTrainStep, BertTrainStep, GPTTrainStep, MegatronEngine, MegatronLMDummyDataLoader, MegatronLMDummyScheduler, MegatronLMOptimizerWrapper, MegatronLMSchedulerWrapper, TaTrainStep, avg_losses_across_data_parallel_group, gather_across_data_parallel_groups, ) from .megatron_lm import initialize as megatron_lm_initialize from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader from .megatron_lm import prepare_model as megatron_lm_prepare_model from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler from .memory import find_executable_batch_size, release_memory from .other import ( extract_model_from_parallel, get_pretty_name, is_port_in_use, merge_dicts, patch_environment, save, wait_for_everyone, write_basic_config, ) from .random import set_seed, synchronize_rng_state, synchronize_rng_states from .torch_xla import install_xla from .tqdm import tqdm from .transformer_engine import convert_model, has_transformer_engine_layers
135
'''simple docstring''' from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging SCREAMING_SNAKE_CASE_: Optional[int] =logging.get_logger(__name__) # pylint: disable=invalid-name class __A ( UpperCamelCase__ ): def __init__(self : Any , __a : CLIPSegForImageSegmentation , __a : CLIPSegProcessor , __a : AutoencoderKL , __a : CLIPTextModel , __a : CLIPTokenizer , __a : UNetaDConditionModel , __a : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __a : StableDiffusionSafetyChecker , __a : CLIPImageProcessor , ): super().__init__() if hasattr(scheduler.config , "steps_offset" ) and scheduler.config.steps_offset != 1: UpperCAmelCase_ = ( f"""The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`""" f""" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure """ "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1" , "1.0.0" , __a , standard_warn=__a ) UpperCAmelCase_ = dict(scheduler.config ) UpperCAmelCase_ = 1 UpperCAmelCase_ = FrozenDict(__a ) if hasattr(scheduler.config , "skip_prk_steps" ) and scheduler.config.skip_prk_steps is False: UpperCAmelCase_ = ( f"""The configuration file of this scheduler: {scheduler} has not set the configuration""" " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" " Hub, it would be very nice if you could open a Pull request for the" " `scheduler/scheduler_config.json` file" ) deprecate("skip_prk_steps not set" , "1.0.0" , __a , standard_warn=__a ) UpperCAmelCase_ = dict(scheduler.config ) UpperCAmelCase_ = True UpperCAmelCase_ = FrozenDict(__a ) if safety_checker is None: logger.warning( f"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure""" " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." ) self.register_modules( segmentation_model=__a , segmentation_processor=__a , vae=__a , text_encoder=__a , tokenizer=__a , unet=__a , scheduler=__a , safety_checker=__a , feature_extractor=__a , ) def _lowercase (self : str , __a : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCAmelCase_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__a ) def _lowercase (self : int ): self.enable_attention_slicing(__a ) def _lowercase (self : Optional[Any] ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) UpperCAmelCase_ = torch.device("cuda" ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(__a , __a ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _lowercase (self : Optional[int] ): if self.device != torch.device("meta" ) or not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(__a , "_hf_hook" ) and hasattr(module._hf_hook , "execution_device" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__(self : Dict , __a : Union[str, List[str]] , __a : Union[torch.FloatTensor, PIL.Image.Image] , __a : str , __a : int = 512 , __a : int = 512 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : int , ): UpperCAmelCase_ = self.segmentation_processor( text=[text] , images=[image] , padding="max_length" , return_tensors="pt" ).to(self.device ) UpperCAmelCase_ = self.segmentation_model(**__a ) UpperCAmelCase_ = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() UpperCAmelCase_ = self.numpy_to_pil(__a )[0].resize(image.size ) # Run inpainting pipeline with the generated mask UpperCAmelCase_ = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=__a , image=__a , mask_image=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , )
78
0
from typing import List, Optional, Union import torch from transformers import ( XLMRobertaTokenizer, ) from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) from .text_encoder import MultilingualCLIP _lowercase : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name _lowercase : List[Any] = '\n Examples:\n ```py\n >>> from diffusers import KandinskyPipeline, KandinskyPriorPipeline\n >>> import torch\n\n >>> pipe_prior = KandinskyPriorPipeline.from_pretrained("kandinsky-community/Kandinsky-2-1-prior")\n >>> pipe_prior.to("cuda")\n\n >>> prompt = "red cat, 4k photo"\n >>> out = pipe_prior(prompt)\n >>> image_emb = out.image_embeds\n >>> negative_image_emb = out.negative_image_embeds\n\n >>> pipe = KandinskyPipeline.from_pretrained("kandinsky-community/kandinsky-2-1")\n >>> pipe.to("cuda")\n\n >>> image = pipe(\n ... prompt,\n ... image_embeds=image_emb,\n ... negative_image_embeds=negative_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=100,\n ... ).images\n\n >>> image[0].save("cat.png")\n ```\n' def _lowerCAmelCase ( UpperCamelCase__: Tuple , UpperCamelCase__: List[str] , UpperCamelCase__: List[str]=8 ) -> Optional[Any]: """simple docstring""" A = h // scale_factor**2 if h % scale_factor**2 != 0: new_h += 1 A = w // scale_factor**2 if w % scale_factor**2 != 0: new_w += 1 return new_h * scale_factor, new_w * scale_factor class _UpperCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self , a__ , a__ , a__ , a__ , a__ , ) -> int: super().__init__() self.register_modules( text_encoder=__a , tokenizer=__a , unet=__a , scheduler=__a , movq=__a , ) A = 2 ** (len(self.movq.config.block_out_channels ) - 1) def _UpperCAmelCase ( self , a__ , a__ , a__ , a__ , a__ , a__ ) -> List[Any]: if latents is None: A = randn_tensor(__a , generator=__a , device=__a , dtype=__a ) else: if latents.shape != shape: raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}' ) A = latents.to(__a ) A = latents * scheduler.init_noise_sigma return latents def _UpperCAmelCase ( self , a__ , a__ , a__ , a__ , a__=None , ) -> List[Any]: A = len(__a ) if isinstance(__a , __a ) else 1 # get prompt text embeddings A = self.tokenizer( __a , padding="""max_length""" , truncation=__a , max_length=77 , return_attention_mask=__a , add_special_tokens=__a , return_tensors="""pt""" , ) A = text_inputs.input_ids A = self.tokenizer(__a , padding="""longest""" , return_tensors="""pt""" ).input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(__a , __a ): A = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" f' {self.tokenizer.model_max_length} tokens: {removed_text}' ) A = text_input_ids.to(__a ) A = text_inputs.attention_mask.to(__a ) A , A = self.text_encoder( input_ids=__a , attention_mask=__a ) A = prompt_embeds.repeat_interleave(__a , dim=0 ) A = text_encoder_hidden_states.repeat_interleave(__a , dim=0 ) A = text_mask.repeat_interleave(__a , dim=0 ) if do_classifier_free_guidance: A = 42 if negative_prompt is None: A = [""""""] * batch_size elif type(__a ) is not type(__a ): raise TypeError( f'`negative_prompt` should be the same type to `prompt`, but got {type(__a )} !=' f' {type(__a )}.' ) elif isinstance(__a , __a ): A = [negative_prompt] elif batch_size != len(__a ): raise ValueError( f'`negative_prompt`: {negative_prompt} has batch size {len(__a )}, but `prompt`:' f' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches' """ the batch size of `prompt`.""" ) else: A = negative_prompt A = self.tokenizer( __a , padding="""max_length""" , max_length=77 , truncation=__a , return_attention_mask=__a , add_special_tokens=__a , return_tensors="""pt""" , ) A = uncond_input.input_ids.to(__a ) A = uncond_input.attention_mask.to(__a ) A , A = self.text_encoder( input_ids=__a , attention_mask=__a ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method A = negative_prompt_embeds.shape[1] A = negative_prompt_embeds.repeat(1 , __a ) A = negative_prompt_embeds.view(batch_size * num_images_per_prompt , __a ) A = uncond_text_encoder_hidden_states.shape[1] A = uncond_text_encoder_hidden_states.repeat(1 , __a , 1 ) A = uncond_text_encoder_hidden_states.view( batch_size * num_images_per_prompt , __a , -1 ) A = uncond_text_mask.repeat_interleave(__a , dim=0 ) # done duplicates # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes A = torch.cat([negative_prompt_embeds, prompt_embeds] ) A = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states] ) A = torch.cat([uncond_text_mask, text_mask] ) return prompt_embeds, text_encoder_hidden_states, text_mask def _UpperCAmelCase ( self , a__=0 ) -> Any: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) A = torch.device(f'cuda:{gpu_id}' ) A = [ self.unet, self.text_encoder, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(__a , __a ) def _UpperCAmelCase ( self , a__=0 ) -> List[str]: if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) A = torch.device(f'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=__a ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) A = None for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]: A , A = cpu_offload_with_hook(__a , __a , prev_module_hook=__a ) if self.safety_checker is not None: A , A = cpu_offload_with_hook(self.safety_checker , __a , prev_module_hook=__a ) # We'll offload the last model manually. A = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _UpperCAmelCase ( self ) -> str: if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(__a , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(__a ) def __call__( self , a__ , a__ , a__ , a__ = None , a__ = 512 , a__ = 512 , a__ = 100 , a__ = 4.0 , a__ = 1 , a__ = None , a__ = None , a__ = "pil" , a__ = True , ) -> Dict: if isinstance(__a , __a ): A = 1 elif isinstance(__a , __a ): A = len(__a ) else: raise ValueError(f'`prompt` has to be of type `str` or `list` but is {type(__a )}' ) A = self._execution_device A = batch_size * num_images_per_prompt A = guidance_scale > 1.0 A , A , A = self._encode_prompt( __a , __a , __a , __a , __a ) if isinstance(__a , __a ): A = torch.cat(__a , dim=0 ) if isinstance(__a , __a ): A = torch.cat(__a , dim=0 ) if do_classifier_free_guidance: A = image_embeds.repeat_interleave(__a , dim=0 ) A = negative_image_embeds.repeat_interleave(__a , dim=0 ) A = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to( dtype=prompt_embeds.dtype , device=__a ) self.scheduler.set_timesteps(__a , device=__a ) A = self.scheduler.timesteps A = self.unet.config.in_channels A , A = get_new_h_w(__a , __a , self.movq_scale_factor ) # create initial latent A = self.prepare_latents( (batch_size, num_channels_latents, height, width) , text_encoder_hidden_states.dtype , __a , __a , __a , self.scheduler , ) for i, t in enumerate(self.progress_bar(__a ) ): # expand the latents if we are doing classifier free guidance A = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents A = {"""text_embeds""": prompt_embeds, """image_embeds""": image_embeds} A = self.unet( sample=__a , timestep=__a , encoder_hidden_states=__a , added_cond_kwargs=__a , return_dict=__a , )[0] if do_classifier_free_guidance: A , A = noise_pred.split(latents.shape[1] , dim=1 ) A , A = noise_pred.chunk(2 ) A , A = variance_pred.chunk(2 ) A = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) A = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , """variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): A , A = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 A = self.scheduler.step( __a , __a , __a , generator=__a , ).prev_sample # post-processing A = self.movq.decode(__a , force_not_quantize=__a )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(f'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: A = image * 0.5 + 0.5 A = image.clamp(0 , 1 ) A = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": A = self.numpy_to_pil(__a ) if not return_dict: return (image,) return ImagePipelineOutput(images=__a )
641
'''simple docstring''' def lowerCAmelCase_ ( snake_case_ : int ) -> bool: '''simple docstring''' if number < 0: raise ValueError("number must not be negative" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
78
0
"""simple docstring""" import unittest import torch from torch import nn from diffusers.models.activations import get_activation class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __UpperCAmelCase ( self : Optional[Any] ): lowerCamelCase__ = get_activation("""swish""" ) self.assertIsInstance(__a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self : str ): lowerCamelCase__ = get_activation("""silu""" ) self.assertIsInstance(__a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self : str ): lowerCamelCase__ = get_activation("""mish""" ) self.assertIsInstance(__a , nn.Mish ) self.assertEqual(act(torch.tensor(-200 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self : Optional[int] ): lowerCamelCase__ = get_activation("""gelu""" ) self.assertIsInstance(__a , nn.GELU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
129
'''simple docstring''' from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class __A : a__ : int a__ : TreeNode | None = None a__ : TreeNode | None = None SCREAMING_SNAKE_CASE_: Union[str, Any] =namedtuple('CoinsDistribResult', 'moves excess') def lowerCAmelCase_ ( snake_case_ : TreeNode | None ) -> int: '''simple docstring''' if root is None: return 0 # Validation def count_nodes(snake_case_ : TreeNode | None ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(snake_case_ : TreeNode | None ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(snake_case_ ) != count_coins(snake_case_ ): raise ValueError("The nodes number should be same as the number of coins" ) # Main calculation def get_distrib(snake_case_ : TreeNode | None ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) UpperCAmelCase_ , UpperCAmelCase_ = get_distrib(node.left ) UpperCAmelCase_ , UpperCAmelCase_ = get_distrib(node.right ) UpperCAmelCase_ = 1 - left_distrib_excess UpperCAmelCase_ = 1 - right_distrib_excess UpperCAmelCase_ = ( left_distrib_moves + right_distrib_moves + abs(snake_case_ ) + abs(snake_case_ ) ) UpperCAmelCase_ = node.data - coins_to_left - coins_to_right return CoinsDistribResult(snake_case_ , snake_case_ ) return get_distrib(snake_case_ )[0] if __name__ == "__main__": import doctest doctest.testmod()
78
0
"""simple docstring""" from __future__ import annotations def a__ ( __SCREAMING_SNAKE_CASE ) -> bool: __lowerCAmelCase: int = str(snake_case_ ) return n == n[::-1] def a__ ( __SCREAMING_SNAKE_CASE = 1_0_0_0_0_0_0 ) -> Optional[Any]: __lowerCAmelCase: Tuple = 0 for i in range(1 , snake_case_ ): if is_palindrome(snake_case_ ) and is_palindrome(bin(snake_case_ ).split("b" )[1] ): total += i return total if __name__ == "__main__": print(solution(int(str(input().strip()))))
346
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) SCREAMING_SNAKE_CASE_: int =logging.getLogger() def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = argparse.ArgumentParser() parser.add_argument("-f" ) UpperCAmelCase_ = parser.parse_args() return args.f def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> str: '''simple docstring''' UpperCAmelCase_ = {} UpperCAmelCase_ = os.path.join(snake_case_ , "all_results.json" ) if os.path.exists(snake_case_ ): with open(snake_case_ , "r" ) as f: UpperCAmelCase_ = json.load(snake_case_ ) else: raise ValueError(f"""can't find {path}""" ) return results def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = torch.cuda.is_available() and torch_device == "cuda" return is_using_cuda and is_apex_available() SCREAMING_SNAKE_CASE_: Any =logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class __A ( UpperCamelCase__ ): @classmethod def _lowercase (cls : Any ): # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU UpperCAmelCase_ = tempfile.mkdtemp() UpperCAmelCase_ = os.path.join(cls.tmpdir , "default_config.yml" ) write_basic_config(save_location=cls.configPath ) UpperCAmelCase_ = ["accelerate", "launch", "--config_file", cls.configPath] @classmethod def _lowercase (cls : int ): shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking """.split() if is_cuda_and_apex_available(): testargs.append("--fp16" ) run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "glue_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking """.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertLess(result["perplexity"] , 100 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "clm_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertLess(result["perplexity"] , 42 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "mlm_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Optional[Any] ): # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu UpperCAmelCase_ = 7 if get_gpu_count() > 1 else 2 UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) self.assertLess(result["train_loss"] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "ner_no_trainer" ) ) ) @unittest.skip(reason="Fix me @muellerzr" ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : int ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result["eval_f1"] , 28 ) self.assertGreaterEqual(result["eval_exact"] , 28 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "qa_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : str ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_accuracy"] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__a , "swag_no_trainer" ) ) ) @slow @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Optional[int] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_rouge1"] , 10 ) self.assertGreaterEqual(result["eval_rouge2"] , 2 ) self.assertGreaterEqual(result["eval_rougeL"] , 7 ) self.assertGreaterEqual(result["eval_rougeLsum"] , 7 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "summarization_no_trainer" ) ) ) @slow @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : List[str] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_bleu"] , 30 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "translation_no_trainer" ) ) ) @slow def _lowercase (self : Dict ): UpperCAmelCase_ = logging.StreamHandler(sys.stdout ) logger.addHandler(__a ) UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_overall_accuracy"] , 0.10 ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Any ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 """.split() if is_cuda_and_apex_available(): testargs.append("--fp16" ) run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) # The base model scores a 25% self.assertGreaterEqual(result["eval_accuracy"] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__a , "step_1" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "image_classification_no_trainer" ) ) )
78
0
import sys from collections import defaultdict class A__ : '''simple docstring''' def __init__( self : str ): """simple docstring""" UpperCamelCase = [] def _SCREAMING_SNAKE_CASE ( self : Tuple , _SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" return self.node_position[vertex] def _SCREAMING_SNAKE_CASE ( self : Any , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" UpperCamelCase = pos def _SCREAMING_SNAKE_CASE ( self : Dict , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" if start > size // 2 - 1: return else: if 2 * start + 2 >= size: UpperCamelCase = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: UpperCamelCase = 2 * start + 1 else: UpperCamelCase = 2 * start + 2 if heap[smallest_child] < heap[start]: UpperCamelCase , UpperCamelCase = heap[smallest_child], positions[smallest_child] UpperCamelCase , UpperCamelCase = ( heap[start], positions[start], ) UpperCamelCase , UpperCamelCase = temp, tempa UpperCamelCase = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , __a ) self.top_to_bottom(__a , __a , __a , __a ) def _SCREAMING_SNAKE_CASE ( self : int , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : int ): """simple docstring""" UpperCamelCase = position[index] while index != 0: UpperCamelCase = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: UpperCamelCase = heap[parent] UpperCamelCase = position[parent] self.set_position(position[parent] , __a ) else: UpperCamelCase = val UpperCamelCase = temp self.set_position(__a , __a ) break UpperCamelCase = parent else: UpperCamelCase = val UpperCamelCase = temp self.set_position(__a , 0 ) def _SCREAMING_SNAKE_CASE ( self : Any , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Any ): """simple docstring""" UpperCamelCase = len(__a ) // 2 - 1 for i in range(__a , -1 , -1 ): self.top_to_bottom(__a , __a , len(__a ) , __a ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" UpperCamelCase = positions[0] UpperCamelCase = sys.maxsize self.top_to_bottom(__a , 0 , len(__a ) , __a ) return temp def lowercase__ ( _UpperCamelCase) -> List[Any]: """simple docstring""" UpperCamelCase = Heap() UpperCamelCase = [0] * len(snake_case_) UpperCamelCase = [-1] * len(snake_case_) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph UpperCamelCase = [] # Heap of Distance of vertices from their neighboring vertex UpperCamelCase = [] for vertex in range(len(snake_case_)): distance_tv.append(sys.maxsize) positions.append(snake_case_) heap.node_position.append(snake_case_) UpperCamelCase = [] UpperCamelCase = 1 UpperCamelCase = sys.maxsize for neighbor, distance in adjacency_list[0]: UpperCamelCase = 0 UpperCamelCase = distance heap.heapify(snake_case_ , snake_case_) for _ in range(1 , len(snake_case_)): UpperCamelCase = heap.delete_minimum(snake_case_ , snake_case_) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex)) UpperCamelCase = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(snake_case_)] ): UpperCamelCase = distance heap.bottom_to_top( snake_case_ , heap.get_position(snake_case_) , snake_case_ , snake_case_) UpperCamelCase = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > __magic_name__ : List[str] = int(input('''Enter number of edges: ''').strip()) __magic_name__ : Tuple = defaultdict(list) for _ in range(edges_number): __magic_name__ : str = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
280
'''simple docstring''' import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP SCREAMING_SNAKE_CASE_: Any =False try: SCREAMING_SNAKE_CASE_: Optional[Any] =_is_package_available('google.colab') except ModuleNotFoundError: pass @input.register class __A : def __init__(self : int , __a : str = None , __a : list = [] ): UpperCAmelCase_ = 0 UpperCAmelCase_ = choices UpperCAmelCase_ = prompt if sys.platform == "win32": UpperCAmelCase_ = "*" else: UpperCAmelCase_ = "➔ " def _lowercase (self : Union[str, Any] , __a : Optional[int] , __a : str = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 32 , __a ) else: forceWrite(self.choices[index] , __a ) def _lowercase (self : Any , __a : int ): if index == self.position: forceWrite(f""" {self.arrow_char} """ ) self.write_choice(__a ) else: forceWrite(f""" {self.choices[index]}""" ) reset_cursor() def _lowercase (self : Optional[Any] , __a : Direction , __a : int = 1 ): UpperCAmelCase_ = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(__a ) move_cursor(__a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP["up"] ) def _lowercase (self : Dict ): self.move_direction(Direction.UP ) @input.mark(KEYMAP["down"] ) def _lowercase (self : Any ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP["newline"] ) def _lowercase (self : Optional[Any] ): move_cursor(len(self.choices ) - self.position , "DOWN" ) return self.position @input.mark(KEYMAP["interrupt"] ) def _lowercase (self : str ): move_cursor(len(self.choices ) - self.position , "DOWN" ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(__a )] for number in range(10 )] ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = int(chr(self.current_selection ) ) UpperCAmelCase_ = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , __a ) else: return else: return def _lowercase (self : Optional[Any] , __a : int = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , "\n" ) if in_colab: forceWrite("Please input a choice index (starting from 0), and press enter" , "\n" ) else: forceWrite("Please select a choice using the arrow or number keys, and selecting with enter" , "\n" ) UpperCAmelCase_ = default_choice for i in range(len(self.choices ) ): self.print_choice(__a ) forceWrite("\n" ) move_cursor(len(self.choices ) - self.position , "UP" ) with cursor.hide(): while True: if in_colab: try: UpperCAmelCase_ = int(builtins.input() ) except ValueError: UpperCAmelCase_ = default_choice else: UpperCAmelCase_ = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , "UP" ) clear_line() self.write_choice(__a , "\n" ) return choice
78
0
import math def _UpperCAmelCase ( UpperCAmelCase : int ): """simple docstring""" assert isinstance(snake_case_ , snake_case_ ) 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 not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False __lowerCamelCase : Tuple = range(3 , int(math.sqrt(snake_case_ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def _UpperCAmelCase ( UpperCAmelCase : List[Any] , UpperCAmelCase : Optional[int]=1 , **UpperCAmelCase : Union[str, Any] ): """simple docstring""" __lowerCamelCase : int = factor * value __lowerCamelCase : int = value while not is_prime(snake_case_ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **snake_case_ ) return value
519
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE_: Optional[int] ={'configuration_beit': ['BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BeitConfig', 'BeitOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[int] =['BeitFeatureExtractor'] SCREAMING_SNAKE_CASE_: int =['BeitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[int] =[ 'BEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BeitForImageClassification', 'BeitForMaskedImageModeling', 'BeitForSemanticSegmentation', 'BeitModel', 'BeitPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: int =[ 'FlaxBeitForImageClassification', 'FlaxBeitForMaskedImageModeling', 'FlaxBeitModel', 'FlaxBeitPreTrainedModel', ] if TYPE_CHECKING: from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_beit import BeitFeatureExtractor from .image_processing_beit import BeitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_beit import ( BEIT_PRETRAINED_MODEL_ARCHIVE_LIST, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, BeitPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_beit import ( FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel, FlaxBeitPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_: Dict =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
78
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import XLMRobertaTokenizer from diffusers import ( AltDiffusionImgaImgPipeline, AutoencoderKL, PNDMScheduler, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) 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 enable_full_determinism() class lowerCamelCase_( unittest.TestCase ): '''simple docstring''' def snake_case__ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def snake_case__ ( self ): _lowerCamelCase = 1 _lowerCamelCase = 3 _lowerCamelCase = (3_2, 3_2) _lowerCamelCase = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(__a ) return image @property def snake_case__ ( self ): torch.manual_seed(0 ) _lowerCamelCase = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=3_2 , ) return model @property def snake_case__ ( self ): torch.manual_seed(0 ) _lowerCamelCase = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) return model @property def snake_case__ ( self ): torch.manual_seed(0 ) _lowerCamelCase = RobertaSeriesConfig( hidden_size=3_2 , project_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5_0_0_6 , ) return RobertaSeriesModelWithTransformation(__a ) @property def snake_case__ ( self ): def extract(*lowerCamelCase__ , **lowerCamelCase__ ): class lowerCamelCase_: '''simple docstring''' def __init__( self ): _lowerCamelCase = torch.ones([0] ) def snake_case__ ( self , lowerCamelCase__ ): self.pixel_values.to(__a ) return self return Out() return extract def snake_case__ ( self ): _lowerCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator _lowerCamelCase = self.dummy_cond_unet _lowerCamelCase = PNDMScheduler(skip_prk_steps=__a ) _lowerCamelCase = self.dummy_vae _lowerCamelCase = self.dummy_text_encoder _lowerCamelCase = XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''' ) _lowerCamelCase = 7_7 _lowerCamelCase = self.dummy_image.to(__a ) _lowerCamelCase = init_image / 2 + 0.5 # make sure here that pndm scheduler skips prk _lowerCamelCase = AltDiffusionImgaImgPipeline( unet=__a , scheduler=__a , vae=__a , text_encoder=__a , tokenizer=__a , safety_checker=__a , feature_extractor=self.dummy_extractor , ) _lowerCamelCase = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=__a ) _lowerCamelCase = alt_pipe.to(__a ) alt_pipe.set_progress_bar_config(disable=__a ) _lowerCamelCase = '''A painting of a squirrel eating a burger''' _lowerCamelCase = torch.Generator(device=__a ).manual_seed(0 ) _lowerCamelCase = alt_pipe( [prompt] , generator=__a , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' , image=__a , ) _lowerCamelCase = output.images _lowerCamelCase = torch.Generator(device=__a ).manual_seed(0 ) _lowerCamelCase = alt_pipe( [prompt] , generator=__a , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' , image=__a , return_dict=__a , )[0] _lowerCamelCase = image[0, -3:, -3:, -1] _lowerCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) _lowerCamelCase = np.array([0.4_4_2_7, 0.3_7_3_1, 0.4_2_4_9, 0.4_9_4_1, 0.4_5_4_6, 0.4_1_4_8, 0.4_1_9_3, 0.4_6_6_6, 0.4_4_9_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 5e-3 @unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''' ) def snake_case__ ( self ): _lowerCamelCase = self.dummy_cond_unet _lowerCamelCase = PNDMScheduler(skip_prk_steps=__a ) _lowerCamelCase = self.dummy_vae _lowerCamelCase = self.dummy_text_encoder _lowerCamelCase = XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''' ) _lowerCamelCase = 7_7 _lowerCamelCase = self.dummy_image.to(__a ) # put models in fp16 _lowerCamelCase = unet.half() _lowerCamelCase = vae.half() _lowerCamelCase = bert.half() # make sure here that pndm scheduler skips prk _lowerCamelCase = AltDiffusionImgaImgPipeline( unet=__a , scheduler=__a , vae=__a , text_encoder=__a , tokenizer=__a , safety_checker=__a , feature_extractor=self.dummy_extractor , ) _lowerCamelCase = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=__a ) _lowerCamelCase = alt_pipe.to(__a ) alt_pipe.set_progress_bar_config(disable=__a ) _lowerCamelCase = '''A painting of a squirrel eating a burger''' _lowerCamelCase = torch.manual_seed(0 ) _lowerCamelCase = alt_pipe( [prompt] , generator=__a , num_inference_steps=2 , output_type='''np''' , image=__a , ).images assert image.shape == (1, 3_2, 3_2, 3) @unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''' ) def snake_case__ ( self ): _lowerCamelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''' ) # resize to resolution that is divisible by 8 but not 16 or 32 _lowerCamelCase = init_image.resize((7_6_0, 5_0_4) ) _lowerCamelCase = '''BAAI/AltDiffusion''' _lowerCamelCase = AltDiffusionImgaImgPipeline.from_pretrained( __a , safety_checker=__a , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() _lowerCamelCase = '''A fantasy landscape, trending on artstation''' _lowerCamelCase = torch.manual_seed(0 ) _lowerCamelCase = pipe( prompt=__a , image=__a , strength=0.7_5 , guidance_scale=7.5 , generator=__a , output_type='''np''' , ) _lowerCamelCase = output.images[0] _lowerCamelCase = image[2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert image.shape == (5_0_4, 7_6_0, 3) _lowerCamelCase = np.array([0.9_3_5_8, 0.9_3_9_7, 0.9_5_9_9, 0.9_9_0_1, 1.0_0_0_0, 1.0_0_0_0, 0.9_8_8_2, 1.0_0_0_0, 1.0_0_0_0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class lowerCamelCase_( unittest.TestCase ): '''simple docstring''' def snake_case__ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case__ ( self ): _lowerCamelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''' ) _lowerCamelCase = init_image.resize((7_6_8, 5_1_2) ) _lowerCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy''' ) _lowerCamelCase = '''BAAI/AltDiffusion''' _lowerCamelCase = AltDiffusionImgaImgPipeline.from_pretrained( __a , safety_checker=__a , ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() _lowerCamelCase = '''A fantasy landscape, trending on artstation''' _lowerCamelCase = torch.manual_seed(0 ) _lowerCamelCase = pipe( prompt=__a , image=__a , strength=0.7_5 , guidance_scale=7.5 , generator=__a , output_type='''np''' , ) _lowerCamelCase = output.images[0] assert image.shape == (5_1_2, 7_6_8, 3) # img2img is flaky across GPUs even in fp32, so using MAE here assert np.abs(expected_image - image ).max() < 1e-2
661
'''simple docstring''' import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed SCREAMING_SNAKE_CASE_: Any ={ 'distilbert': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), 'roberta': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), 'bert': (BertConfig, BertForMaskedLM, BertTokenizer), 'gpt2': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def lowerCAmelCase_ ( snake_case_ : Any ) -> str: '''simple docstring''' assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def lowerCAmelCase_ ( snake_case_ : Optional[Any] , snake_case_ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' if args.student_type == "roberta": UpperCAmelCase_ = False elif args.student_type == "gpt2": UpperCAmelCase_ = False def lowerCAmelCase_ ( snake_case_ : Optional[int] , snake_case_ : List[Any] ) -> Tuple: '''simple docstring''' if args.student_type == "roberta": UpperCAmelCase_ = False def lowerCAmelCase_ ( ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = argparse.ArgumentParser(description="Training" ) parser.add_argument("--force" , action="store_true" , help="Overwrite dump_path if it already exists." ) parser.add_argument( "--dump_path" , type=snake_case_ , required=snake_case_ , help="The output directory (log, checkpoints, parameters, etc.)" ) parser.add_argument( "--data_file" , type=snake_case_ , required=snake_case_ , help="The binarized file (tokenized + tokens_to_ids) and grouped by sequence." , ) parser.add_argument( "--student_type" , type=snake_case_ , choices=["distilbert", "roberta", "gpt2"] , required=snake_case_ , help="The student type (DistilBERT, RoBERTa)." , ) parser.add_argument("--student_config" , type=snake_case_ , required=snake_case_ , help="Path to the student configuration." ) parser.add_argument( "--student_pretrained_weights" , default=snake_case_ , type=snake_case_ , help="Load student initialization checkpoint." ) parser.add_argument( "--teacher_type" , choices=["bert", "roberta", "gpt2"] , required=snake_case_ , help="Teacher type (BERT, RoBERTa)." ) parser.add_argument("--teacher_name" , type=snake_case_ , required=snake_case_ , help="The teacher model." ) parser.add_argument("--temperature" , default=2.0 , type=snake_case_ , help="Temperature for the softmax temperature." ) parser.add_argument( "--alpha_ce" , default=0.5 , type=snake_case_ , help="Linear weight for the distillation loss. Must be >=0." ) parser.add_argument( "--alpha_mlm" , default=0.0 , type=snake_case_ , help="Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag." , ) parser.add_argument("--alpha_clm" , default=0.5 , type=snake_case_ , help="Linear weight for the CLM loss. Must be >=0." ) parser.add_argument("--alpha_mse" , default=0.0 , type=snake_case_ , help="Linear weight of the MSE loss. Must be >=0." ) parser.add_argument( "--alpha_cos" , default=0.0 , type=snake_case_ , help="Linear weight of the cosine embedding loss. Must be >=0." ) parser.add_argument( "--mlm" , action="store_true" , help="The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM." ) parser.add_argument( "--mlm_mask_prop" , default=0.15 , type=snake_case_ , help="Proportion of tokens for which we need to make a prediction." , ) parser.add_argument("--word_mask" , default=0.8 , type=snake_case_ , help="Proportion of tokens to mask out." ) parser.add_argument("--word_keep" , default=0.1 , type=snake_case_ , help="Proportion of tokens to keep." ) parser.add_argument("--word_rand" , default=0.1 , type=snake_case_ , help="Proportion of tokens to randomly replace." ) parser.add_argument( "--mlm_smoothing" , default=0.7 , type=snake_case_ , help="Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec)." , ) parser.add_argument("--token_counts" , type=snake_case_ , help="The token counts in the data_file for MLM." ) parser.add_argument( "--restrict_ce_to_mask" , action="store_true" , help="If true, compute the distillation loss only the [MLM] prediction distribution." , ) parser.add_argument( "--freeze_pos_embs" , action="store_true" , help="Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only." , ) parser.add_argument( "--freeze_token_type_embds" , action="store_true" , help="Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only." , ) parser.add_argument("--n_epoch" , type=snake_case_ , default=3 , help="Number of pass on the whole dataset." ) parser.add_argument("--batch_size" , type=snake_case_ , default=5 , help="Batch size (for each process)." ) parser.add_argument( "--group_by_size" , action="store_false" , help="If true, group sequences that have similar length into the same batch. Default is true." , ) parser.add_argument( "--gradient_accumulation_steps" , type=snake_case_ , default=50 , help="Gradient accumulation for larger training batches." , ) parser.add_argument("--warmup_prop" , default=0.05 , type=snake_case_ , help="Linear warmup proportion." ) parser.add_argument("--weight_decay" , default=0.0 , type=snake_case_ , help="Weight decay if we apply some." ) parser.add_argument("--learning_rate" , default=5E-4 , type=snake_case_ , help="The initial learning rate for Adam." ) parser.add_argument("--adam_epsilon" , default=1E-6 , type=snake_case_ , help="Epsilon for Adam optimizer." ) parser.add_argument("--max_grad_norm" , default=5.0 , type=snake_case_ , help="Max gradient norm." ) parser.add_argument("--initializer_range" , default=0.02 , type=snake_case_ , help="Random initialization range." ) parser.add_argument( "--fp16" , action="store_true" , help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit" , ) parser.add_argument( "--fp16_opt_level" , type=snake_case_ , default="O1" , help=( "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html" ) , ) parser.add_argument("--n_gpu" , type=snake_case_ , default=1 , help="Number of GPUs in the node." ) parser.add_argument("--local_rank" , type=snake_case_ , default=-1 , help="Distributed training - Local rank" ) parser.add_argument("--seed" , type=snake_case_ , default=56 , help="Random seed" ) parser.add_argument("--log_interval" , type=snake_case_ , default=5_00 , help="Tensorboard logging interval." ) parser.add_argument("--checkpoint_interval" , type=snake_case_ , default=40_00 , help="Checkpoint interval." ) UpperCAmelCase_ = parser.parse_args() sanity_checks(snake_case_ ) # ARGS # init_gpu_params(snake_case_ ) set_seed(snake_case_ ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f"""Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite""" " itUse `--force` if you want to overwrite it" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f"""Experiment will be dumped and logged in {args.dump_path}""" ) # SAVE PARAMS # logger.info(f"""Param: {args}""" ) with open(os.path.join(args.dump_path , "parameters.json" ) , "w" ) as f: json.dump(vars(snake_case_ ) , snake_case_ , indent=4 ) git_log(args.dump_path ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = MODEL_CLASSES[args.student_type] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = MODEL_CLASSES[args.teacher_type] # TOKENIZER # UpperCAmelCase_ = teacher_tokenizer_class.from_pretrained(args.teacher_name ) UpperCAmelCase_ = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): UpperCAmelCase_ = tokenizer.all_special_tokens.index(snake_case_ ) UpperCAmelCase_ = tokenizer.all_special_ids[idx] logger.info(f"""Special tokens {special_tok_ids}""" ) UpperCAmelCase_ = special_tok_ids UpperCAmelCase_ = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f"""Loading data from {args.data_file}""" ) with open(args.data_file , "rb" ) as fp: UpperCAmelCase_ = pickle.load(snake_case_ ) if args.mlm: logger.info(f"""Loading token counts from {args.token_counts} (already pre-computed)""" ) with open(args.token_counts , "rb" ) as fp: UpperCAmelCase_ = pickle.load(snake_case_ ) UpperCAmelCase_ = np.maximum(snake_case_ , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): UpperCAmelCase_ = 0.0 # do not predict special tokens UpperCAmelCase_ = torch.from_numpy(snake_case_ ) else: UpperCAmelCase_ = None UpperCAmelCase_ = LmSeqsDataset(params=snake_case_ , data=snake_case_ ) logger.info("Data loader created." ) # STUDENT # logger.info(f"""Loading student config from {args.student_config}""" ) UpperCAmelCase_ = student_config_class.from_pretrained(args.student_config ) UpperCAmelCase_ = True if args.student_pretrained_weights is not None: logger.info(f"""Loading pretrained weights from {args.student_pretrained_weights}""" ) UpperCAmelCase_ = student_model_class.from_pretrained(args.student_pretrained_weights , config=snake_case_ ) else: UpperCAmelCase_ = student_model_class(snake_case_ ) if args.n_gpu > 0: student.to(f"""cuda:{args.local_rank}""" ) logger.info("Student loaded." ) # TEACHER # UpperCAmelCase_ = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=snake_case_ ) if args.n_gpu > 0: teacher.to(f"""cuda:{args.local_rank}""" ) logger.info(f"""Teacher loaded from {args.teacher_name}.""" ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(snake_case_ , snake_case_ ) if args.freeze_token_type_embds: freeze_token_type_embeddings(snake_case_ , snake_case_ ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() UpperCAmelCase_ = Distiller( params=snake_case_ , dataset=snake_case_ , token_probs=snake_case_ , student=snake_case_ , teacher=snake_case_ ) distiller.train() logger.info("Let's go get some drinks." ) if __name__ == "__main__": main()
78
0
from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging a_ = logging.get_logger(__name__) # pylint: disable=invalid-name class UpperCAmelCase__ ( UpperCamelCase__ ): """simple docstring""" def __init__( self: Any , __lowerCAmelCase: CLIPSegForImageSegmentation , __lowerCAmelCase: CLIPSegProcessor , __lowerCAmelCase: AutoencoderKL , __lowerCAmelCase: CLIPTextModel , __lowerCAmelCase: CLIPTokenizer , __lowerCAmelCase: UNetaDConditionModel , __lowerCAmelCase: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __lowerCAmelCase: StableDiffusionSafetyChecker , __lowerCAmelCase: CLIPImageProcessor , ) -> Optional[Any]: '''simple docstring''' super().__init__() if hasattr(scheduler.config , "steps_offset" ) and scheduler.config.steps_offset != 1: __UpperCAmelCase = ( F'''The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`''' F''' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure ''' "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1" , "1.0.0" , __a , standard_warn=__a ) __UpperCAmelCase = dict(scheduler.config ) __UpperCAmelCase = 1 __UpperCAmelCase = FrozenDict(__a ) if hasattr(scheduler.config , "skip_prk_steps" ) and scheduler.config.skip_prk_steps is False: __UpperCAmelCase = ( F'''The configuration file of this scheduler: {scheduler} has not set the configuration''' " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" " Hub, it would be very nice if you could open a Pull request for the" " `scheduler/scheduler_config.json` file" ) deprecate("skip_prk_steps not set" , "1.0.0" , __a , standard_warn=__a ) __UpperCAmelCase = dict(scheduler.config ) __UpperCAmelCase = True __UpperCAmelCase = FrozenDict(__a ) if safety_checker is None: logger.warning( F'''You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure''' " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." ) self.register_modules( segmentation_model=__a , segmentation_processor=__a , vae=__a , text_encoder=__a , tokenizer=__a , unet=__a , scheduler=__a , safety_checker=__a , feature_extractor=__a , ) def _UpperCAmelCase ( self: str , __lowerCAmelCase: Optional[Union[str, int]] = "auto" ) -> List[str]: '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __UpperCAmelCase = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__a ) def _UpperCAmelCase ( self: int ) -> int: '''simple docstring''' self.enable_attention_slicing(__a ) def _UpperCAmelCase ( self: Optional[Any] ) -> Optional[Any]: '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) __UpperCAmelCase = torch.device("cuda" ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(__a , __a ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _UpperCAmelCase ( self: Optional[int] ) -> Union[str, Any]: '''simple docstring''' if self.device != torch.device("meta" ) or not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(__a , "_hf_hook" ) and hasattr(module._hf_hook , "execution_device" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__( self: Dict , __lowerCAmelCase: Union[str, List[str]] , __lowerCAmelCase: Union[torch.FloatTensor, PIL.Image.Image] , __lowerCAmelCase: str , __lowerCAmelCase: int = 512 , __lowerCAmelCase: int = 512 , __lowerCAmelCase: int = 50 , __lowerCAmelCase: float = 7.5 , __lowerCAmelCase: Optional[Union[str, List[str]]] = None , __lowerCAmelCase: Optional[int] = 1 , __lowerCAmelCase: float = 0.0 , __lowerCAmelCase: Optional[torch.Generator] = None , __lowerCAmelCase: Optional[torch.FloatTensor] = None , __lowerCAmelCase: Optional[str] = "pil" , __lowerCAmelCase: bool = True , __lowerCAmelCase: Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __lowerCAmelCase: int = 1 , **__lowerCAmelCase: int , ) -> Tuple: '''simple docstring''' __UpperCAmelCase = self.segmentation_processor( text=[text] , images=[image] , padding="max_length" , return_tensors="pt" ).to(self.device ) __UpperCAmelCase = self.segmentation_model(**__a ) __UpperCAmelCase = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() __UpperCAmelCase = self.numpy_to_pil(__a )[0].resize(image.size ) # Run inpainting pipeline with the generated mask __UpperCAmelCase = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=__a , image=__a , mask_image=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , )
221
'''simple docstring''' import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __A ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): a__ : int = AutoencoderKL a__ : Optional[Any] = """sample""" a__ : Union[str, Any] = 1e-2 @property def _lowercase (self : Optional[int] ): UpperCAmelCase_ = 4 UpperCAmelCase_ = 3 UpperCAmelCase_ = (32, 32) UpperCAmelCase_ = floats_tensor((batch_size, num_channels) + sizes ).to(__a ) return {"sample": image} @property def _lowercase (self : Any ): return (3, 32, 32) @property def _lowercase (self : Dict ): return (3, 32, 32) def _lowercase (self : int ): UpperCAmelCase_ = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } UpperCAmelCase_ = self.dummy_input return init_dict, inputs_dict def _lowercase (self : int ): pass def _lowercase (self : int ): pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def _lowercase (self : List[Any] ): # enable deterministic behavior for gradient checkpointing UpperCAmelCase_ , UpperCAmelCase_ = self.prepare_init_args_and_inputs_for_common() UpperCAmelCase_ = self.model_class(**__a ) model.to(__a ) assert not model.is_gradient_checkpointing and model.training UpperCAmelCase_ = model(**__a ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() UpperCAmelCase_ = torch.randn_like(__a ) UpperCAmelCase_ = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing UpperCAmelCase_ = self.model_class(**__a ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(__a ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training UpperCAmelCase_ = model_a(**__a ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() UpperCAmelCase_ = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) UpperCAmelCase_ = dict(model.named_parameters() ) UpperCAmelCase_ = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def _lowercase (self : Any ): UpperCAmelCase_ , UpperCAmelCase_ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=__a ) self.assertIsNotNone(__a ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(__a ) UpperCAmelCase_ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def _lowercase (self : List[str] ): UpperCAmelCase_ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) UpperCAmelCase_ = model.to(__a ) model.eval() if torch_device == "mps": UpperCAmelCase_ = torch.manual_seed(0 ) else: UpperCAmelCase_ = torch.Generator(device=__a ).manual_seed(0 ) UpperCAmelCase_ = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) UpperCAmelCase_ = image.to(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , sample_posterior=__a , generator=__a ).sample UpperCAmelCase_ = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": UpperCAmelCase_ = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": UpperCAmelCase_ = torch.tensor( [-0.13_52, 0.08_78, 0.04_19, -0.08_18, -0.10_69, 0.06_88, -0.14_58, -0.44_46, -0.00_26] ) else: UpperCAmelCase_ = torch.tensor( [-0.24_21, 0.46_42, 0.25_07, -0.04_38, 0.06_82, 0.31_60, -0.20_18, -0.07_27, 0.24_85] ) self.assertTrue(torch_all_close(__a , __a , rtol=1E-2 ) ) @slow class __A ( unittest.TestCase ): def _lowercase (self : Dict , __a : Dict , __a : int ): return f"""gaussian_noise_s={seed}_shape={"_".join([str(__a ) for s in shape] )}.npy""" def _lowercase (self : str ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self : Optional[Any] , __a : Optional[Any]=0 , __a : str=(4, 3, 512, 512) , __a : List[str]=False ): UpperCAmelCase_ = torch.floataa if fpaa else torch.floataa UpperCAmelCase_ = torch.from_numpy(load_hf_numpy(self.get_file_format(__a , __a ) ) ).to(__a ).to(__a ) return image def _lowercase (self : List[Any] , __a : Union[str, Any]="CompVis/stable-diffusion-v1-4" , __a : List[Any]=False ): UpperCAmelCase_ = "fp16" if fpaa else None UpperCAmelCase_ = torch.floataa if fpaa else torch.floataa UpperCAmelCase_ = AutoencoderKL.from_pretrained( __a , subfolder="vae" , torch_dtype=__a , revision=__a , ) model.to(__a ).eval() return model def _lowercase (self : List[Any] , __a : List[Any]=0 ): if torch_device == "mps": return torch.manual_seed(__a ) return torch.Generator(device=__a ).manual_seed(__a ) @parameterized.expand( [ # fmt: off [33, [-0.16_03, 0.98_78, -0.04_95, -0.07_90, -0.27_09, 0.83_75, -0.20_60, -0.08_24], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_76, 0.11_68, 0.13_32, -0.48_40, -0.25_08, -0.07_91, -0.04_93, -0.40_89], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def _lowercase (self : List[Any] , __a : Dict , __a : Optional[int] , __a : List[str] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , generator=__a , sample_posterior=__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, -2:, :2].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(__a , __a , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.05_13, 0.02_89, 1.37_99, 0.21_66, -0.25_73, -0.08_71, 0.51_03, -0.09_99]], [47, [-0.41_28, -0.13_20, -0.37_04, 0.19_65, -0.41_16, -0.23_32, -0.33_40, 0.22_47]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : Dict , __a : Optional[int] , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , fpaa=__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , generator=__a , sample_posterior=__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.16_09, 0.98_66, -0.04_87, -0.07_77, -0.27_16, 0.83_68, -0.20_55, -0.08_14], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_77, 0.11_47, 0.13_33, -0.48_41, -0.25_06, -0.08_05, -0.04_91, -0.40_85], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def _lowercase (self : str , __a : int , __a : Union[str, Any] , __a : List[Any] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, -2:, :2].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(__a , __a , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.20_51, -0.18_03, -0.23_11, -0.21_14, -0.32_92, -0.35_74, -0.29_53, -0.33_23]], [37, [-0.26_32, -0.26_25, -0.21_99, -0.27_41, -0.45_39, -0.49_90, -0.37_20, -0.49_25]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : int , __a : int , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.03_69, 0.02_07, -0.07_76, -0.06_82, -0.17_47, -0.19_30, -0.14_65, -0.20_39]], [16, [-0.16_28, -0.21_34, -0.27_47, -0.26_42, -0.37_74, -0.44_04, -0.36_87, -0.42_77]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : Union[str, Any] , __a : List[str] , __a : Optional[Any] ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) , fpaa=__a ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , atol=5E-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def _lowercase (self : List[str] , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) , fpaa=__a ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__a , __a , atol=1E-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def _lowercase (self : Union[str, Any] , __a : Dict ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__a , __a , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.30_01, 0.09_18, -2.69_84, -3.97_20, -3.20_99, -5.03_53, 1.73_38, -0.20_65, 3.42_67]], [47, [-1.50_30, -4.38_71, -6.03_55, -9.11_57, -1.66_61, -2.78_53, 2.16_07, -5.08_23, 2.56_33]], # fmt: on ] ) def _lowercase (self : Tuple , __a : List[Any] , __a : List[Any] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model.encode(__a ).latent_dist UpperCAmelCase_ = dist.sample(generator=__a ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] UpperCAmelCase_ = sample[0, -1, -3:, -3:].flatten().cpu() UpperCAmelCase_ = torch.tensor(__a ) UpperCAmelCase_ = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(__a , __a , atol=__a )
78
0
"""simple docstring""" from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool _A = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyè': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmål': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class _lowerCamelCase ( UpperCamelCase__ ): _lowerCamelCase :Any = """facebook/nllb-200-distilled-600M""" _lowerCamelCase :Union[str, Any] = ( """This is a tool that translates text from a language to another. It takes three inputs: `text`, which should """ """be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, """ """which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in """ """plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`.""" ) _lowerCamelCase :int = """translator""" _lowerCamelCase :Optional[Any] = AutoTokenizer _lowerCamelCase :Optional[Any] = AutoModelForSeqaSeqLM _lowerCamelCase :Dict = LANGUAGE_CODES _lowerCamelCase :Union[str, Any] = ["""text""", """text""", """text"""] _lowerCamelCase :Union[str, Any] = ["""text"""] def _lowerCAmelCase ( self : int , UpperCamelCase : int , UpperCamelCase : Dict , UpperCamelCase : int ) -> str: """simple docstring""" if src_lang not in self.lang_to_code: raise ValueError(f"""{src_lang} is not a supported language.""" ) if tgt_lang not in self.lang_to_code: raise ValueError(f"""{tgt_lang} is not a supported language.""" ) lowerCAmelCase__ : Optional[Any] = self.lang_to_code[src_lang] lowerCAmelCase__ : int = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( __a , return_tensors="""pt""" , src_lang=__a , tgt_lang=__a ) def _lowerCAmelCase ( self : Optional[Any] , UpperCamelCase : List[str] ) -> List[Any]: """simple docstring""" return self.model.generate(**__a ) def _lowerCAmelCase ( self : Any , UpperCamelCase : Tuple ) -> Tuple: """simple docstring""" return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=__a )
299
'''simple docstring''' import logging from transformers import PretrainedConfig SCREAMING_SNAKE_CASE_: Any =logging.getLogger(__name__) SCREAMING_SNAKE_CASE_: Any ={ 'bertabs-finetuned-cnndm': 'https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json', } class __A ( UpperCamelCase__ ): a__ : List[Any] = """bertabs""" def __init__(self : Any , __a : int=30522 , __a : Tuple=512 , __a : Tuple=6 , __a : Dict=512 , __a : int=8 , __a : List[Any]=512 , __a : List[str]=0.2 , __a : List[Any]=6 , __a : int=768 , __a : Any=8 , __a : Dict=2048 , __a : Tuple=0.2 , **__a : Optional[int] , ): super().__init__(**__a ) UpperCAmelCase_ = vocab_size UpperCAmelCase_ = max_pos UpperCAmelCase_ = enc_layers UpperCAmelCase_ = enc_hidden_size UpperCAmelCase_ = enc_heads UpperCAmelCase_ = enc_ff_size UpperCAmelCase_ = enc_dropout UpperCAmelCase_ = dec_layers UpperCAmelCase_ = dec_hidden_size UpperCAmelCase_ = dec_heads UpperCAmelCase_ = dec_ff_size UpperCAmelCase_ = dec_dropout
78
0
import argparse import hashlib # hashlib is only used inside the Test class import struct class __lowerCAmelCase : """simple docstring""" def __init__( self : str , _lowerCAmelCase : Any ) -> Tuple: """simple docstring""" snake_case_ = data snake_case_ = [0X6_7_4_5_2_3_0_1, 0XE_F_C_D_A_B_8_9, 0X9_8_B_A_D_C_F_E, 0X1_0_3_2_5_4_7_6, 0XC_3_D_2_E_1_F_0] @staticmethod def lowerCAmelCase__ ( _lowerCAmelCase : List[str] , _lowerCAmelCase : str ) -> Any: """simple docstring""" return ((n << b) | (n >> (3_2 - b))) & 0XF_F_F_F_F_F_F_F def lowerCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" snake_case_ = B"\x80" + B"\x00" * (6_3 - (len(self.data ) + 8) % 6_4) snake_case_ = self.data + padding + struct.pack(">Q" , 8 * len(self.data ) ) return padded_data def lowerCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" return [ self.padded_data[i : i + 6_4] for i in range(0 , len(self.padded_data ) , 6_4 ) ] def lowerCAmelCase__ ( self : Union[str, Any] , _lowerCAmelCase : Optional[int] ) -> List[str]: """simple docstring""" snake_case_ = list(struct.unpack(">16L" , __a ) ) + [0] * 6_4 for i in range(1_6 , 8_0 ): snake_case_ = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 1_4] ^ w[i - 1_6]) , 1 ) return w def lowerCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" snake_case_ = self.padding() snake_case_ = self.split_blocks() for block in self.blocks: snake_case_ = self.expand_block(__a ) snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ = self.h for i in range(0 , 8_0 ): if 0 <= i < 2_0: snake_case_ = (b & c) | ((~b) & d) snake_case_ = 0X5_A_8_2_7_9_9_9 elif 2_0 <= i < 4_0: snake_case_ = b ^ c ^ d snake_case_ = 0X6_E_D_9_E_B_A_1 elif 4_0 <= i < 6_0: snake_case_ = (b & c) | (b & d) | (c & d) snake_case_ = 0X8_F_1_B_B_C_D_C elif 6_0 <= i < 8_0: snake_case_ = b ^ c ^ d snake_case_ = 0XC_A_6_2_C_1_D_6 snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ = ( self.rotate(__a , 5 ) + f + e + k + expanded_block[i] & 0XF_F_F_F_F_F_F_F, a, self.rotate(__a , 3_0 ), c, d, ) snake_case_ = ( self.h[0] + a & 0XF_F_F_F_F_F_F_F, self.h[1] + b & 0XF_F_F_F_F_F_F_F, self.h[2] + c & 0XF_F_F_F_F_F_F_F, self.h[3] + d & 0XF_F_F_F_F_F_F_F, self.h[4] + e & 0XF_F_F_F_F_F_F_F, ) return ("{:08x}" * 5).format(*self.h ) def _lowerCAmelCase ( )->Union[str, Any]: '''simple docstring''' snake_case_ = b"Test String" assert SHAaHash(snake_case_ ).final_hash() == hashlib.shaa(snake_case_ ).hexdigest() # noqa: S324 def _lowerCAmelCase ( )->Dict: '''simple docstring''' snake_case_ = argparse.ArgumentParser(description="Process some strings or files" ) parser.add_argument( "--string" , dest="input_string" , default="Hello World!! Welcome to Cryptography" , help="Hash the string" , ) parser.add_argument("--file" , dest="input_file" , help="Hash contents of a file" ) snake_case_ = parser.parse_args() snake_case_ = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , "rb" ) as f: snake_case_ = f.read() else: snake_case_ = bytes(snake_case_ , "utf-8" ) print(SHAaHash(snake_case_ ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
283
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE_: Tuple =logging.get_logger(__name__) def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> int: '''simple docstring''' UpperCAmelCase_ = "huggingface/label-files" UpperCAmelCase_ = "imagenet-1k-id2label.json" UpperCAmelCase_ = json.load(open(hf_hub_download(snake_case_ , snake_case_ , repo_type="dataset" ) , "r" ) ) UpperCAmelCase_ = {int(snake_case_ ): v for k, v in idalabel.items()} UpperCAmelCase_ = {v: k for k, v in idalabel.items()} UpperCAmelCase_ = "std_conv" if "bit" in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" UpperCAmelCase_ = BitConfig( conv_layer=snake_case_ , num_labels=10_00 , idalabel=snake_case_ , labelaid=snake_case_ , ) return config def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' if "stem.conv" in name: UpperCAmelCase_ = name.replace("stem.conv" , "bit.embedder.convolution" ) if "blocks" in name: UpperCAmelCase_ = name.replace("blocks" , "layers" ) if "head.fc" in name: UpperCAmelCase_ = name.replace("head.fc" , "classifier.1" ) if name.startswith("norm" ): UpperCAmelCase_ = "bit." + name if "bit" not in name and "classifier" not in name: UpperCAmelCase_ = "bit.encoder." + name return name def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = "http://images.cocodataset.org/val2017/000000039769.jpg" UpperCAmelCase_ = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : Tuple , snake_case_ : Optional[Any] , snake_case_ : int=False ) -> List[Any]: '''simple docstring''' UpperCAmelCase_ = get_config(snake_case_ ) # load original model from timm UpperCAmelCase_ = create_model(snake_case_ , pretrained=snake_case_ ) timm_model.eval() # load state_dict of original model UpperCAmelCase_ = timm_model.state_dict() for key in state_dict.copy().keys(): UpperCAmelCase_ = state_dict.pop(snake_case_ ) UpperCAmelCase_ = val.squeeze() if "head" in key else val # load HuggingFace model UpperCAmelCase_ = BitForImageClassification(snake_case_ ) model.eval() model.load_state_dict(snake_case_ ) # create image processor UpperCAmelCase_ = create_transform(**resolve_data_config({} , model=snake_case_ ) ) UpperCAmelCase_ = transform.transforms UpperCAmelCase_ = { "bilinear": PILImageResampling.BILINEAR, "bicubic": PILImageResampling.BICUBIC, "nearest": PILImageResampling.NEAREST, } UpperCAmelCase_ = BitImageProcessor( do_resize=snake_case_ , size={"shortest_edge": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=snake_case_ , crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]} , do_normalize=snake_case_ , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = transform(snake_case_ ).unsqueeze(0 ) UpperCAmelCase_ = processor(snake_case_ , return_tensors="pt" ).pixel_values # verify pixel values assert torch.allclose(snake_case_ , snake_case_ ) # verify logits with torch.no_grad(): UpperCAmelCase_ = model(snake_case_ ) UpperCAmelCase_ = outputs.logits print("Logits:" , logits[0, :3] ) print("Predicted class:" , model.config.idalabel[logits.argmax(-1 ).item()] ) UpperCAmelCase_ = timm_model(snake_case_ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(snake_case_ , outputs.logits , atol=1E-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) print(f"""Saving model {model_name} and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(snake_case_ ) processor.save_pretrained(snake_case_ ) if push_to_hub: print(f"""Pushing model {model_name} and processor to the hub""" ) model.push_to_hub(f"""ybelkada/{model_name}""" ) processor.push_to_hub(f"""ybelkada/{model_name}""" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: int =argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='resnetv2_50x1_bitm', type=str, help='Name of the BiT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model to the hub.', ) SCREAMING_SNAKE_CASE_: Union[str, Any] =parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
78
0
"""simple docstring""" import gc import unittest import numpy as np import torch import torch.nn.functional as F from transformers import ( ClapTextConfig, ClapTextModelWithProjection, RobertaTokenizer, SpeechTaHifiGan, SpeechTaHifiGanConfig, ) from diffusers import ( AudioLDMPipeline, AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class A( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" A = AudioLDMPipeline A = TEXT_TO_AUDIO_PARAMS A = TEXT_TO_AUDIO_BATCH_PARAMS A = frozenset( [ "num_inference_steps", "num_waveforms_per_prompt", "generator", "latents", "output_type", "return_dict", "callback", "callback_steps", ] ) def _UpperCamelCase( self ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) _UpperCamelCase :List[str] = 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, 64) , class_embed_type='''simple_projection''' , projection_class_embeddings_input_dim=32 , class_embeddings_concat=__a , ) _UpperCamelCase :Tuple = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' , clip_sample=__a , set_alpha_to_one=__a , ) torch.manual_seed(0 ) _UpperCamelCase :Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) _UpperCamelCase :int = ClapTextConfig( 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 , projection_dim=32 , ) _UpperCamelCase :str = ClapTextModelWithProjection(__a ) _UpperCamelCase :Optional[Any] = RobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-roberta''' , model_max_length=77 ) _UpperCamelCase :Tuple = SpeechTaHifiGanConfig( model_in_dim=8 , sampling_rate=1_60_00 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=__a , ) _UpperCamelCase :List[str] = SpeechTaHifiGan(__a ) _UpperCamelCase :Optional[Any] = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''vocoder''': vocoder, } return components def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=0 ) -> Optional[Any]: """simple docstring""" if str(__a ).startswith('''mps''' ): _UpperCamelCase :str = torch.manual_seed(__a ) else: _UpperCamelCase :Optional[Any] = torch.Generator(device=__a ).manual_seed(__a ) _UpperCamelCase :List[str] = { '''prompt''': '''A hammer hitting a wooden surface''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, } return inputs def _UpperCamelCase( self ) -> List[str]: """simple docstring""" _UpperCamelCase :Optional[Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator _UpperCamelCase :List[str] = self.get_dummy_components() _UpperCamelCase :Dict = AudioLDMPipeline(**__a ) _UpperCamelCase :Any = audioldm_pipe.to(__a ) audioldm_pipe.set_progress_bar_config(disable=__a ) _UpperCamelCase :int = self.get_dummy_inputs(__a ) _UpperCamelCase :int = audioldm_pipe(**__a ) _UpperCamelCase :Any = output.audios[0] assert audio.ndim == 1 assert len(__a ) == 2_56 _UpperCamelCase :str = audio[:10] _UpperCamelCase :Any = np.array( [-0.0_0_5_0, 0.0_0_5_0, -0.0_0_6_0, 0.0_0_3_3, -0.0_0_2_6, 0.0_0_3_3, -0.0_0_2_7, 0.0_0_3_3, -0.0_0_2_8, 0.0_0_3_3] ) assert np.abs(audio_slice - expected_slice ).max() < 1E-2 def _UpperCamelCase( self ) -> Dict: """simple docstring""" _UpperCamelCase :Optional[Any] = self.get_dummy_components() _UpperCamelCase :str = AudioLDMPipeline(**__a ) _UpperCamelCase :int = audioldm_pipe.to(__a ) _UpperCamelCase :Any = audioldm_pipe.to(__a ) audioldm_pipe.set_progress_bar_config(disable=__a ) _UpperCamelCase :Union[str, Any] = self.get_dummy_inputs(__a ) _UpperCamelCase :Tuple = 3 * [inputs['''prompt''']] # forward _UpperCamelCase :Optional[Any] = audioldm_pipe(**__a ) _UpperCamelCase :Tuple = output.audios[0] _UpperCamelCase :Dict = self.get_dummy_inputs(__a ) _UpperCamelCase :Tuple = 3 * [inputs.pop('''prompt''' )] _UpperCamelCase :int = audioldm_pipe.tokenizer( __a , padding='''max_length''' , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=__a , return_tensors='''pt''' , ) _UpperCamelCase :int = text_inputs['''input_ids'''].to(__a ) _UpperCamelCase :List[Any] = audioldm_pipe.text_encoder( __a , ) _UpperCamelCase :List[Any] = prompt_embeds.text_embeds # additional L_2 normalization over each hidden-state _UpperCamelCase :Optional[int] = F.normalize(__a , dim=-1 ) _UpperCamelCase :str = prompt_embeds # forward _UpperCamelCase :List[str] = audioldm_pipe(**__a ) _UpperCamelCase :Tuple = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1E-2 def _UpperCamelCase( self ) -> Any: """simple docstring""" _UpperCamelCase :str = self.get_dummy_components() _UpperCamelCase :Tuple = AudioLDMPipeline(**__a ) _UpperCamelCase :List[Any] = audioldm_pipe.to(__a ) _UpperCamelCase :str = audioldm_pipe.to(__a ) audioldm_pipe.set_progress_bar_config(disable=__a ) _UpperCamelCase :Union[str, Any] = self.get_dummy_inputs(__a ) _UpperCamelCase :int = 3 * ['''this is a negative prompt'''] _UpperCamelCase :List[str] = negative_prompt _UpperCamelCase :Union[str, Any] = 3 * [inputs['''prompt''']] # forward _UpperCamelCase :List[Any] = audioldm_pipe(**__a ) _UpperCamelCase :Any = output.audios[0] _UpperCamelCase :str = self.get_dummy_inputs(__a ) _UpperCamelCase :Dict = 3 * [inputs.pop('''prompt''' )] _UpperCamelCase :int = [] for p in [prompt, negative_prompt]: _UpperCamelCase :Optional[Any] = audioldm_pipe.tokenizer( __a , padding='''max_length''' , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=__a , return_tensors='''pt''' , ) _UpperCamelCase :str = text_inputs['''input_ids'''].to(__a ) _UpperCamelCase :Union[str, Any] = audioldm_pipe.text_encoder( __a , ) _UpperCamelCase :Dict = text_embeds.text_embeds # additional L_2 normalization over each hidden-state _UpperCamelCase :Union[str, Any] = F.normalize(__a , dim=-1 ) embeds.append(__a ) _UpperCamelCase , _UpperCamelCase :Any = embeds # forward _UpperCamelCase :Any = audioldm_pipe(**__a ) _UpperCamelCase :Optional[Any] = output.audios[0] assert np.abs(audio_a - audio_a ).max() < 1E-2 def _UpperCamelCase( self ) -> List[str]: """simple docstring""" _UpperCamelCase :Tuple = '''cpu''' # ensure determinism for the device-dependent torch.Generator _UpperCamelCase :Optional[int] = self.get_dummy_components() _UpperCamelCase :Tuple = PNDMScheduler(skip_prk_steps=__a ) _UpperCamelCase :List[str] = AudioLDMPipeline(**__a ) _UpperCamelCase :Union[str, Any] = audioldm_pipe.to(__a ) audioldm_pipe.set_progress_bar_config(disable=__a ) _UpperCamelCase :Dict = self.get_dummy_inputs(__a ) _UpperCamelCase :List[str] = '''egg cracking''' _UpperCamelCase :Dict = audioldm_pipe(**__a , negative_prompt=__a ) _UpperCamelCase :Union[str, Any] = output.audios[0] assert audio.ndim == 1 assert len(__a ) == 2_56 _UpperCamelCase :int = audio[:10] _UpperCamelCase :Dict = np.array( [-0.0_0_5_1, 0.0_0_5_0, -0.0_0_6_0, 0.0_0_3_4, -0.0_0_2_6, 0.0_0_3_3, -0.0_0_2_7, 0.0_0_3_3, -0.0_0_2_8, 0.0_0_3_2] ) assert np.abs(audio_slice - expected_slice ).max() < 1E-2 def _UpperCamelCase( self ) -> str: """simple docstring""" _UpperCamelCase :str = '''cpu''' # ensure determinism for the device-dependent torch.Generator _UpperCamelCase :List[str] = self.get_dummy_components() _UpperCamelCase :Union[str, Any] = PNDMScheduler(skip_prk_steps=__a ) _UpperCamelCase :Optional[Any] = AudioLDMPipeline(**__a ) _UpperCamelCase :str = audioldm_pipe.to(__a ) audioldm_pipe.set_progress_bar_config(disable=__a ) _UpperCamelCase :Union[str, Any] = '''A hammer hitting a wooden surface''' # test num_waveforms_per_prompt=1 (default) _UpperCamelCase :Dict = audioldm_pipe(__a , num_inference_steps=2 ).audios assert audios.shape == (1, 2_56) # test num_waveforms_per_prompt=1 (default) for batch of prompts _UpperCamelCase :Dict = 2 _UpperCamelCase :Union[str, Any] = audioldm_pipe([prompt] * batch_size , num_inference_steps=2 ).audios assert audios.shape == (batch_size, 2_56) # test num_waveforms_per_prompt for single prompt _UpperCamelCase :int = 2 _UpperCamelCase :Union[str, Any] = audioldm_pipe(__a , num_inference_steps=2 , num_waveforms_per_prompt=__a ).audios assert audios.shape == (num_waveforms_per_prompt, 2_56) # test num_waveforms_per_prompt for batch of prompts _UpperCamelCase :List[Any] = 2 _UpperCamelCase :Dict = audioldm_pipe( [prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=__a ).audios assert audios.shape == (batch_size * num_waveforms_per_prompt, 2_56) def _UpperCamelCase( self ) -> int: """simple docstring""" _UpperCamelCase :Optional[Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator _UpperCamelCase :str = self.get_dummy_components() _UpperCamelCase :int = AudioLDMPipeline(**__a ) _UpperCamelCase :str = audioldm_pipe.to(__a ) audioldm_pipe.set_progress_bar_config(disable=__a ) _UpperCamelCase :Dict = audioldm_pipe.vocoder.config.sampling_rate _UpperCamelCase :Optional[Any] = self.get_dummy_inputs(__a ) _UpperCamelCase :List[str] = audioldm_pipe(audio_length_in_s=0.0_1_6 , **__a ) _UpperCamelCase :str = output.audios[0] assert audio.ndim == 1 assert len(__a ) / vocoder_sampling_rate == 0.0_1_6 _UpperCamelCase :Optional[Any] = audioldm_pipe(audio_length_in_s=0.0_3_2 , **__a ) _UpperCamelCase :Any = output.audios[0] assert audio.ndim == 1 assert len(__a ) / vocoder_sampling_rate == 0.0_3_2 def _UpperCamelCase( self ) -> List[Any]: """simple docstring""" _UpperCamelCase :Dict = self.get_dummy_components() _UpperCamelCase :Tuple = AudioLDMPipeline(**__a ) _UpperCamelCase :Any = audioldm_pipe.to(__a ) audioldm_pipe.set_progress_bar_config(disable=__a ) _UpperCamelCase :int = ['''hey'''] _UpperCamelCase :Union[str, Any] = audioldm_pipe(__a , num_inference_steps=1 ) _UpperCamelCase :int = output.audios.shape assert audio_shape == (1, 2_56) _UpperCamelCase :Tuple = audioldm_pipe.vocoder.config config.model_in_dim *= 2 _UpperCamelCase :Optional[Any] = SpeechTaHifiGan(__a ).to(__a ) _UpperCamelCase :Union[str, Any] = audioldm_pipe(__a , num_inference_steps=1 ) _UpperCamelCase :Any = output.audios.shape # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram assert audio_shape == (1, 2_56) def _UpperCamelCase( self ) -> List[Any]: """simple docstring""" self._test_attention_slicing_forward_pass(test_mean_pixel_difference=__a ) def _UpperCamelCase( self ) -> Any: """simple docstring""" self._test_inference_batch_single_identical(test_mean_pixel_difference=__a ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def _UpperCamelCase( self ) -> Any: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__a ) @slow class A( unittest.TestCase ): """simple docstring""" def _UpperCamelCase( self ) -> Union[str, Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__="cpu" , SCREAMING_SNAKE_CASE__=torch.floataa , SCREAMING_SNAKE_CASE__=0 ) -> Any: """simple docstring""" _UpperCamelCase :Optional[int] = torch.Generator(device=__a ).manual_seed(__a ) _UpperCamelCase :int = np.random.RandomState(__a ).standard_normal((1, 8, 1_28, 16) ) _UpperCamelCase :Optional[Any] = torch.from_numpy(__a ).to(device=__a , dtype=__a ) _UpperCamelCase :Optional[Any] = { '''prompt''': '''A hammer hitting a wooden surface''', '''latents''': latents, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 2.5, } return inputs def _UpperCamelCase( self ) -> Optional[Any]: """simple docstring""" _UpperCamelCase :Union[str, Any] = AudioLDMPipeline.from_pretrained('''cvssp/audioldm''' ) _UpperCamelCase :Union[str, Any] = audioldm_pipe.to(__a ) audioldm_pipe.set_progress_bar_config(disable=__a ) _UpperCamelCase :List[str] = self.get_inputs(__a ) _UpperCamelCase :Optional[int] = 25 _UpperCamelCase :int = audioldm_pipe(**__a ).audios[0] assert audio.ndim == 1 assert len(__a ) == 8_19_20 _UpperCamelCase :Dict = audio[7_72_30:7_72_40] _UpperCamelCase :Tuple = np.array( [-0.4_8_8_4, -0.4_6_0_7, 0.0_0_2_3, 0.5_0_0_7, 0.5_8_9_6, 0.5_1_5_1, 0.3_8_1_3, -0.0_2_0_8, -0.3_6_8_7, -0.4_3_1_5] ) _UpperCamelCase :str = np.abs(expected_slice - audio_slice ).max() assert max_diff < 1E-2 def _UpperCamelCase( self ) -> Optional[Any]: """simple docstring""" _UpperCamelCase :Tuple = AudioLDMPipeline.from_pretrained('''cvssp/audioldm''' ) _UpperCamelCase :List[Any] = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config ) _UpperCamelCase :Any = audioldm_pipe.to(__a ) audioldm_pipe.set_progress_bar_config(disable=__a ) _UpperCamelCase :List[Any] = self.get_inputs(__a ) _UpperCamelCase :Dict = audioldm_pipe(**__a ).audios[0] assert audio.ndim == 1 assert len(__a ) == 8_19_20 _UpperCamelCase :Dict = audio[2_77_80:2_77_90] _UpperCamelCase :Tuple = np.array([-0.2_1_3_1, -0.0_8_7_3, -0.0_1_2_4, -0.0_1_8_9, 0.0_5_6_9, 0.1_3_7_3, 0.1_8_8_3, 0.2_8_8_6, 0.3_2_9_7, 0.2_2_1_2] ) _UpperCamelCase :Dict = np.abs(expected_slice - audio_slice ).max() assert max_diff < 3E-2
355
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class __A ( unittest.TestCase ): def _lowercase (self : List[str] ): UpperCAmelCase_ = 0 def _lowercase (self : Tuple ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("openai/clip-vit-base-patch32" ) self.assertIsInstance(__a , __a ) def _lowercase (self : str ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : Dict ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : List[str] ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = CLIPConfig() # Create a dummy config file with image_proceesor_type UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ).to_dict() config_dict.pop("image_processor_type" ) UpperCAmelCase_ = CLIPImageProcessor(**__a ) # save in new folder model_config.save_pretrained(__a ) config.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) # make sure private variable is not incorrectly saved UpperCAmelCase_ = json.loads(config.to_json_string() ) self.assertTrue("_processor_class" not in dict_as_saved ) self.assertIsInstance(__a , __a ) def _lowercase (self : int ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : Tuple ): with self.assertRaisesRegex( __a , "clip-base is not a local folder and is not a valid model identifier" ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("clip-base" ) def _lowercase (self : Optional[int] ): with self.assertRaisesRegex( __a , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a , revision="aaaaaa" ) def _lowercase (self : Union[str, Any] ): with self.assertRaisesRegex( __a , "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json." , ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/config-no-model" ) def _lowercase (self : List[Any] ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(__a ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" ) # If remote code is disabled, we can't load this config. with self.assertRaises(__a ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a , trust_remote_code=__a ) self.assertEqual(reloaded_image_processor.__class__.__name__ , "NewImageProcessor" ) def _lowercase (self : Optional[int] ): try: AutoConfig.register("custom" , __a ) AutoImageProcessor.register(__a , __a ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__a ): AutoImageProcessor.register(__a , __a ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = CustomImageProcessor.from_pretrained(__a ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def _lowercase (self : Optional[int] ): class __A ( UpperCamelCase__ ): a__ : str = True try: AutoConfig.register("custom" , __a ) AutoImageProcessor.register(__a , __a ) # If remote code is not set, the default is to use local UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(not hasattr(__a , "is_local" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
78
0
'''simple docstring''' import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# __SCREAMING_SNAKE_CASE : Dict =[ # (stable-diffusion, HF Diffusers) ('time_embed.0.weight', 'time_embedding.linear_1.weight'), ('time_embed.0.bias', 'time_embedding.linear_1.bias'), ('time_embed.2.weight', 'time_embedding.linear_2.weight'), ('time_embed.2.bias', 'time_embedding.linear_2.bias'), ('input_blocks.0.0.weight', 'conv_in.weight'), ('input_blocks.0.0.bias', 'conv_in.bias'), ('out.0.weight', 'conv_norm_out.weight'), ('out.0.bias', 'conv_norm_out.bias'), ('out.2.weight', 'conv_out.weight'), ('out.2.bias', 'conv_out.bias'), ] __SCREAMING_SNAKE_CASE : List[Any] =[ # (stable-diffusion, HF Diffusers) ('in_layers.0', 'norm1'), ('in_layers.2', 'conv1'), ('out_layers.0', 'norm2'), ('out_layers.3', 'conv2'), ('emb_layers.1', 'time_emb_proj'), ('skip_connection', 'conv_shortcut'), ] __SCREAMING_SNAKE_CASE : Union[str, Any] =[] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks __SCREAMING_SNAKE_CASE : Any =f"""down_blocks.{i}.resnets.{j}.""" __SCREAMING_SNAKE_CASE : Tuple =f"""input_blocks.{3*i + j + 1}.0.""" unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 __SCREAMING_SNAKE_CASE : Optional[Any] =f"""down_blocks.{i}.attentions.{j}.""" __SCREAMING_SNAKE_CASE : List[str] =f"""input_blocks.{3*i + j + 1}.1.""" unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks __SCREAMING_SNAKE_CASE : Union[str, Any] =f"""up_blocks.{i}.resnets.{j}.""" __SCREAMING_SNAKE_CASE : Any =f"""output_blocks.{3*i + j}.0.""" unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 __SCREAMING_SNAKE_CASE : int =f"""up_blocks.{i}.attentions.{j}.""" __SCREAMING_SNAKE_CASE : Optional[int] =f"""output_blocks.{3*i + j}.1.""" unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 __SCREAMING_SNAKE_CASE : Union[str, Any] =f"""down_blocks.{i}.downsamplers.0.conv.""" __SCREAMING_SNAKE_CASE : Union[str, Any] =f"""input_blocks.{3*(i+1)}.0.op.""" unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 __SCREAMING_SNAKE_CASE : int =f"""up_blocks.{i}.upsamplers.0.""" __SCREAMING_SNAKE_CASE : List[Any] =f"""output_blocks.{3*i + 2}.{1 if i == 0 else 2}.""" unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) __SCREAMING_SNAKE_CASE : int ='mid_block.attentions.0.' __SCREAMING_SNAKE_CASE : List[Any] ='middle_block.1.' unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): __SCREAMING_SNAKE_CASE : Tuple =f"""mid_block.resnets.{j}.""" __SCREAMING_SNAKE_CASE : Tuple =f"""middle_block.{2*j}.""" unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def _SCREAMING_SNAKE_CASE ( lowerCamelCase__ : Optional[Any] ): '''simple docstring''' A: Optional[Any] = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: A: int = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: A: int = v.replace(snake_case_ , snake_case_ ) A: List[str] = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: A: Optional[Any] = v.replace(snake_case_ , snake_case_ ) A: int = v A: Optional[Any] = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# __SCREAMING_SNAKE_CASE : int =[ # (stable-diffusion, HF Diffusers) ('nin_shortcut', 'conv_shortcut'), ('norm_out', 'conv_norm_out'), ('mid.attn_1.', 'mid_block.attentions.0.'), ] for i in range(4): # down_blocks have two resnets for j in range(2): __SCREAMING_SNAKE_CASE : Tuple =f"""encoder.down_blocks.{i}.resnets.{j}.""" __SCREAMING_SNAKE_CASE : int =f"""encoder.down.{i}.block.{j}.""" vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: __SCREAMING_SNAKE_CASE : int =f"""down_blocks.{i}.downsamplers.0.""" __SCREAMING_SNAKE_CASE : str =f"""down.{i}.downsample.""" vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) __SCREAMING_SNAKE_CASE : int =f"""up_blocks.{i}.upsamplers.0.""" __SCREAMING_SNAKE_CASE : List[str] =f"""up.{3-i}.upsample.""" vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): __SCREAMING_SNAKE_CASE : List[str] =f"""decoder.up_blocks.{i}.resnets.{j}.""" __SCREAMING_SNAKE_CASE : Dict =f"""decoder.up.{3-i}.block.{j}.""" vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): __SCREAMING_SNAKE_CASE : Any =f"""mid_block.resnets.{i}.""" __SCREAMING_SNAKE_CASE : Tuple =f"""mid.block_{i+1}.""" vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) __SCREAMING_SNAKE_CASE : int =[ # (stable-diffusion, HF Diffusers) ('norm.', 'group_norm.'), ('q.', 'query.'), ('k.', 'key.'), ('v.', 'value.'), ('proj_out.', 'proj_attn.'), ] def _SCREAMING_SNAKE_CASE ( lowerCamelCase__ : Tuple ): '''simple docstring''' return w.reshape(*w.shape , 1 , 1 ) def _SCREAMING_SNAKE_CASE ( lowerCamelCase__ : Optional[Any] ): '''simple docstring''' A: str = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: A: int = v.replace(snake_case_ , snake_case_ ) A: Union[str, Any] = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: A: List[Any] = v.replace(snake_case_ , snake_case_ ) A: Any = v A: Dict = {v: vae_state_dict[k] for k, v in mapping.items()} A: List[str] = ["""q""", """k""", """v""", """proj_out"""] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if f'mid.attn_1.{weight_name}.weight' in k: print(f'Reshaping {k} for SD format' ) A: Optional[Any] = reshape_weight_for_sd(snake_case_ ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# __SCREAMING_SNAKE_CASE : List[Any] =[ # (stable-diffusion, HF Diffusers) ('resblocks.', 'text_model.encoder.layers.'), ('ln_1', 'layer_norm1'), ('ln_2', 'layer_norm2'), ('.c_fc.', '.fc1.'), ('.c_proj.', '.fc2.'), ('.attn', '.self_attn'), ('ln_final.', 'transformer.text_model.final_layer_norm.'), ('token_embedding.weight', 'transformer.text_model.embeddings.token_embedding.weight'), ('positional_embedding', 'transformer.text_model.embeddings.position_embedding.weight'), ] __SCREAMING_SNAKE_CASE : Dict ={re.escape(x[1]): x[0] for x in textenc_conversion_lst} __SCREAMING_SNAKE_CASE : str =re.compile('|'.join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp __SCREAMING_SNAKE_CASE : List[Any] ={'q': 0, 'k': 1, 'v': 2} def _SCREAMING_SNAKE_CASE ( lowerCamelCase__ : Union[str, Any] ): '''simple docstring''' A: Optional[Any] = {} A: int = {} A: Optional[int] = {} for k, v in text_enc_dict.items(): if ( k.endswith(""".self_attn.q_proj.weight""" ) or k.endswith(""".self_attn.k_proj.weight""" ) or k.endswith(""".self_attn.v_proj.weight""" ) ): A: Dict = k[: -len(""".q_proj.weight""" )] A: Optional[Any] = k[-len("""q_proj.weight""" )] if k_pre not in capture_qkv_weight: A: Optional[int] = [None, None, None] A: Optional[int] = v continue if ( k.endswith(""".self_attn.q_proj.bias""" ) or k.endswith(""".self_attn.k_proj.bias""" ) or k.endswith(""".self_attn.v_proj.bias""" ) ): A: Any = k[: -len(""".q_proj.bias""" )] A: str = k[-len("""q_proj.bias""" )] if k_pre not in capture_qkv_bias: A: List[str] = [None, None, None] A: Optional[Any] = v continue A: int = textenc_pattern.sub(lambda lowerCamelCase__ : protected[re.escape(m.group(0 ) )] , snake_case_ ) A: Any = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("""CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing""" ) A: Union[str, Any] = textenc_pattern.sub(lambda lowerCamelCase__ : protected[re.escape(m.group(0 ) )] , snake_case_ ) A: Tuple = torch.cat(snake_case_ ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("""CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing""" ) A: Optional[Any] = textenc_pattern.sub(lambda lowerCamelCase__ : protected[re.escape(m.group(0 ) )] , snake_case_ ) A: Optional[int] = torch.cat(snake_case_ ) return new_state_dict def _SCREAMING_SNAKE_CASE ( lowerCamelCase__ : List[Any] ): '''simple docstring''' return text_enc_dict if __name__ == "__main__": __SCREAMING_SNAKE_CASE : str =argparse.ArgumentParser() parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.') parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--use_safetensors', action='store_true', help='Save weights use safetensors, default is ckpt.' ) __SCREAMING_SNAKE_CASE : Dict =parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors __SCREAMING_SNAKE_CASE : Any =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.safetensors') __SCREAMING_SNAKE_CASE : Dict =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.safetensors') __SCREAMING_SNAKE_CASE : Union[str, Any] =osp.join(args.model_path, 'text_encoder', 'model.safetensors') # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): __SCREAMING_SNAKE_CASE : Union[str, Any] =load_file(unet_path, device='cpu') else: __SCREAMING_SNAKE_CASE : int =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.bin') __SCREAMING_SNAKE_CASE : Dict =torch.load(unet_path, map_location='cpu') if osp.exists(vae_path): __SCREAMING_SNAKE_CASE : Tuple =load_file(vae_path, device='cpu') else: __SCREAMING_SNAKE_CASE : List[Any] =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.bin') __SCREAMING_SNAKE_CASE : str =torch.load(vae_path, map_location='cpu') if osp.exists(text_enc_path): __SCREAMING_SNAKE_CASE : Tuple =load_file(text_enc_path, device='cpu') else: __SCREAMING_SNAKE_CASE : List[Any] =osp.join(args.model_path, 'text_encoder', 'pytorch_model.bin') __SCREAMING_SNAKE_CASE : Any =torch.load(text_enc_path, map_location='cpu') # Convert the UNet model __SCREAMING_SNAKE_CASE : List[Any] =convert_unet_state_dict(unet_state_dict) __SCREAMING_SNAKE_CASE : Any ={'model.diffusion_model.' + k: v for k, v in unet_state_dict.items()} # Convert the VAE model __SCREAMING_SNAKE_CASE : List[Any] =convert_vae_state_dict(vae_state_dict) __SCREAMING_SNAKE_CASE : Dict ={'first_stage_model.' + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper __SCREAMING_SNAKE_CASE : Dict ='text_model.encoder.layers.22.layer_norm2.bias' in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm __SCREAMING_SNAKE_CASE : Any ={'transformer.' + k: v for k, v in text_enc_dict.items()} __SCREAMING_SNAKE_CASE : str =convert_text_enc_state_dict_vaa(text_enc_dict) __SCREAMING_SNAKE_CASE : int ={'cond_stage_model.model.' + k: v for k, v in text_enc_dict.items()} else: __SCREAMING_SNAKE_CASE : str =convert_text_enc_state_dict(text_enc_dict) __SCREAMING_SNAKE_CASE : Optional[int] ={'cond_stage_model.transformer.' + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint __SCREAMING_SNAKE_CASE : List[str] ={**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: __SCREAMING_SNAKE_CASE : List[str] ={k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: __SCREAMING_SNAKE_CASE : str ={'state_dict': state_dict} torch.save(state_dict, args.checkpoint_path)
135
'''simple docstring''' import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..utils.py_utils import no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: from .features import FeatureType SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_: Tuple =False, False, False @dataclass class __A : a__ : Optional[int] = None a__ : bool = True a__ : bool = True a__ : Optional[str] = None # Automatically constructed a__ : ClassVar[str] = "dict" a__ : ClassVar[Any] = pa.struct({"""bytes""": pa.binary(), """path""": pa.string()} ) a__ : str = field(default="""Audio""" , init=UpperCamelCase__ , repr=UpperCamelCase__ ) def __call__(self : Optional[Any] ): return self.pa_type def _lowercase (self : str , __a : Union[str, bytes, dict] ): try: import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files. except ImportError as err: raise ImportError("To support encoding audio data, please install 'soundfile'." ) from err if isinstance(__a , __a ): return {"bytes": None, "path": value} elif isinstance(__a , __a ): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes UpperCAmelCase_ = BytesIO() sf.write(__a , value["array"] , value["sampling_rate"] , format="wav" ) return {"bytes": buffer.getvalue(), "path": None} elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally if value["path"].endswith("pcm" ): # "PCM" only has raw audio bytes if value.get("sampling_rate" ) is None: # At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate raise KeyError("To use PCM files, please specify a 'sampling_rate' in Audio object" ) if value.get("bytes" ): # If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!) UpperCAmelCase_ = np.frombuffer(value["bytes"] , dtype=np.intaa ).astype(np.floataa ) / 32767 else: UpperCAmelCase_ = np.memmap(value["path"] , dtype="h" , mode="r" ).astype(np.floataa ) / 32767 UpperCAmelCase_ = BytesIO(bytes() ) sf.write(__a , __a , value["sampling_rate"] , format="wav" ) return {"bytes": buffer.getvalue(), "path": None} else: return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the audio bytes, and path is used to infer the audio format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( f"""An audio sample should have one of 'path' or 'bytes' but they are missing or None in {value}.""" ) def _lowercase (self : Dict , __a : dict , __a : Optional[Dict[str, Union[str, bool, None]]] = None ): if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Audio(decode=True) instead." ) UpperCAmelCase_ , UpperCAmelCase_ = (value["path"], BytesIO(value["bytes"] )) if value["bytes"] is not None else (value["path"], None) if path is None and file is None: raise ValueError(f"""An audio sample should have one of 'path' or 'bytes' but both are None in {value}.""" ) try: import librosa import soundfile as sf except ImportError as err: raise ImportError("To support decoding audio files, please install 'librosa' and 'soundfile'." ) from err UpperCAmelCase_ = xsplitext(__a )[1][1:].lower() if path is not None else None if not config.IS_OPUS_SUPPORTED and audio_format == "opus": raise RuntimeError( "Decoding 'opus' files requires system library 'libsndfile'>=1.0.31, " "You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. " ) elif not config.IS_MP3_SUPPORTED and audio_format == "mp3": raise RuntimeError( "Decoding 'mp3' files requires system library 'libsndfile'>=1.1.0, " "You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. " ) if file is None: UpperCAmelCase_ = token_per_repo_id or {} UpperCAmelCase_ = path.split("::" )[-1] try: UpperCAmelCase_ = string_to_dict(__a , config.HUB_DATASETS_URL )["repo_id"] UpperCAmelCase_ = token_per_repo_id[repo_id] except (ValueError, KeyError): UpperCAmelCase_ = None with xopen(__a , "rb" , use_auth_token=__a ) as f: UpperCAmelCase_ , UpperCAmelCase_ = sf.read(__a ) else: UpperCAmelCase_ , UpperCAmelCase_ = sf.read(__a ) UpperCAmelCase_ = array.T if self.mono: UpperCAmelCase_ = librosa.to_mono(__a ) if self.sampling_rate and self.sampling_rate != sampling_rate: UpperCAmelCase_ = librosa.resample(__a , orig_sr=__a , target_sr=self.sampling_rate ) UpperCAmelCase_ = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def _lowercase (self : Dict ): from .features import Value if self.decode: raise ValueError("Cannot flatten a decoded Audio feature." ) return { "bytes": Value("binary" ), "path": Value("string" ), } def _lowercase (self : Optional[Any] , __a : Union[pa.StringArray, pa.StructArray] ): if pa.types.is_string(storage.type ): UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.binary() ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.string() ) UpperCAmelCase_ = pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ) and storage.type.get_all_field_indices("array" ): UpperCAmelCase_ = pa.array([Audio().encode_example(__a ) if x is not None else None for x in storage.to_pylist()] ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: UpperCAmelCase_ = storage.field("bytes" ) else: UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: UpperCAmelCase_ = storage.field("path" ) else: UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.string() ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) return array_cast(__a , self.pa_type ) def _lowercase (self : Dict , __a : pa.StructArray ): @no_op_if_value_is_null def path_to_bytes(__a : Tuple ): with xopen(__a , "rb" ) as f: UpperCAmelCase_ = f.read() return bytes_ UpperCAmelCase_ = pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) UpperCAmelCase_ = pa.array( [os.path.basename(__a ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(__a , self.pa_type )
78
0
def _lowerCAmelCase ( UpperCamelCase__: list ) -> list: """simple docstring""" A = len(snake_case_ ) for _ in range(snake_case_ ): for i in range(_ % 2 , arr_size - 1 , 2 ): if arr[i + 1] < arr[i]: A , A = arr[i + 1], arr[i] return arr if __name__ == "__main__": _lowercase : Optional[int] = list(range(10, 0, -1)) print(f'''Original: {arr}. Sorted: {odd_even_transposition(arr)}''')
641
'''simple docstring''' import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def lowerCAmelCase_ ( snake_case_ : Any , snake_case_ : Optional[int] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg" UpperCAmelCase_ = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ).convert("RGB" ) UpperCAmelCase_ = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.4814_5466, 0.457_8275, 0.4082_1073) , (0.2686_2954, 0.2613_0258, 0.2757_7711) ), ] ) UpperCAmelCase_ = transform(snake_case_ ).unsqueeze(0 ).to(snake_case_ ) return image def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' if "visual_encoder" in key: UpperCAmelCase_ = re.sub("visual_encoder*" , "vision_model.encoder" , snake_case_ ) if "blocks" in key: UpperCAmelCase_ = re.sub(R"blocks" , "layers" , snake_case_ ) if "attn" in key: UpperCAmelCase_ = re.sub(R"attn" , "self_attn" , snake_case_ ) if "norm1" in key: UpperCAmelCase_ = re.sub(R"norm1" , "layer_norm1" , snake_case_ ) if "norm2" in key: UpperCAmelCase_ = re.sub(R"norm2" , "layer_norm2" , snake_case_ ) if "encoder.norm" in key: UpperCAmelCase_ = re.sub(R"encoder.norm" , "post_layernorm" , snake_case_ ) if "encoder.patch_embed.proj" in key: UpperCAmelCase_ = re.sub(R"encoder.patch_embed.proj" , "embeddings.patch_embedding" , snake_case_ ) if "encoder.pos_embed" in key: UpperCAmelCase_ = re.sub(R"encoder.pos_embed" , "embeddings.position_embedding" , snake_case_ ) if "encoder.cls_token" in key: UpperCAmelCase_ = re.sub(R"encoder.cls_token" , "embeddings.class_embedding" , snake_case_ ) if "self_attn" in key: UpperCAmelCase_ = re.sub(R"self_attn.proj" , "self_attn.projection" , snake_case_ ) return key @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : Any=None ) -> Union[str, Any]: '''simple docstring''' if config_path is not None: UpperCAmelCase_ = BlipConfig.from_pretrained(snake_case_ ) else: UpperCAmelCase_ = BlipConfig(projection_dim=5_12 , text_config={} , vision_config={} ) UpperCAmelCase_ = BlipForConditionalGeneration(snake_case_ ).eval() UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth" UpperCAmelCase_ = blip_decoder(pretrained=snake_case_ , image_size=3_84 , vit="base" ) UpperCAmelCase_ = pt_model.eval() UpperCAmelCase_ = pt_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value hf_model.load_state_dict(snake_case_ ) UpperCAmelCase_ = 3_84 UpperCAmelCase_ = load_demo_image(image_size=snake_case_ , device="cpu" ) UpperCAmelCase_ = BertTokenizer.from_pretrained("bert-base-uncased" ) UpperCAmelCase_ = tokenizer(["a picture of"] ).input_ids UpperCAmelCase_ = hf_model.generate(snake_case_ , snake_case_ ) assert out[0].tolist() == [3_05_22, 10_37, 38_61, 19_97, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] UpperCAmelCase_ = hf_model.generate(snake_case_ ) assert out[0].tolist() == [3_05_22, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(snake_case_ ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' UpperCAmelCase_ = ( "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth" ) UpperCAmelCase_ = blip_vqa(pretrained=snake_case_ , image_size=snake_case_ , vit="base" ) vqa_model.eval() UpperCAmelCase_ = vqa_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value UpperCAmelCase_ = BlipForQuestionAnswering(snake_case_ ) hf_vqa_model.load_state_dict(snake_case_ ) UpperCAmelCase_ = ["How many dogs are in this image?"] UpperCAmelCase_ = tokenizer(snake_case_ , return_tensors="pt" ).input_ids UpperCAmelCase_ = hf_vqa_model.generate(snake_case_ , snake_case_ ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + "_vqa" ) UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth" UpperCAmelCase_ = blip_itm(pretrained=snake_case_ , image_size=snake_case_ , vit="base" ) itm_model.eval() UpperCAmelCase_ = itm_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value UpperCAmelCase_ = BlipForImageTextRetrieval(snake_case_ ) UpperCAmelCase_ = ["A picture of a woman with a dog sitting in a beach"] UpperCAmelCase_ = tokenizer( snake_case_ , return_tensors="pt" , padding="max_length" , truncation=snake_case_ , max_length=35 , ).input_ids hf_itm_model.load_state_dict(snake_case_ ) hf_itm_model.eval() UpperCAmelCase_ = hf_itm_model(snake_case_ , snake_case_ , use_itm_head=snake_case_ ) UpperCAmelCase_ = hf_itm_model(snake_case_ , snake_case_ , use_itm_head=snake_case_ ) assert out[0].item() == 0.2110_6874_9427_7954 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.4_5698_8453_8650_5127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + "_itm" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Optional[Any] =argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') SCREAMING_SNAKE_CASE_: int =parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
78
0
"""simple docstring""" from __future__ import annotations __magic_name__ = [True] * 1_00_00_01 __magic_name__ = 2 while i * i <= 1_00_00_00: if seive[i]: for j in range(i * i, 1_00_00_01, i): __magic_name__ = False i += 1 def _A ( __lowercase ): """simple docstring""" return seive[n] def _A ( __lowercase ): """simple docstring""" return any(digit in """02468""" for digit in str(snake_case_ ) ) def _A ( __lowercase = 100_0000 ): """simple docstring""" lowerCamelCase__ = [2] # result already includes the number 2. for num in range(3 , limit + 1 , 2 ): if is_prime(snake_case_ ) and not contains_an_even_digit(snake_case_ ): lowerCamelCase__ = str(snake_case_ ) lowerCamelCase__ = [int(str_num[j:] + str_num[:j] ) for j in range(len(snake_case_ ) )] if all(is_prime(snake_case_ ) for i in list_nums ): result.append(snake_case_ ) return result def _A ( ): """simple docstring""" return len(find_circular_primes() ) if __name__ == "__main__": print(F'{len(find_circular_primes()) = }')
129
'''simple docstring''' import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowerCAmelCase_ ( snake_case_ : List[Any] , snake_case_ : Union[str, Any]=0.999 , snake_case_ : Tuple="cosine" , ) -> Optional[Any]: '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(snake_case_ : Optional[int] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(snake_case_ : Optional[Any] ): return math.exp(t * -12.0 ) else: raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) UpperCAmelCase_ = [] for i in range(snake_case_ ): UpperCAmelCase_ = i / num_diffusion_timesteps UpperCAmelCase_ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(snake_case_ ) / alpha_bar_fn(snake_case_ ) , snake_case_ ) ) return torch.tensor(snake_case_ , dtype=torch.floataa ) class __A ( UpperCamelCase__ , UpperCamelCase__ ): a__ : Tuple = [e.name for e in KarrasDiffusionSchedulers] a__ : Optional[Any] = 2 @register_to_config def __init__(self : Union[str, Any] , __a : int = 1000 , __a : float = 0.0_00_85 , __a : float = 0.0_12 , __a : str = "linear" , __a : Optional[Union[np.ndarray, List[float]]] = None , __a : str = "epsilon" , __a : Optional[bool] = False , __a : Optional[bool] = False , __a : float = 1.0 , __a : str = "linspace" , __a : int = 0 , ): if trained_betas is not None: UpperCAmelCase_ = torch.tensor(__a , dtype=torch.floataa ) elif beta_schedule == "linear": UpperCAmelCase_ = torch.linspace(__a , __a , __a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. UpperCAmelCase_ = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , __a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule UpperCAmelCase_ = betas_for_alpha_bar(__a , alpha_transform_type="cosine" ) elif beta_schedule == "exp": UpperCAmelCase_ = betas_for_alpha_bar(__a , alpha_transform_type="exp" ) else: raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}""" ) UpperCAmelCase_ = 1.0 - self.betas UpperCAmelCase_ = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(__a , __a , __a ) UpperCAmelCase_ = use_karras_sigmas def _lowercase (self : Optional[Any] , __a : Union[str, Any] , __a : Tuple=None ): if schedule_timesteps is None: UpperCAmelCase_ = self.timesteps UpperCAmelCase_ = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: UpperCAmelCase_ = 1 if len(__a ) > 1 else 0 else: UpperCAmelCase_ = timestep.cpu().item() if torch.is_tensor(__a ) else timestep UpperCAmelCase_ = self._index_counter[timestep_int] return indices[pos].item() @property def _lowercase (self : List[Any] ): # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _lowercase (self : Optional[Any] , __a : torch.FloatTensor , __a : Union[float, torch.FloatTensor] , ): UpperCAmelCase_ = self.index_for_timestep(__a ) UpperCAmelCase_ = self.sigmas[step_index] UpperCAmelCase_ = sample / ((sigma**2 + 1) ** 0.5) return sample def _lowercase (self : Any , __a : int , __a : Union[str, torch.device] = None , __a : Optional[int] = None , ): UpperCAmelCase_ = num_inference_steps UpperCAmelCase_ = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": UpperCAmelCase_ = np.linspace(0 , num_train_timesteps - 1 , __a , dtype=__a )[::-1].copy() elif self.config.timestep_spacing == "leading": UpperCAmelCase_ = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 UpperCAmelCase_ = (np.arange(0 , __a ) * step_ratio).round()[::-1].copy().astype(__a ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": UpperCAmelCase_ = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 UpperCAmelCase_ = (np.arange(__a , 0 , -step_ratio )).round().copy().astype(__a ) timesteps -= 1 else: raise ValueError( f"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.""" ) UpperCAmelCase_ = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) UpperCAmelCase_ = np.log(__a ) UpperCAmelCase_ = np.interp(__a , np.arange(0 , len(__a ) ) , __a ) if self.config.use_karras_sigmas: UpperCAmelCase_ = self._convert_to_karras(in_sigmas=__a , num_inference_steps=self.num_inference_steps ) UpperCAmelCase_ = np.array([self._sigma_to_t(__a , __a ) for sigma in sigmas] ) UpperCAmelCase_ = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) UpperCAmelCase_ = torch.from_numpy(__a ).to(device=__a ) UpperCAmelCase_ = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) UpperCAmelCase_ = torch.from_numpy(__a ) UpperCAmelCase_ = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(__a ).startswith("mps" ): # mps does not support float64 UpperCAmelCase_ = timesteps.to(__a , dtype=torch.floataa ) else: UpperCAmelCase_ = timesteps.to(device=__a ) # empty dt and derivative UpperCAmelCase_ = None UpperCAmelCase_ = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter UpperCAmelCase_ = defaultdict(__a ) def _lowercase (self : int , __a : Optional[Any] , __a : List[str] ): # get log sigma UpperCAmelCase_ = np.log(__a ) # get distribution UpperCAmelCase_ = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range UpperCAmelCase_ = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) UpperCAmelCase_ = low_idx + 1 UpperCAmelCase_ = log_sigmas[low_idx] UpperCAmelCase_ = log_sigmas[high_idx] # interpolate sigmas UpperCAmelCase_ = (low - log_sigma) / (low - high) UpperCAmelCase_ = np.clip(__a , 0 , 1 ) # transform interpolation to time range UpperCAmelCase_ = (1 - w) * low_idx + w * high_idx UpperCAmelCase_ = t.reshape(sigma.shape ) return t def _lowercase (self : Dict , __a : torch.FloatTensor , __a : Optional[int] ): UpperCAmelCase_ = in_sigmas[-1].item() UpperCAmelCase_ = in_sigmas[0].item() UpperCAmelCase_ = 7.0 # 7.0 is the value used in the paper UpperCAmelCase_ = np.linspace(0 , 1 , __a ) UpperCAmelCase_ = sigma_min ** (1 / rho) UpperCAmelCase_ = sigma_max ** (1 / rho) UpperCAmelCase_ = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _lowercase (self : List[str] ): return self.dt is None def _lowercase (self : List[Any] , __a : Union[torch.FloatTensor, np.ndarray] , __a : Union[float, torch.FloatTensor] , __a : Union[torch.FloatTensor, np.ndarray] , __a : bool = True , ): UpperCAmelCase_ = self.index_for_timestep(__a ) # advance index counter by 1 UpperCAmelCase_ = timestep.cpu().item() if torch.is_tensor(__a ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: UpperCAmelCase_ = self.sigmas[step_index] UpperCAmelCase_ = self.sigmas[step_index + 1] else: # 2nd order / Heun's method UpperCAmelCase_ = self.sigmas[step_index - 1] UpperCAmelCase_ = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API UpperCAmelCase_ = 0 UpperCAmelCase_ = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": UpperCAmelCase_ = sigma_hat if self.state_in_first_order else sigma_next UpperCAmelCase_ = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": UpperCAmelCase_ = sigma_hat if self.state_in_first_order else sigma_next UpperCAmelCase_ = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": UpperCAmelCase_ = model_output else: raise ValueError( f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""" ) if self.config.clip_sample: UpperCAmelCase_ = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order UpperCAmelCase_ = (sample - pred_original_sample) / sigma_hat # 3. delta timestep UpperCAmelCase_ = sigma_next - sigma_hat # store for 2nd order step UpperCAmelCase_ = derivative UpperCAmelCase_ = dt UpperCAmelCase_ = sample else: # 2. 2nd order / Heun's method UpperCAmelCase_ = (sample - pred_original_sample) / sigma_next UpperCAmelCase_ = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample UpperCAmelCase_ = self.dt UpperCAmelCase_ = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=__a ) def _lowercase (self : Any , __a : torch.FloatTensor , __a : torch.FloatTensor , __a : torch.FloatTensor , ): # Make sure sigmas and timesteps have the same device and dtype as original_samples UpperCAmelCase_ = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(__a ): # mps does not support float64 UpperCAmelCase_ = self.timesteps.to(original_samples.device , dtype=torch.floataa ) UpperCAmelCase_ = timesteps.to(original_samples.device , dtype=torch.floataa ) else: UpperCAmelCase_ = self.timesteps.to(original_samples.device ) UpperCAmelCase_ = timesteps.to(original_samples.device ) UpperCAmelCase_ = [self.index_for_timestep(__a , __a ) for t in timesteps] UpperCAmelCase_ = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): UpperCAmelCase_ = sigma.unsqueeze(-1 ) UpperCAmelCase_ = original_samples + noise * sigma return noisy_samples def __len__(self : str ): return self.config.num_train_timesteps
78
0
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( ImageTextPipelineOutput, UniDiffuserPipeline, ) else: from .modeling_text_decoder import UniDiffuserTextDecoder from .modeling_uvit import UniDiffuserModel, UTransformeraDModel from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
346
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __A ( UpperCamelCase__ ): a__ : List[str] = """Salesforce/blip-image-captioning-base""" a__ : Optional[Any] = ( """This is a tool that generates a description of an image. It takes an input named `image` which should be the """ """image to caption, and returns a text that contains the description in English.""" ) a__ : str = """image_captioner""" a__ : List[str] = AutoModelForVisionaSeq a__ : int = ["""image"""] a__ : Optional[Any] = ["""text"""] def __init__(self : Any , *__a : Dict , **__a : Union[str, Any] ): requires_backends(self , ["vision"] ) super().__init__(*__a , **__a ) def _lowercase (self : Union[str, Any] , __a : "Image" ): return self.pre_processor(images=__a , return_tensors="pt" ) def _lowercase (self : List[str] , __a : Dict ): return self.model.generate(**__a ) def _lowercase (self : int , __a : Optional[Any] ): return self.pre_processor.batch_decode(__a , skip_special_tokens=__a )[0].strip()
78
0
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 __magic_name__ : List[Any] = object() # For specifying empty leaf dict `{}` __magic_name__ : List[Any] = object() def lowercase__ ( _UpperCamelCase , _UpperCamelCase) -> Tuple: """simple docstring""" UpperCamelCase = tuple((re.compile(x + '$') for x in qs)) for i in range(len(snake_case_) - len(snake_case_) + 1): UpperCamelCase = [x.match(snake_case_) for x, y in zip(snake_case_ , ks[i:])] if matches and all(snake_case_): return True return False def lowercase__ ( _UpperCamelCase) -> Tuple: """simple docstring""" def replace(_UpperCamelCase , _UpperCamelCase): for rule, replacement in rules: if _match(snake_case_ , snake_case_): return replacement return val return replace def lowercase__ ( ) -> Any: """simple docstring""" return [ # embeddings (("transformer", "wpe", "embedding"), P('mp' , snake_case_)), (("transformer", "wte", "embedding"), P('mp' , snake_case_)), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(snake_case_ , 'mp')), (("attention", "out_proj", "kernel"), P('mp' , snake_case_)), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(snake_case_ , 'mp')), (("mlp", "c_fc", "bias"), P('mp')), (("mlp", "c_proj", "kernel"), P('mp' , snake_case_)), (("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 lowercase__ ( _UpperCamelCase) -> Any: """simple docstring""" UpperCamelCase = _get_partition_rules() UpperCamelCase = _replacement_rules(snake_case_) UpperCamelCase = {k: _unmatched for k in flatten_dict(snake_case_)} UpperCamelCase = {k: replace(snake_case_ , snake_case_) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(snake_case_))
280
'''simple docstring''' import logging import math from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union import torch from .tensor_utils import tensor_tree_map, tree_map def lowerCAmelCase_ ( snake_case_ : Union[dict, list, tuple, torch.Tensor] ) -> List[Tuple[int, ...]]: '''simple docstring''' UpperCAmelCase_ = [] if isinstance(snake_case_ , snake_case_ ): for v in tree.values(): shapes.extend(_fetch_dims(snake_case_ ) ) elif isinstance(snake_case_ , (list, tuple) ): for t in tree: shapes.extend(_fetch_dims(snake_case_ ) ) elif isinstance(snake_case_ , torch.Tensor ): shapes.append(tree.shape ) else: raise ValueError("Not supported" ) return shapes @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : Tuple[int, ...] ) -> Tuple[int, ...]: '''simple docstring''' UpperCAmelCase_ = [] for d in reversed(snake_case_ ): idx.append(flat_idx % d ) UpperCAmelCase_ = flat_idx // d return tuple(reversed(snake_case_ ) ) @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : Sequence[int] , snake_case_ : Sequence[int] , snake_case_ : Sequence[int] , snake_case_ : Optional[Sequence[bool]] = None , snake_case_ : Optional[Sequence[bool]] = None , ) -> List[Tuple[slice, ...]]: '''simple docstring''' def reduce_edge_list(snake_case_ : List[bool] ) -> None: UpperCAmelCase_ = True for i in range(len(snake_case_ ) ): UpperCAmelCase_ = -1 * (i + 1) l[reversed_idx] &= tally UpperCAmelCase_ = l[reversed_idx] if start_edges is None: UpperCAmelCase_ = [s == 0 for s in start] reduce_edge_list(snake_case_ ) if end_edges is None: UpperCAmelCase_ = [e == (d - 1) for e, d in zip(snake_case_ , snake_case_ )] reduce_edge_list(snake_case_ ) # Base cases. Either start/end are empty and we're done, or the final, # one-dimensional tensor can be simply sliced if len(snake_case_ ) == 0: return [()] elif len(snake_case_ ) == 1: return [(slice(start[0] , end[0] + 1 ),)] UpperCAmelCase_ = [] UpperCAmelCase_ = [] # Dimensions common to start and end can be selected directly for s, e in zip(snake_case_ , snake_case_ ): if s == e: path_list.append(slice(snake_case_ , s + 1 ) ) else: break UpperCAmelCase_ = tuple(snake_case_ ) UpperCAmelCase_ = len(snake_case_ ) # start == end, and we're done if divergence_idx == len(snake_case_ ): return [path] def upper() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None UpperCAmelCase_ = start[divergence_idx] return tuple( path + (slice(snake_case_ , sdi + 1 ),) + s for s in _get_minimal_slice_set( start[divergence_idx + 1 :] , [d - 1 for d in dims[divergence_idx + 1 :]] , dims[divergence_idx + 1 :] , start_edges=start_edges[divergence_idx + 1 :] , end_edges=[True for _ in end_edges[divergence_idx + 1 :]] , ) ) def lower() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None UpperCAmelCase_ = end[divergence_idx] return tuple( path + (slice(snake_case_ , edi + 1 ),) + s for s in _get_minimal_slice_set( [0 for _ in start[divergence_idx + 1 :]] , end[divergence_idx + 1 :] , dims[divergence_idx + 1 :] , start_edges=[True for _ in start_edges[divergence_idx + 1 :]] , end_edges=end_edges[divergence_idx + 1 :] , ) ) # If both start and end are at the edges of the subtree rooted at # divergence_idx, we can just select the whole subtree at once if start_edges[divergence_idx] and end_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] + 1 ),) ) # If just start is at the edge, we can grab almost all of the subtree, # treating only the ragged bottom edge as an edge case elif start_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] ),) ) slices.extend(lower() ) # Analogous to the previous case, but the top is ragged this time elif end_edges[divergence_idx]: slices.extend(upper() ) slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] + 1 ),) ) # If both sides of the range are ragged, we need to handle both sides # separately. If there's contiguous meat in between them, we can index it # in one big chunk else: slices.extend(upper() ) UpperCAmelCase_ = end[divergence_idx] - start[divergence_idx] if middle_ground > 1: slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] ),) ) slices.extend(lower() ) return slices @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : torch.Tensor , snake_case_ : int , snake_case_ : int , snake_case_ : int ) -> torch.Tensor: '''simple docstring''' UpperCAmelCase_ = t.shape[:no_batch_dims] UpperCAmelCase_ = list(_flat_idx_to_idx(snake_case_ , snake_case_ ) ) # _get_minimal_slice_set is inclusive UpperCAmelCase_ = list(_flat_idx_to_idx(flat_end - 1 , snake_case_ ) ) # Get an ordered list of slices to perform UpperCAmelCase_ = _get_minimal_slice_set( snake_case_ , snake_case_ , snake_case_ , ) UpperCAmelCase_ = [t[s] for s in slices] return torch.cat([s.view((-1,) + t.shape[no_batch_dims:] ) for s in sliced_tensors] ) def lowerCAmelCase_ ( snake_case_ : Callable , snake_case_ : Dict[str, Any] , snake_case_ : int , snake_case_ : int , snake_case_ : bool = False , snake_case_ : Any = None , snake_case_ : bool = False , ) -> Any: '''simple docstring''' if not (len(snake_case_ ) > 0): raise ValueError("Must provide at least one input" ) UpperCAmelCase_ = [shape[:no_batch_dims] for shape in _fetch_dims(snake_case_ )] UpperCAmelCase_ = tuple([max(snake_case_ ) for s in zip(*snake_case_ )] ) def _prep_inputs(snake_case_ : torch.Tensor ) -> torch.Tensor: if not low_mem: if not sum(t.shape[:no_batch_dims] ) == no_batch_dims: UpperCAmelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) UpperCAmelCase_ = t.reshape(-1 , *t.shape[no_batch_dims:] ) else: UpperCAmelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) return t UpperCAmelCase_ = tensor_tree_map(_prep_inputs , snake_case_ ) UpperCAmelCase_ = None if _out is not None: UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.view([-1] + list(t.shape[no_batch_dims:] ) ) , _out ) UpperCAmelCase_ = 1 for d in orig_batch_dims: flat_batch_dim *= d UpperCAmelCase_ = flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0) def _select_chunk(snake_case_ : torch.Tensor ) -> torch.Tensor: return t[i : i + chunk_size] if t.shape[0] != 1 else t UpperCAmelCase_ = 0 UpperCAmelCase_ = prepped_outputs for _ in range(snake_case_ ): # Chunk the input if not low_mem: UpperCAmelCase_ = _select_chunk else: UpperCAmelCase_ = partial( _chunk_slice , flat_start=snake_case_ , flat_end=min(snake_case_ , i + chunk_size ) , no_batch_dims=len(snake_case_ ) , ) UpperCAmelCase_ = tensor_tree_map(snake_case_ , snake_case_ ) # Run the layer on the chunk UpperCAmelCase_ = layer(**snake_case_ ) # Allocate space for the output if out is None: UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.new_zeros((flat_batch_dim,) + t.shape[1:] ) , snake_case_ ) # Put the chunk in its pre-allocated space if isinstance(snake_case_ , snake_case_ ): def assign(snake_case_ : dict , snake_case_ : dict ) -> None: for k, v in da.items(): if isinstance(snake_case_ , snake_case_ ): assign(snake_case_ , da[k] ) else: if _add_into_out: v[i : i + chunk_size] += da[k] else: UpperCAmelCase_ = da[k] assign(snake_case_ , snake_case_ ) elif isinstance(snake_case_ , snake_case_ ): for xa, xa in zip(snake_case_ , snake_case_ ): if _add_into_out: xa[i : i + chunk_size] += xa else: UpperCAmelCase_ = xa elif isinstance(snake_case_ , torch.Tensor ): if _add_into_out: out[i : i + chunk_size] += output_chunk else: UpperCAmelCase_ = output_chunk else: raise ValueError("Not supported" ) i += chunk_size UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.view(orig_batch_dims + t.shape[1:] ) , snake_case_ ) return out class __A : def __init__(self : Dict , __a : int = 512 , ): UpperCAmelCase_ = max_chunk_size UpperCAmelCase_ = None UpperCAmelCase_ = None def _lowercase (self : List[Any] , __a : Callable , __a : tuple , __a : int ): logging.info("Tuning chunk size..." ) if min_chunk_size >= self.max_chunk_size: return min_chunk_size UpperCAmelCase_ = [2**l for l in range(int(math.log(self.max_chunk_size , 2 ) ) + 1 )] UpperCAmelCase_ = [c for c in candidates if c > min_chunk_size] UpperCAmelCase_ = [min_chunk_size] + candidates candidates[-1] += 4 def test_chunk_size(__a : int ) -> bool: try: with torch.no_grad(): fn(*__a , chunk_size=__a ) return True except RuntimeError: return False UpperCAmelCase_ = 0 UpperCAmelCase_ = len(__a ) - 1 while i > min_viable_chunk_size_index: UpperCAmelCase_ = test_chunk_size(candidates[i] ) if not viable: UpperCAmelCase_ = (min_viable_chunk_size_index + i) // 2 else: UpperCAmelCase_ = i UpperCAmelCase_ = (i + len(__a ) - 1) // 2 return candidates[min_viable_chunk_size_index] def _lowercase (self : int , __a : Iterable , __a : Iterable ): UpperCAmelCase_ = True for aa, aa in zip(__a , __a ): assert type(__a ) == type(__a ) if isinstance(__a , (list, tuple) ): consistent &= self._compare_arg_caches(__a , __a ) elif isinstance(__a , __a ): UpperCAmelCase_ = [v for _, v in sorted(aa.items() , key=lambda __a : x[0] )] UpperCAmelCase_ = [v for _, v in sorted(aa.items() , key=lambda __a : x[0] )] consistent &= self._compare_arg_caches(__a , __a ) else: consistent &= aa == aa return consistent def _lowercase (self : List[str] , __a : Callable , __a : tuple , __a : int , ): UpperCAmelCase_ = True UpperCAmelCase_ = tree_map(lambda __a : a.shape if isinstance(__a , torch.Tensor ) else a , __a , __a ) if self.cached_arg_data is not None: # If args have changed shape/value, we need to re-tune assert len(self.cached_arg_data ) == len(__a ) UpperCAmelCase_ = self._compare_arg_caches(self.cached_arg_data , __a ) else: # Otherwise, we can reuse the precomputed value UpperCAmelCase_ = False if not consistent: UpperCAmelCase_ = self._determine_favorable_chunk_size( __a , __a , __a , ) UpperCAmelCase_ = arg_data assert self.cached_chunk_size is not None return self.cached_chunk_size
78
0
import random import timeit from functools import wraps from typing import Callable, Optional from ..configuration_utils import PretrainedConfig from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING from ..utils import is_pyanvml_available, is_tf_available, logging from .benchmark_utils import ( Benchmark, Memory, MemorySummary, measure_peak_memory_cpu, start_memory_tracing, stop_memory_tracing, ) if is_tf_available(): import tensorflow as tf from tensorflow.python.framework.errors_impl import ResourceExhaustedError from .benchmark_args_tf import TensorFlowBenchmarkArguments if is_pyanvml_available(): import pyanvml.pyanvml as nvml __UpperCamelCase : Optional[int] = logging.get_logger(__name__) def _UpperCAmelCase ( UpperCAmelCase : bool , UpperCAmelCase : bool ): """simple docstring""" def run_func(UpperCAmelCase : Any ): @wraps(snake_case_ ) def run_in_eager_mode(*UpperCAmelCase : Tuple , **UpperCAmelCase : Any ): return func(*snake_case_ , **snake_case_ ) @wraps(snake_case_ ) @tf.function(experimental_compile=snake_case_ ) def run_in_graph_mode(*UpperCAmelCase : Any , **UpperCAmelCase : str ): return func(*snake_case_ , **snake_case_ ) if do_eager_mode is True: if use_xla is not False: raise ValueError( """Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`.""" ) return run_in_eager_mode else: return run_in_graph_mode return run_func def _UpperCAmelCase ( UpperCAmelCase : int , UpperCAmelCase : int , UpperCAmelCase : int ): """simple docstring""" __lowerCamelCase : Optional[Any] = random.Random() __lowerCamelCase : int = [rng.randint(0 , vocab_size - 1 ) for i in range(batch_size * sequence_length )] return tf.constant(snake_case_ , shape=(batch_size, sequence_length) , dtype=tf.intaa ) class _UpperCamelCase ( UpperCamelCase__ ): '''simple docstring''' a_ : TensorFlowBenchmarkArguments a_ : PretrainedConfig a_ : str = "TensorFlow" @property def _snake_case ( self : List[str] ): '''simple docstring''' return tf.__version__ def _snake_case ( self : Optional[Any] , _lowerCamelCase : str , _lowerCamelCase : int , _lowerCamelCase : int ): '''simple docstring''' __lowerCamelCase : Tuple = self.args.strategy if strategy is None: raise ValueError("""A device strategy has to be initialized before using TensorFlow.""" ) __lowerCamelCase : Optional[int] = self._prepare_inference_func(__a , __a , __a ) return self._measure_speed(_inference ) def _snake_case ( self : Optional[Any] , _lowerCamelCase : str , _lowerCamelCase : int , _lowerCamelCase : int ): '''simple docstring''' __lowerCamelCase : Dict = self.args.strategy if strategy is None: raise ValueError("""A device strategy has to be initialized before using TensorFlow.""" ) __lowerCamelCase : int = self._prepare_train_func(__a , __a , __a ) return self._measure_speed(_train ) def _snake_case ( self : Optional[int] , _lowerCamelCase : str , _lowerCamelCase : int , _lowerCamelCase : int ): '''simple docstring''' if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , __a ) __lowerCamelCase : Optional[Any] = self.args.strategy if strategy is None: raise ValueError("""A device strategy has to be initialized before using TensorFlow.""" ) __lowerCamelCase : Optional[int] = self._prepare_inference_func(__a , __a , __a ) return self._measure_memory(_inference ) def _snake_case ( self : Dict , _lowerCamelCase : str , _lowerCamelCase : int , _lowerCamelCase : int ): '''simple docstring''' if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , __a ) __lowerCamelCase : List[Any] = self.args.strategy if strategy is None: raise ValueError("""A device strategy has to be initialized before using TensorFlow.""" ) __lowerCamelCase : Optional[Any] = self._prepare_train_func(__a , __a , __a ) return self._measure_memory(_train ) def _snake_case ( self : Optional[Any] , _lowerCamelCase : str , _lowerCamelCase : int , _lowerCamelCase : int ): '''simple docstring''' __lowerCamelCase : Optional[Any] = self.config_dict[model_name] if self.args.fpaa: raise NotImplementedError("""Mixed precision is currently not supported.""" ) __lowerCamelCase : Optional[Any] = ( hasattr(__a , """architectures""" ) and isinstance(config.architectures , __a ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: __lowerCamelCase : Union[str, Any] = """TF""" + config.architectures[0] # prepend 'TF' for tensorflow model __lowerCamelCase : Optional[Any] = __import__("""transformers""" , fromlist=[model_class] ) __lowerCamelCase : List[Any] = getattr(__a , __a ) __lowerCamelCase : List[str] = model_cls(__a ) except ImportError: raise ImportError( F"""{model_class} does not exist. If you just want to test the pretrained model, you might want to""" """ set `--only_pretrain_model` or `args.only_pretrain_model=True`.""" ) else: __lowerCamelCase : Optional[Any] = TF_MODEL_MAPPING[config.__class__](__a ) # encoder-decoder has vocab size saved differently __lowerCamelCase : Optional[int] = config.vocab_size if hasattr(__a , """vocab_size""" ) else config.encoder.vocab_size __lowerCamelCase : Any = random_input_ids(__a , __a , __a ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_forward(): return model(__a , decoder_input_ids=__a , training=__a ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_forward(): return model(__a , training=__a ) __lowerCamelCase : Optional[Any] = encoder_decoder_forward if config.is_encoder_decoder else encoder_forward return _inference def _snake_case ( self : Dict , _lowerCamelCase : str , _lowerCamelCase : int , _lowerCamelCase : int ): '''simple docstring''' __lowerCamelCase : List[str] = self.config_dict[model_name] if self.args.eager_mode is not False: raise ValueError("""Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.""" ) if self.args.fpaa: raise NotImplementedError("""Mixed precision is currently not supported.""" ) __lowerCamelCase : Optional[Any] = ( hasattr(__a , """architectures""" ) and isinstance(config.architectures , __a ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: __lowerCamelCase : List[str] = """TF""" + config.architectures[0] # prepend 'TF' for tensorflow model __lowerCamelCase : Union[str, Any] = __import__("""transformers""" , fromlist=[model_class] ) __lowerCamelCase : List[Any] = getattr(__a , __a ) __lowerCamelCase : int = model_cls(__a ) except ImportError: raise ImportError( F"""{model_class} does not exist. If you just want to test the pretrained model, you might want to""" """ set `--only_pretrain_model` or `args.only_pretrain_model=True`.""" ) else: __lowerCamelCase : Tuple = TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](__a ) # encoder-decoder has vocab size saved differently __lowerCamelCase : Any = config.vocab_size if hasattr(__a , """vocab_size""" ) else config.encoder.vocab_size __lowerCamelCase : Union[str, Any] = random_input_ids(__a , __a , __a ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_train(): __lowerCamelCase : Optional[Any] = model(__a , decoder_input_ids=__a , labels=__a , training=__a )[0] __lowerCamelCase : str = tf.gradients(__a , model.trainable_variables ) return gradients @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_train(): __lowerCamelCase : str = model(__a , labels=__a , training=__a )[0] __lowerCamelCase : str = tf.gradients(__a , model.trainable_variables ) return gradients __lowerCamelCase : int = encoder_decoder_train if config.is_encoder_decoder else encoder_train return _train def _snake_case ( self : Dict , _lowerCamelCase : str ): '''simple docstring''' with self.args.strategy.scope(): try: if self.args.is_tpu or self.args.use_xla: # run additional 10 times to stabilize compilation for tpu logger.info("""Do inference on TPU. Running model 5 times to stabilize compilation""" ) timeit.repeat(__a , repeat=1 , number=5 ) # as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average __lowerCamelCase : Any = timeit.repeat( __a , repeat=self.args.repeat , number=1_0 , ) return min(__a ) / 10.0 except ResourceExhaustedError as e: self.print_fn(F"""Doesn't fit on GPU. {e}""" ) def _snake_case ( self : Dict , _lowerCamelCase : Callable[[], None] ): '''simple docstring''' logger.info( """Note that TensorFlow allocates more memory than """ """it might need to speed up computation. """ """The memory reported here corresponds to the memory """ """reported by `nvidia-smi`, which can vary depending """ """on total available memory on the GPU that is used.""" ) with self.args.strategy.scope(): try: if self.args.trace_memory_line_by_line: if not self.args.eager_mode: raise ValueError( """`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory""" """ consumption line by line.""" ) __lowerCamelCase : Any = start_memory_tracing("""transformers""" ) if self.args.is_tpu: # tpu raise NotImplementedError( """Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking""" """ with `args.memory=False`""" ) elif self.args.is_gpu: # gpu if not is_pyanvml_available(): logger.warning( """py3nvml not installed, we won't log GPU memory usage. """ """Install py3nvml (pip install py3nvml) to log information about GPU.""" ) __lowerCamelCase : Tuple = """N/A""" else: logger.info( """Measuring total GPU usage on GPU device. Make sure to not have additional processes""" """ running on the same GPU.""" ) # init nvml nvml.nvmlInit() func() __lowerCamelCase : Optional[int] = nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx ) __lowerCamelCase : List[Any] = nvml.nvmlDeviceGetMemoryInfo(__a ) __lowerCamelCase : List[Any] = meminfo.used __lowerCamelCase : Union[str, Any] = Memory(__a ) # shutdown nvml nvml.nvmlShutdown() else: # cpu if self.args.trace_memory_line_by_line: logger.info( """When enabling line by line tracing, the max peak memory for CPU is inaccurate in""" """ TensorFlow.""" ) __lowerCamelCase : List[str] = None else: __lowerCamelCase : List[str] = measure_peak_memory_cpu(__a ) __lowerCamelCase : Tuple = Memory(__a ) if isinstance(__a , __a ) else memory_bytes if self.args.trace_memory_line_by_line: __lowerCamelCase : int = stop_memory_tracing(__a ) if memory is None: __lowerCamelCase : Optional[int] = summary.total else: __lowerCamelCase : Any = None return memory, summary except ResourceExhaustedError as e: self.print_fn(F"""Doesn't fit on GPU. {e}""" ) return "N/A", None
519
'''simple docstring''' import copy import re class __A : a__ : Optional[int] = """hp""" a__ : Optional[Any] = {} a__ : List[Any] = None @classmethod def _lowercase (cls : Optional[int] , __a : str , __a : Tuple ): UpperCAmelCase_ = prefix UpperCAmelCase_ = defaults cls.build_naming_info() @staticmethod def _lowercase (__a : List[Any] , __a : List[str] ): if len(__a ) == 0: return "" UpperCAmelCase_ = None if any(char.isdigit() for char in word ): raise Exception(f"""Parameters should not contain numbers: '{word}' contains a number""" ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(__a ) + 1 ): UpperCAmelCase_ = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: UpperCAmelCase_ = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(__a : Union[str, Any] ): UpperCAmelCase_ = "" while integer != 0: UpperCAmelCase_ = chr(ord("A" ) + integer % 10 ) + s integer //= 10 return s UpperCAmelCase_ = 0 while True: UpperCAmelCase_ = word + "#" + int_to_alphabetic(__a ) if sword in info["reverse_short_word"]: continue else: UpperCAmelCase_ = sword break UpperCAmelCase_ = short_word UpperCAmelCase_ = word return short_word @staticmethod def _lowercase (__a : List[str] , __a : Union[str, Any] ): UpperCAmelCase_ = param_name.split("_" ) UpperCAmelCase_ = [TrialShortNamer.shortname_for_word(__a , __a ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name UpperCAmelCase_ = ["", "_"] for separator in separators: UpperCAmelCase_ = separator.join(__a ) if shortname not in info["reverse_short_param"]: UpperCAmelCase_ = shortname UpperCAmelCase_ = param_name return shortname return param_name @staticmethod def _lowercase (__a : int , __a : Union[str, Any] ): UpperCAmelCase_ = TrialShortNamer.shortname_for_key(__a , __a ) UpperCAmelCase_ = short_name UpperCAmelCase_ = param_name @classmethod def _lowercase (cls : Any ): if cls.NAMING_INFO is not None: return UpperCAmelCase_ = { "short_word": {}, "reverse_short_word": {}, "short_param": {}, "reverse_short_param": {}, } UpperCAmelCase_ = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(__a , __a ) UpperCAmelCase_ = info @classmethod def _lowercase (cls : int , __a : Optional[int] ): cls.build_naming_info() assert cls.PREFIX is not None UpperCAmelCase_ = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(f"""You should provide a default value for the param name {k} with value {v}""" ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue UpperCAmelCase_ = cls.NAMING_INFO["short_param"][k] if isinstance(__a , __a ): UpperCAmelCase_ = 1 if v else 0 UpperCAmelCase_ = "" if isinstance(__a , (int, float) ) else "-" UpperCAmelCase_ = f"""{key}{sep}{v}""" name.append(__a ) return "_".join(__a ) @classmethod def _lowercase (cls : Dict , __a : Dict ): UpperCAmelCase_ = repr[len(cls.PREFIX ) + 1 :] if repr == "": UpperCAmelCase_ = [] else: UpperCAmelCase_ = repr.split("_" ) UpperCAmelCase_ = {} for value in values: if "-" in value: UpperCAmelCase_ , UpperCAmelCase_ = value.split("-" ) else: UpperCAmelCase_ = re.sub("[0-9.]" , "" , __a ) UpperCAmelCase_ = float(re.sub("[^0-9.]" , "" , __a ) ) UpperCAmelCase_ = cls.NAMING_INFO["reverse_short_param"][p_k] UpperCAmelCase_ = p_v for k in cls.DEFAULTS: if k not in parameters: UpperCAmelCase_ = cls.DEFAULTS[k] return parameters
78
0
"""simple docstring""" import os import random import sys from . import cryptomath_module as cryptoMath # noqa: N812 from . import rabin_miller as rabinMiller # noqa: N812 def lowerCAmelCase_( ) -> None: print('''Making key files...''' ) make_key_files('''rsa''' , 10_24 ) print('''Key files generation successful.''' ) def lowerCAmelCase_( lowercase_ : int ) -> tuple[tuple[int, int], tuple[int, int]]: print('''Generating prime p...''' ) _lowerCamelCase = rabinMiller.generate_large_prime(snake_case_ ) print('''Generating prime q...''' ) _lowerCamelCase = rabinMiller.generate_large_prime(snake_case_ ) _lowerCamelCase = p * q print('''Generating e that is relatively prime to (p - 1) * (q - 1)...''' ) while True: _lowerCamelCase = random.randrange(2 ** (key_size - 1) , 2 ** (key_size) ) if cryptoMath.gcd(snake_case_ , (p - 1) * (q - 1) ) == 1: break print('''Calculating d that is mod inverse of e...''' ) _lowerCamelCase = cryptoMath.find_mod_inverse(snake_case_ , (p - 1) * (q - 1) ) _lowerCamelCase = (n, e) _lowerCamelCase = (n, d) return (public_key, private_key) def lowerCAmelCase_( lowercase_ : str , lowercase_ : int ) -> None: if os.path.exists(F"""{name}_pubkey.txt""" ) or os.path.exists(F"""{name}_privkey.txt""" ): print('''\nWARNING:''' ) print( F"""\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \n""" '''Use a different name or delete these files and re-run this program.''' ) sys.exit() _lowerCamelCase , _lowerCamelCase = generate_key(snake_case_ ) print(F"""\nWriting public key to file {name}_pubkey.txt...""" ) with open(F"""{name}_pubkey.txt""" , '''w''' ) as out_file: out_file.write(F"""{key_size},{public_key[0]},{public_key[1]}""" ) print(F"""Writing private key to file {name}_privkey.txt...""" ) with open(F"""{name}_privkey.txt""" , '''w''' ) as out_file: out_file.write(F"""{key_size},{private_key[0]},{private_key[1]}""" ) if __name__ == "__main__": main()
661
'''simple docstring''' from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging SCREAMING_SNAKE_CASE_: int =logging.get_logger(__name__) class __A ( UpperCamelCase__ ): a__ : Tuple = ["""pixel_values"""] def __init__(self : int , __a : bool = True , __a : Union[int, float] = 1 / 255 , __a : bool = True , __a : int = 8 , **__a : int , ): super().__init__(**__a ) UpperCAmelCase_ = do_rescale UpperCAmelCase_ = rescale_factor UpperCAmelCase_ = do_pad UpperCAmelCase_ = pad_size def _lowercase (self : Optional[int] , __a : np.ndarray , __a : float , __a : Optional[Union[str, ChannelDimension]] = None , **__a : Optional[int] ): return rescale(__a , scale=__a , data_format=__a , **__a ) def _lowercase (self : Optional[int] , __a : np.ndarray , __a : int , __a : Optional[Union[str, ChannelDimension]] = None ): UpperCAmelCase_ , UpperCAmelCase_ = get_image_size(__a ) UpperCAmelCase_ = (old_height // size + 1) * size - old_height UpperCAmelCase_ = (old_width // size + 1) * size - old_width return pad(__a , ((0, pad_height), (0, pad_width)) , mode="symmetric" , data_format=__a ) def _lowercase (self : Tuple , __a : ImageInput , __a : Optional[bool] = None , __a : Optional[float] = None , __a : Optional[bool] = None , __a : Optional[int] = None , __a : Optional[Union[str, TensorType]] = None , __a : Union[str, ChannelDimension] = ChannelDimension.FIRST , **__a : List[str] , ): 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_pad if do_pad is not None else self.do_pad UpperCAmelCase_ = pad_size if pad_size is not None else self.pad_size UpperCAmelCase_ = make_list_of_images(__a ) if not valid_images(__a ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) # All transformations expect numpy arrays. UpperCAmelCase_ = [to_numpy_array(__a ) for image in images] if do_rescale: UpperCAmelCase_ = [self.rescale(image=__a , scale=__a ) for image in images] if do_pad: UpperCAmelCase_ = [self.pad(__a , size=__a ) for image in images] UpperCAmelCase_ = [to_channel_dimension_format(__a , __a ) for image in images] UpperCAmelCase_ = {"pixel_values": images} return BatchFeature(data=__a , tensor_type=__a )
78
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) a_ = { 'configuration_funnel': ['FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FunnelConfig'], 'convert_funnel_original_tf_checkpoint_to_pytorch': [], 'tokenization_funnel': ['FunnelTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['FunnelTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST', 'FunnelBaseModel', 'FunnelForMaskedLM', 'FunnelForMultipleChoice', 'FunnelForPreTraining', 'FunnelForQuestionAnswering', 'FunnelForSequenceClassification', 'FunnelForTokenClassification', 'FunnelModel', 'FunnelPreTrainedModel', 'load_tf_weights_in_funnel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFFunnelBaseModel', 'TFFunnelForMaskedLM', 'TFFunnelForMultipleChoice', 'TFFunnelForPreTraining', 'TFFunnelForQuestionAnswering', 'TFFunnelForSequenceClassification', 'TFFunnelForTokenClassification', 'TFFunnelModel', 'TFFunnelPreTrainedModel', ] if TYPE_CHECKING: from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig from .tokenization_funnel import FunnelTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_funnel_fast import FunnelTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_funnel import ( FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, FunnelBaseModel, FunnelForMaskedLM, FunnelForMultipleChoice, FunnelForPreTraining, FunnelForQuestionAnswering, FunnelForSequenceClassification, FunnelForTokenClassification, FunnelModel, FunnelPreTrainedModel, load_tf_weights_in_funnel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_funnel import ( TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, TFFunnelPreTrainedModel, ) else: import sys a_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
221
'''simple docstring''' import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# SCREAMING_SNAKE_CASE_: Dict =[ # (stable-diffusion, HF Diffusers) ('time_embed.0.weight', 'time_embedding.linear_1.weight'), ('time_embed.0.bias', 'time_embedding.linear_1.bias'), ('time_embed.2.weight', 'time_embedding.linear_2.weight'), ('time_embed.2.bias', 'time_embedding.linear_2.bias'), ('input_blocks.0.0.weight', 'conv_in.weight'), ('input_blocks.0.0.bias', 'conv_in.bias'), ('out.0.weight', 'conv_norm_out.weight'), ('out.0.bias', 'conv_norm_out.bias'), ('out.2.weight', 'conv_out.weight'), ('out.2.bias', 'conv_out.bias'), ] SCREAMING_SNAKE_CASE_: List[Any] =[ # (stable-diffusion, HF Diffusers) ('in_layers.0', 'norm1'), ('in_layers.2', 'conv1'), ('out_layers.0', 'norm2'), ('out_layers.3', 'conv2'), ('emb_layers.1', 'time_emb_proj'), ('skip_connection', 'conv_shortcut'), ] SCREAMING_SNAKE_CASE_: Union[str, Any] =[] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks SCREAMING_SNAKE_CASE_: Any =f"down_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Tuple =f"input_blocks.{3*i + j + 1}.0." unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 SCREAMING_SNAKE_CASE_: Optional[Any] =f"down_blocks.{i}.attentions.{j}." SCREAMING_SNAKE_CASE_: List[str] =f"input_blocks.{3*i + j + 1}.1." unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks SCREAMING_SNAKE_CASE_: Union[str, Any] =f"up_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Any =f"output_blocks.{3*i + j}.0." unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.attentions.{j}." SCREAMING_SNAKE_CASE_: Optional[int] =f"output_blocks.{3*i + j}.1." unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 SCREAMING_SNAKE_CASE_: Union[str, Any] =f"down_blocks.{i}.downsamplers.0.conv." SCREAMING_SNAKE_CASE_: Union[str, Any] =f"input_blocks.{3*(i+1)}.0.op." unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.upsamplers.0." SCREAMING_SNAKE_CASE_: List[Any] =f"output_blocks.{3*i + 2}.{1 if i == 0 else 2}." unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) SCREAMING_SNAKE_CASE_: int ='mid_block.attentions.0.' SCREAMING_SNAKE_CASE_: List[Any] ='middle_block.1.' unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): SCREAMING_SNAKE_CASE_: Tuple =f"mid_block.resnets.{j}." SCREAMING_SNAKE_CASE_: Tuple =f"middle_block.{2*j}." unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: UpperCAmelCase_ = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v UpperCAmelCase_ = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# SCREAMING_SNAKE_CASE_: int =[ # (stable-diffusion, HF Diffusers) ('nin_shortcut', 'conv_shortcut'), ('norm_out', 'conv_norm_out'), ('mid.attn_1.', 'mid_block.attentions.0.'), ] for i in range(4): # down_blocks have two resnets for j in range(2): SCREAMING_SNAKE_CASE_: Tuple =f"encoder.down_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: int =f"encoder.down.{i}.block.{j}." vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: SCREAMING_SNAKE_CASE_: int =f"down_blocks.{i}.downsamplers.0." SCREAMING_SNAKE_CASE_: str =f"down.{i}.downsample." vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.upsamplers.0." SCREAMING_SNAKE_CASE_: List[str] =f"up.{3-i}.upsample." vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): SCREAMING_SNAKE_CASE_: List[str] =f"decoder.up_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Dict =f"decoder.up.{3-i}.block.{j}." vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): SCREAMING_SNAKE_CASE_: Any =f"mid_block.resnets.{i}." SCREAMING_SNAKE_CASE_: Tuple =f"mid.block_{i+1}." vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) SCREAMING_SNAKE_CASE_: int =[ # (stable-diffusion, HF Diffusers) ('norm.', 'group_norm.'), ('q.', 'query.'), ('k.', 'key.'), ('v.', 'value.'), ('proj_out.', 'proj_attn.'), ] def lowerCAmelCase_ ( snake_case_ : Tuple ) -> Tuple: '''simple docstring''' return w.reshape(*w.shape , 1 , 1 ) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v UpperCAmelCase_ = {v: vae_state_dict[k] for k, v in mapping.items()} UpperCAmelCase_ = ["q", "k", "v", "proj_out"] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if f"""mid.attn_1.{weight_name}.weight""" in k: print(f"""Reshaping {k} for SD format""" ) UpperCAmelCase_ = reshape_weight_for_sd(snake_case_ ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# SCREAMING_SNAKE_CASE_: List[Any] =[ # (stable-diffusion, HF Diffusers) ('resblocks.', 'text_model.encoder.layers.'), ('ln_1', 'layer_norm1'), ('ln_2', 'layer_norm2'), ('.c_fc.', '.fc1.'), ('.c_proj.', '.fc2.'), ('.attn', '.self_attn'), ('ln_final.', 'transformer.text_model.final_layer_norm.'), ('token_embedding.weight', 'transformer.text_model.embeddings.token_embedding.weight'), ('positional_embedding', 'transformer.text_model.embeddings.position_embedding.weight'), ] SCREAMING_SNAKE_CASE_: Dict ={re.escape(x[1]): x[0] for x in textenc_conversion_lst} SCREAMING_SNAKE_CASE_: str =re.compile('|'.join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp SCREAMING_SNAKE_CASE_: List[Any] ={'q': 0, 'k': 1, 'v': 2} def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = {} UpperCAmelCase_ = {} UpperCAmelCase_ = {} for k, v in text_enc_dict.items(): if ( k.endswith(".self_attn.q_proj.weight" ) or k.endswith(".self_attn.k_proj.weight" ) or k.endswith(".self_attn.v_proj.weight" ) ): UpperCAmelCase_ = k[: -len(".q_proj.weight" )] UpperCAmelCase_ = k[-len("q_proj.weight" )] if k_pre not in capture_qkv_weight: UpperCAmelCase_ = [None, None, None] UpperCAmelCase_ = v continue if ( k.endswith(".self_attn.q_proj.bias" ) or k.endswith(".self_attn.k_proj.bias" ) or k.endswith(".self_attn.v_proj.bias" ) ): UpperCAmelCase_ = k[: -len(".q_proj.bias" )] UpperCAmelCase_ = k[-len("q_proj.bias" )] if k_pre not in capture_qkv_bias: UpperCAmelCase_ = [None, None, None] UpperCAmelCase_ = v continue UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = torch.cat(snake_case_ ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = torch.cat(snake_case_ ) return new_state_dict def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> Union[str, Any]: '''simple docstring''' return text_enc_dict if __name__ == "__main__": SCREAMING_SNAKE_CASE_: str =argparse.ArgumentParser() parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.') parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--use_safetensors', action='store_true', help='Save weights use safetensors, default is ckpt.' ) SCREAMING_SNAKE_CASE_: Dict =parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors SCREAMING_SNAKE_CASE_: Any =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.safetensors') SCREAMING_SNAKE_CASE_: Dict =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.safetensors') SCREAMING_SNAKE_CASE_: Union[str, Any] =osp.join(args.model_path, 'text_encoder', 'model.safetensors') # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): SCREAMING_SNAKE_CASE_: Union[str, Any] =load_file(unet_path, device='cpu') else: SCREAMING_SNAKE_CASE_: int =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.bin') SCREAMING_SNAKE_CASE_: Dict =torch.load(unet_path, map_location='cpu') if osp.exists(vae_path): SCREAMING_SNAKE_CASE_: Tuple =load_file(vae_path, device='cpu') else: SCREAMING_SNAKE_CASE_: List[Any] =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.bin') SCREAMING_SNAKE_CASE_: str =torch.load(vae_path, map_location='cpu') if osp.exists(text_enc_path): SCREAMING_SNAKE_CASE_: Tuple =load_file(text_enc_path, device='cpu') else: SCREAMING_SNAKE_CASE_: List[Any] =osp.join(args.model_path, 'text_encoder', 'pytorch_model.bin') SCREAMING_SNAKE_CASE_: Any =torch.load(text_enc_path, map_location='cpu') # Convert the UNet model SCREAMING_SNAKE_CASE_: List[Any] =convert_unet_state_dict(unet_state_dict) SCREAMING_SNAKE_CASE_: Any ={'model.diffusion_model.' + k: v for k, v in unet_state_dict.items()} # Convert the VAE model SCREAMING_SNAKE_CASE_: List[Any] =convert_vae_state_dict(vae_state_dict) SCREAMING_SNAKE_CASE_: Dict ={'first_stage_model.' + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper SCREAMING_SNAKE_CASE_: Dict ='text_model.encoder.layers.22.layer_norm2.bias' in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm SCREAMING_SNAKE_CASE_: Any ={'transformer.' + k: v for k, v in text_enc_dict.items()} SCREAMING_SNAKE_CASE_: str =convert_text_enc_state_dict_vaa(text_enc_dict) SCREAMING_SNAKE_CASE_: int ={'cond_stage_model.model.' + k: v for k, v in text_enc_dict.items()} else: SCREAMING_SNAKE_CASE_: str =convert_text_enc_state_dict(text_enc_dict) SCREAMING_SNAKE_CASE_: Optional[int] ={'cond_stage_model.transformer.' + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint SCREAMING_SNAKE_CASE_: List[str] ={**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: SCREAMING_SNAKE_CASE_: List[str] ={k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: SCREAMING_SNAKE_CASE_: str ={'state_dict': state_dict} torch.save(state_dict, args.checkpoint_path)
78
0
"""simple docstring""" import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal _A = datasets.utils.logging.get_logger(__name__) _A = ['names', 'prefix'] _A = ['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols'] _A = ['encoding_errors', 'on_bad_lines'] _A = ['date_format'] @dataclass class _lowerCamelCase ( datasets.BuilderConfig ): _lowerCamelCase :str = "," _lowerCamelCase :Optional[str] = None _lowerCamelCase :Optional[Union[int, List[int], str]] = "infer" _lowerCamelCase :Optional[List[str]] = None _lowerCamelCase :Optional[List[str]] = None _lowerCamelCase :Optional[Union[int, str, List[int], List[str]]] = None _lowerCamelCase :Optional[Union[List[int], List[str]]] = None _lowerCamelCase :Optional[str] = None _lowerCamelCase :bool = True _lowerCamelCase :Optional[Literal["c", "python", "pyarrow"]] = None _lowerCamelCase :Dict[Union[int, str], Callable[[Any], Any]] = None _lowerCamelCase :Optional[list] = None _lowerCamelCase :Optional[list] = None _lowerCamelCase :bool = False _lowerCamelCase :Optional[Union[int, List[int]]] = None _lowerCamelCase :Optional[int] = None _lowerCamelCase :Optional[Union[str, List[str]]] = None _lowerCamelCase :bool = True _lowerCamelCase :bool = True _lowerCamelCase :bool = False _lowerCamelCase :bool = True _lowerCamelCase :Optional[str] = None _lowerCamelCase :str = "." _lowerCamelCase :Optional[str] = None _lowerCamelCase :str = '"' _lowerCamelCase :int = 0 _lowerCamelCase :Optional[str] = None _lowerCamelCase :Optional[str] = None _lowerCamelCase :Optional[str] = None _lowerCamelCase :Optional[str] = None _lowerCamelCase :bool = True _lowerCamelCase :bool = True _lowerCamelCase :int = 0 _lowerCamelCase :bool = True _lowerCamelCase :bool = False _lowerCamelCase :Optional[str] = None _lowerCamelCase :int = 10000 _lowerCamelCase :Optional[datasets.Features] = None _lowerCamelCase :Optional[str] = "strict" _lowerCamelCase :Literal["error", "warn", "skip"] = "error" _lowerCamelCase :Optional[str] = None def _lowerCAmelCase ( self : Tuple ) -> Optional[int]: """simple docstring""" if self.delimiter is not None: lowerCAmelCase__ : int = self.delimiter if self.column_names is not None: lowerCAmelCase__ : Union[str, Any] = self.column_names @property def _lowerCAmelCase ( self : Optional[Any] ) -> str: """simple docstring""" lowerCAmelCase__ : Union[str, Any] = { """sep""": self.sep, """header""": self.header, """names""": self.names, """index_col""": self.index_col, """usecols""": self.usecols, """prefix""": self.prefix, """mangle_dupe_cols""": self.mangle_dupe_cols, """engine""": self.engine, """converters""": self.converters, """true_values""": self.true_values, """false_values""": self.false_values, """skipinitialspace""": self.skipinitialspace, """skiprows""": self.skiprows, """nrows""": self.nrows, """na_values""": self.na_values, """keep_default_na""": self.keep_default_na, """na_filter""": self.na_filter, """verbose""": self.verbose, """skip_blank_lines""": self.skip_blank_lines, """thousands""": self.thousands, """decimal""": self.decimal, """lineterminator""": self.lineterminator, """quotechar""": self.quotechar, """quoting""": self.quoting, """escapechar""": self.escapechar, """comment""": self.comment, """encoding""": self.encoding, """dialect""": self.dialect, """error_bad_lines""": self.error_bad_lines, """warn_bad_lines""": self.warn_bad_lines, """skipfooter""": self.skipfooter, """doublequote""": self.doublequote, """memory_map""": self.memory_map, """float_precision""": self.float_precision, """chunksize""": self.chunksize, """encoding_errors""": self.encoding_errors, """on_bad_lines""": self.on_bad_lines, """date_format""": self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , __a ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class _lowerCamelCase ( datasets.ArrowBasedBuilder ): _lowerCamelCase :int = CsvConfig def _lowerCAmelCase ( self : int ) -> Tuple: """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def _lowerCAmelCase ( self : str , UpperCamelCase : Dict ) -> Tuple: """simple docstring""" if not self.config.data_files: raise ValueError(f"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) lowerCAmelCase__ : Dict = dl_manager.download_and_extract(self.config.data_files ) if isinstance(__a , (str, list, tuple) ): lowerCAmelCase__ : Union[str, Any] = data_files if isinstance(__a , __a ): lowerCAmelCase__ : Any = [files] lowerCAmelCase__ : int = [dl_manager.iter_files(__a ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] lowerCAmelCase__ : Optional[Any] = [] for split_name, files in data_files.items(): if isinstance(__a , __a ): lowerCAmelCase__ : Union[str, Any] = [files] lowerCAmelCase__ : Any = [dl_manager.iter_files(__a ) for file in files] splits.append(datasets.SplitGenerator(name=__a , gen_kwargs={"""files""": files} ) ) return splits def _lowerCAmelCase ( self : Tuple , UpperCamelCase : pa.Table ) -> str: """simple docstring""" if self.config.features is not None: lowerCAmelCase__ : Union[str, Any] = self.config.features.arrow_schema if all(not require_storage_cast(__a ) for feature in self.config.features.values() ): # cheaper cast lowerCAmelCase__ : List[Any] = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=__a ) else: # more expensive cast; allows str <-> int/float or str to Audio for example lowerCAmelCase__ : Any = table_cast(__a , __a ) return pa_table def _lowerCAmelCase ( self : Tuple , UpperCamelCase : str ) -> Union[str, Any]: """simple docstring""" lowerCAmelCase__ : Tuple = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str lowerCAmelCase__ : Optional[int] = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(__a ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(__a ) ): lowerCAmelCase__ : Tuple = pd.read_csv(__a , iterator=__a , dtype=__a , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(__a ): lowerCAmelCase__ : str = pa.Table.from_pandas(__a ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(__a ) except ValueError as e: logger.error(f"""Failed to read file '{file}' with error {type(__a )}: {e}""" ) raise
299
'''simple docstring''' import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( snake_case_ : ndarray ) -> float: '''simple docstring''' return np.dot(snake_case_ , snake_case_ ) class __A : def __init__(self : int , *, __a : float = np.inf , __a : str = "linear" , __a : float = 0.0 , ): UpperCAmelCase_ = regularization UpperCAmelCase_ = gamma if kernel == "linear": UpperCAmelCase_ = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("rbf kernel requires gamma" ) if not isinstance(self.gamma , (float, int) ): raise ValueError("gamma must be float or int" ) if not self.gamma > 0: raise ValueError("gamma must be > 0" ) UpperCAmelCase_ = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: UpperCAmelCase_ = f"""Unknown kernel: {kernel}""" raise ValueError(__a ) def _lowercase (self : Optional[int] , __a : ndarray , __a : ndarray ): return np.dot(__a , __a ) def _lowercase (self : Optional[int] , __a : ndarray , __a : ndarray ): return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def _lowercase (self : str , __a : list[ndarray] , __a : ndarray ): UpperCAmelCase_ = observations UpperCAmelCase_ = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((UpperCAmelCase_) , ) = np.shape(__a ) def to_minimize(__a : ndarray ) -> float: UpperCAmelCase_ = 0 ((UpperCAmelCase_) , ) = np.shape(__a ) for i in range(__a ): for j in range(__a ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(__a ) UpperCAmelCase_ = LinearConstraint(__a , 0 , 0 ) UpperCAmelCase_ = Bounds(0 , self.regularization ) UpperCAmelCase_ = minimize( __a , np.ones(__a ) , bounds=__a , constraints=[ly_contraint] ).x UpperCAmelCase_ = l_star # calculating mean offset of separation plane to points UpperCAmelCase_ = 0 for i in range(__a ): for j in range(__a ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) UpperCAmelCase_ = s / n def _lowercase (self : Optional[int] , __a : ndarray ): UpperCAmelCase_ = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , __a ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
78
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE__ : Any = { """configuration_perceiver""": ["""PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PerceiverConfig""", """PerceiverOnnxConfig"""], """tokenization_perceiver""": ["""PerceiverTokenizer"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ["""PerceiverFeatureExtractor"""] SCREAMING_SNAKE_CASE__ : Any = ["""PerceiverImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ """PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST""", """PerceiverForImageClassificationConvProcessing""", """PerceiverForImageClassificationFourier""", """PerceiverForImageClassificationLearned""", """PerceiverForMaskedLM""", """PerceiverForMultimodalAutoencoding""", """PerceiverForOpticalFlow""", """PerceiverForSequenceClassification""", """PerceiverLayer""", """PerceiverModel""", """PerceiverPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig from .tokenization_perceiver import PerceiverTokenizer try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_perceiver import PerceiverFeatureExtractor from .image_processing_perceiver import PerceiverImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_perceiver import ( PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST, PerceiverForImageClassificationConvProcessing, PerceiverForImageClassificationFourier, PerceiverForImageClassificationLearned, PerceiverForMaskedLM, PerceiverForMultimodalAutoencoding, PerceiverForOpticalFlow, PerceiverForSequenceClassification, PerceiverLayer, PerceiverModel, PerceiverPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
79
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_realm import RealmTokenizer SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : int = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} SCREAMING_SNAKE_CASE__ : List[str] = { """vocab_file""": { """google/realm-cc-news-pretrained-embedder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt""" ), """google/realm-cc-news-pretrained-encoder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt""" ), """google/realm-cc-news-pretrained-scorer""": ( """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt""" ), """google/realm-cc-news-pretrained-openqa""": ( """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt""" ), """google/realm-orqa-nq-openqa""": """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt""", """google/realm-orqa-nq-reader""": """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt""", """google/realm-orqa-wq-openqa""": """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt""", """google/realm-orqa-wq-reader""": """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt""", }, """tokenizer_file""": { """google/realm-cc-news-pretrained-embedder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont""" ), """google/realm-cc-news-pretrained-encoder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json""" ), """google/realm-cc-news-pretrained-scorer""": ( """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json""" ), """google/realm-cc-news-pretrained-openqa""": ( """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json""" ), """google/realm-orqa-nq-openqa""": ( """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json""" ), """google/realm-orqa-nq-reader""": ( """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json""" ), """google/realm-orqa-wq-openqa""": ( """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json""" ), """google/realm-orqa-wq-reader""": ( """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json""" ), }, } SCREAMING_SNAKE_CASE__ : Optional[Any] = { """google/realm-cc-news-pretrained-embedder""": 5_12, """google/realm-cc-news-pretrained-encoder""": 5_12, """google/realm-cc-news-pretrained-scorer""": 5_12, """google/realm-cc-news-pretrained-openqa""": 5_12, """google/realm-orqa-nq-openqa""": 5_12, """google/realm-orqa-nq-reader""": 5_12, """google/realm-orqa-wq-openqa""": 5_12, """google/realm-orqa-wq-reader""": 5_12, } SCREAMING_SNAKE_CASE__ : Optional[Any] = { """google/realm-cc-news-pretrained-embedder""": {"""do_lower_case""": True}, """google/realm-cc-news-pretrained-encoder""": {"""do_lower_case""": True}, """google/realm-cc-news-pretrained-scorer""": {"""do_lower_case""": True}, """google/realm-cc-news-pretrained-openqa""": {"""do_lower_case""": True}, """google/realm-orqa-nq-openqa""": {"""do_lower_case""": True}, """google/realm-orqa-nq-reader""": {"""do_lower_case""": True}, """google/realm-orqa-wq-openqa""": {"""do_lower_case""": True}, """google/realm-orqa-wq-reader""": {"""do_lower_case""": True}, } class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = VOCAB_FILES_NAMES __lowerCamelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase = PRETRAINED_INIT_CONFIGURATION __lowerCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase = RealmTokenizer def __init__( self , _lowerCAmelCase=None , _lowerCAmelCase=None , _lowerCAmelCase=True , _lowerCAmelCase="[UNK]" , _lowerCAmelCase="[SEP]" , _lowerCAmelCase="[PAD]" , _lowerCAmelCase="[CLS]" , _lowerCAmelCase="[MASK]" , _lowerCAmelCase=True , _lowerCAmelCase=None , **_lowerCAmelCase , ): super().__init__( _lowerCAmelCase , tokenizer_file=_lowerCAmelCase , do_lower_case=_lowerCAmelCase , unk_token=_lowerCAmelCase , sep_token=_lowerCAmelCase , pad_token=_lowerCAmelCase , cls_token=_lowerCAmelCase , mask_token=_lowerCAmelCase , tokenize_chinese_chars=_lowerCAmelCase , strip_accents=_lowerCAmelCase , **_lowerCAmelCase , ) UpperCAmelCase__ : Tuple = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , _lowerCAmelCase ) != do_lower_case or normalizer_state.get("""strip_accents""" , _lowerCAmelCase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , _lowerCAmelCase ) != tokenize_chinese_chars ): UpperCAmelCase__ : Any = getattr(_lowerCAmelCase , normalizer_state.pop("""type""" ) ) UpperCAmelCase__ : str = do_lower_case UpperCAmelCase__ : Tuple = strip_accents UpperCAmelCase__ : Tuple = tokenize_chinese_chars UpperCAmelCase__ : Union[str, Any] = normalizer_class(**_lowerCAmelCase ) UpperCAmelCase__ : Dict = do_lower_case def __UpperCAmelCase ( self , _lowerCAmelCase , **_lowerCAmelCase ): UpperCAmelCase__ : List[Any] = PaddingStrategy.MAX_LENGTH UpperCAmelCase__ : Optional[int] = text UpperCAmelCase__ : Optional[int] = kwargs.pop("""text_pair""" , _lowerCAmelCase ) UpperCAmelCase__ : Optional[int] = kwargs.pop("""return_tensors""" , _lowerCAmelCase ) UpperCAmelCase__ : Optional[Any] = { """input_ids""": [], """attention_mask""": [], """token_type_ids""": [], } for idx, candidate_text in enumerate(_lowerCAmelCase ): if batch_text_pair is not None: UpperCAmelCase__ : str = batch_text_pair[idx] else: UpperCAmelCase__ : Any = None UpperCAmelCase__ : str = super().__call__(_lowerCAmelCase , _lowerCAmelCase , return_tensors=_lowerCAmelCase , **_lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = encoded_candidates.get("""input_ids""" ) UpperCAmelCase__ : str = encoded_candidates.get("""attention_mask""" ) UpperCAmelCase__ : Union[str, Any] = encoded_candidates.get("""token_type_ids""" ) if encoded_input_ids is not None: output_data["input_ids"].append(_lowerCAmelCase ) if encoded_attention_mask is not None: output_data["attention_mask"].append(_lowerCAmelCase ) if encoded_token_type_ids is not None: output_data["token_type_ids"].append(_lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = {key: item for key, item in output_data.items() if len(_lowerCAmelCase ) != 0} return BatchEncoding(_lowerCAmelCase , tensor_type=_lowerCAmelCase ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase=None ): UpperCAmelCase__ : List[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 __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase = None ): UpperCAmelCase__ : Any = [self.sep_token_id] UpperCAmelCase__ : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase = None ): UpperCAmelCase__ : List[str] = self._tokenizer.model.save(_lowerCAmelCase , name=_lowerCAmelCase ) return tuple(_lowerCAmelCase )
79
1
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : str = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { """huggingface/informer-tourism-monthly""": ( """https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json""" ), # See all Informer models at https://huggingface.co/models?filter=informer } class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = 'informer' __lowerCamelCase = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = "student_t" , _lowerCAmelCase = "nll" , _lowerCAmelCase = 1 , _lowerCAmelCase = None , _lowerCAmelCase = "mean" , _lowerCAmelCase = 0 , _lowerCAmelCase = 0 , _lowerCAmelCase = 0 , _lowerCAmelCase = 0 , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = 64 , _lowerCAmelCase = 32 , _lowerCAmelCase = 32 , _lowerCAmelCase = 2 , _lowerCAmelCase = 2 , _lowerCAmelCase = 2 , _lowerCAmelCase = 2 , _lowerCAmelCase = True , _lowerCAmelCase = "gelu" , _lowerCAmelCase = 0.0_5 , _lowerCAmelCase = 0.1 , _lowerCAmelCase = 0.1 , _lowerCAmelCase = 0.1 , _lowerCAmelCase = 0.1 , _lowerCAmelCase = 100 , _lowerCAmelCase = 0.0_2 , _lowerCAmelCase=True , _lowerCAmelCase = "prob" , _lowerCAmelCase = 5 , _lowerCAmelCase = True , **_lowerCAmelCase , ): # time series specific configuration UpperCAmelCase__ : List[str] = prediction_length UpperCAmelCase__ : Optional[Any] = context_length or prediction_length UpperCAmelCase__ : str = distribution_output UpperCAmelCase__ : int = loss UpperCAmelCase__ : Optional[Any] = input_size UpperCAmelCase__ : Any = num_time_features UpperCAmelCase__ : int = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7] UpperCAmelCase__ : Union[str, Any] = scaling UpperCAmelCase__ : Optional[Any] = num_dynamic_real_features UpperCAmelCase__ : List[str] = num_static_real_features UpperCAmelCase__ : str = num_static_categorical_features # set cardinality if cardinality and num_static_categorical_features > 0: if len(_lowerCAmelCase ) != num_static_categorical_features: raise ValueError( """The cardinality should be a list of the same length as `num_static_categorical_features`""" ) UpperCAmelCase__ : List[str] = cardinality else: UpperCAmelCase__ : Optional[Any] = [0] # set embedding_dimension if embedding_dimension and num_static_categorical_features > 0: if len(_lowerCAmelCase ) != num_static_categorical_features: raise ValueError( """The embedding dimension should be a list of the same length as `num_static_categorical_features`""" ) UpperCAmelCase__ : str = embedding_dimension else: UpperCAmelCase__ : List[str] = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] UpperCAmelCase__ : Union[str, Any] = num_parallel_samples # Transformer architecture configuration UpperCAmelCase__ : Dict = input_size * len(self.lags_sequence ) + self._number_of_features UpperCAmelCase__ : Any = d_model UpperCAmelCase__ : int = encoder_attention_heads UpperCAmelCase__ : Optional[Any] = decoder_attention_heads UpperCAmelCase__ : int = encoder_ffn_dim UpperCAmelCase__ : Tuple = decoder_ffn_dim UpperCAmelCase__ : List[Any] = encoder_layers UpperCAmelCase__ : Optional[Any] = decoder_layers UpperCAmelCase__ : Tuple = dropout UpperCAmelCase__ : int = attention_dropout UpperCAmelCase__ : List[str] = activation_dropout UpperCAmelCase__ : Any = encoder_layerdrop UpperCAmelCase__ : Union[str, Any] = decoder_layerdrop UpperCAmelCase__ : Tuple = activation_function UpperCAmelCase__ : Dict = init_std UpperCAmelCase__ : str = use_cache # Informer UpperCAmelCase__ : Union[str, Any] = attention_type UpperCAmelCase__ : int = sampling_factor UpperCAmelCase__ : Any = distil super().__init__(is_encoder_decoder=_lowerCAmelCase , **_lowerCAmelCase ) @property def __UpperCAmelCase ( self ): return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
79
# 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. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = 'facebook/bart-large-mnli' __lowerCamelCase = ( 'This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which ' 'should be the text to classify, and `labels`, which should be the list of labels to use for classification. ' 'It returns the most likely label in the list of provided `labels` for the input text.' ) __lowerCamelCase = 'text_classifier' __lowerCamelCase = AutoTokenizer __lowerCamelCase = AutoModelForSequenceClassification __lowerCamelCase = ['text', ['text']] __lowerCamelCase = ['text'] def __UpperCAmelCase ( self ): super().setup() UpperCAmelCase__ : Optional[Any] = self.model.config UpperCAmelCase__ : Tuple = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("""entail""" ): UpperCAmelCase__ : Dict = int(_lowerCAmelCase ) if self.entailment_id == -1: raise ValueError("""Could not determine the entailment ID from the model config, please pass it at init.""" ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : List[Any] = labels return self.pre_processor( [text] * len(_lowerCAmelCase ) , [f"This example is {label}" for label in labels] , return_tensors="""pt""" , padding="""max_length""" , ) def __UpperCAmelCase ( self , _lowerCAmelCase ): UpperCAmelCase__ : str = outputs.logits UpperCAmelCase__ : List[Any] = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
79
1
import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : List[str] = logging.get_logger() def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = True ) -> Any: '''simple docstring''' print(F"Converting {name}..." ) with torch.no_grad(): if hidden_sizes == 128: if name[-1] == "S": UpperCAmelCase__ : int = timm.create_model("""levit_128s""" , pretrained=__lowerCamelCase ) else: UpperCAmelCase__ : Optional[int] = timm.create_model("""levit_128""" , pretrained=__lowerCamelCase ) if hidden_sizes == 192: UpperCAmelCase__ : Union[str, Any] = timm.create_model("""levit_192""" , pretrained=__lowerCamelCase ) if hidden_sizes == 256: UpperCAmelCase__ : str = timm.create_model("""levit_256""" , pretrained=__lowerCamelCase ) if hidden_sizes == 384: UpperCAmelCase__ : int = timm.create_model("""levit_384""" , pretrained=__lowerCamelCase ) from_model.eval() UpperCAmelCase__ : List[Any] = LevitForImageClassificationWithTeacher(__lowerCamelCase ).eval() UpperCAmelCase__ : Tuple = OrderedDict() UpperCAmelCase__ : Tuple = from_model.state_dict() UpperCAmelCase__ : Optional[int] = list(from_model.state_dict().keys() ) UpperCAmelCase__ : List[Any] = list(our_model.state_dict().keys() ) print(len(__lowerCamelCase ) , len(__lowerCamelCase ) ) for i in range(len(__lowerCamelCase ) ): UpperCAmelCase__ : List[Any] = weights[og_keys[i]] our_model.load_state_dict(__lowerCamelCase ) UpperCAmelCase__ : Dict = torch.randn((2, 3, 224, 224) ) UpperCAmelCase__ : Any = from_model(__lowerCamelCase ) UpperCAmelCase__ : Union[str, Any] = our_model(__lowerCamelCase ).logits assert torch.allclose(__lowerCamelCase , __lowerCamelCase ), "The model logits don't match the original one." UpperCAmelCase__ : Optional[Any] = name print(__lowerCamelCase ) if push_to_hub: our_model.save_pretrained(save_directory / checkpoint_name ) UpperCAmelCase__ : Any = LevitImageProcessor() image_processor.save_pretrained(save_directory / checkpoint_name ) print(F"Pushed {checkpoint_name}" ) def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = True ) -> List[str]: '''simple docstring''' UpperCAmelCase__ : List[Any] = """imagenet-1k-id2label.json""" UpperCAmelCase__ : Optional[int] = 1000 UpperCAmelCase__ : Any = (1, num_labels) UpperCAmelCase__ : Tuple = """huggingface/label-files""" UpperCAmelCase__ : int = num_labels UpperCAmelCase__ : str = json.load(open(hf_hub_download(__lowerCamelCase , __lowerCamelCase , repo_type="""dataset""" ) , """r""" ) ) UpperCAmelCase__ : Optional[int] = {int(__lowerCamelCase ): v for k, v in idalabel.items()} UpperCAmelCase__ : int = idalabel UpperCAmelCase__ : int = {v: k for k, v in idalabel.items()} UpperCAmelCase__ : List[str] = partial(__lowerCamelCase , num_labels=__lowerCamelCase , idalabel=__lowerCamelCase , labelaid=__lowerCamelCase ) UpperCAmelCase__ : int = { """levit-128S""": 128, """levit-128""": 128, """levit-192""": 192, """levit-256""": 256, """levit-384""": 384, } UpperCAmelCase__ : Optional[int] = { """levit-128S""": ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] , num_attention_heads=[4, 6, 8] , depths=[2, 3, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), """levit-128""": ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] , num_attention_heads=[4, 8, 12] , depths=[4, 4, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), """levit-192""": ImageNetPreTrainedConfig( hidden_sizes=[192, 288, 384] , num_attention_heads=[3, 5, 6] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), """levit-256""": ImageNetPreTrainedConfig( hidden_sizes=[256, 384, 512] , num_attention_heads=[4, 6, 8] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), """levit-384""": ImageNetPreTrainedConfig( hidden_sizes=[384, 512, 768] , num_attention_heads=[6, 9, 12] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0.1 , ), } if model_name: convert_weight_and_push( names_to_hidden_sizes[model_name] , __lowerCamelCase , names_to_config[model_name] , __lowerCamelCase , __lowerCamelCase ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(names_to_hidden_sizes[model_name] , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return config, expected_shape if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default=None, type=str, help="""The name of the model you wish to convert, it must be one of the supported Levit* architecture,""", ) parser.add_argument( """--pytorch_dump_folder_path""", default="""levit-dump-folder/""", type=Path, required=False, help="""Path to the output PyTorch model directory.""", ) parser.add_argument("""--push_to_hub""", action="""store_true""", help="""Push model and image processor to the hub""") parser.add_argument( """--no-push_to_hub""", dest="""push_to_hub""", action="""store_false""", help="""Do not push model and image processor to the hub""", ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args() SCREAMING_SNAKE_CASE__ : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
79
from __future__ import annotations import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFViTForImageClassification, TFViTModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class UpperCAmelCase_ : def __init__( self , _lowerCAmelCase , _lowerCAmelCase=13 , _lowerCAmelCase=30 , _lowerCAmelCase=2 , _lowerCAmelCase=3 , _lowerCAmelCase=True , _lowerCAmelCase=True , _lowerCAmelCase=32 , _lowerCAmelCase=2 , _lowerCAmelCase=4 , _lowerCAmelCase=37 , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.1 , _lowerCAmelCase=10 , _lowerCAmelCase=0.0_2 , _lowerCAmelCase=3 , _lowerCAmelCase=None , ): UpperCAmelCase__ : Tuple = parent UpperCAmelCase__ : Optional[int] = batch_size UpperCAmelCase__ : Union[str, Any] = image_size UpperCAmelCase__ : int = patch_size UpperCAmelCase__ : str = num_channels UpperCAmelCase__ : int = is_training UpperCAmelCase__ : List[str] = use_labels UpperCAmelCase__ : List[Any] = hidden_size UpperCAmelCase__ : int = num_hidden_layers UpperCAmelCase__ : Tuple = num_attention_heads UpperCAmelCase__ : Optional[int] = intermediate_size UpperCAmelCase__ : Optional[Any] = hidden_act UpperCAmelCase__ : int = hidden_dropout_prob UpperCAmelCase__ : int = attention_probs_dropout_prob UpperCAmelCase__ : List[str] = type_sequence_label_size UpperCAmelCase__ : Optional[int] = initializer_range UpperCAmelCase__ : Any = scope # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) UpperCAmelCase__ : Any = (image_size // patch_size) ** 2 UpperCAmelCase__ : Tuple = num_patches + 1 def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase__ : List[str] = None if self.use_labels: UpperCAmelCase__ : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase__ : Union[str, Any] = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self ): return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_lowerCAmelCase , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : str = TFViTModel(config=_lowerCAmelCase ) UpperCAmelCase__ : str = model(_lowerCAmelCase , training=_lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # Test with an image with different size than the one specified in config. UpperCAmelCase__ : Optional[Any] = self.image_size // 2 UpperCAmelCase__ : List[str] = pixel_values[:, :, :image_size, :image_size] UpperCAmelCase__ : List[Any] = model(_lowerCAmelCase , interpolate_pos_encoding=_lowerCAmelCase , training=_lowerCAmelCase ) UpperCAmelCase__ : str = (image_size // self.patch_size) ** 2 + 1 self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : Tuple = self.type_sequence_label_size UpperCAmelCase__ : List[Any] = TFViTForImageClassification(_lowerCAmelCase ) UpperCAmelCase__ : List[str] = model(_lowerCAmelCase , labels=_lowerCAmelCase , training=_lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # Test with an image with different size than the one specified in config. UpperCAmelCase__ : Tuple = self.image_size // 2 UpperCAmelCase__ : Union[str, Any] = pixel_values[:, :, :image_size, :image_size] UpperCAmelCase__ : List[str] = model(_lowerCAmelCase , interpolate_pos_encoding=_lowerCAmelCase , training=_lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCAmelCase__ : Union[str, Any] = 1 UpperCAmelCase__ : Optional[Any] = TFViTForImageClassification(_lowerCAmelCase ) UpperCAmelCase__ : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCAmelCase__ : List[str] = model(_lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[Any] = self.prepare_config_and_inputs() UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : int = config_and_inputs UpperCAmelCase__ : int = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class UpperCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): __lowerCamelCase = (TFViTModel, TFViTForImageClassification) if is_tf_available() else () __lowerCamelCase = ( {'feature-extraction': TFViTModel, 'image-classification': TFViTForImageClassification} if is_tf_available() else {} ) __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False def __UpperCAmelCase ( self ): UpperCAmelCase__ : Any = TFViTModelTester(self ) UpperCAmelCase__ : int = ConfigTester(self , config_class=_lowerCAmelCase , has_text_modality=_lowerCAmelCase , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): UpperCAmelCase__ , UpperCAmelCase__ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ : str = model_class(_lowerCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) UpperCAmelCase__ : Dict = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowerCAmelCase , tf.keras.layers.Layer ) ) def __UpperCAmelCase ( self ): UpperCAmelCase__ , UpperCAmelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ : Optional[int] = model_class(_lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase__ : Tuple = [*signature.parameters.keys()] UpperCAmelCase__ : str = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _lowerCAmelCase ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCAmelCase ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase ) @slow def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = TFViTModel.from_pretrained("""google/vit-base-patch16-224""" ) self.assertIsNotNone(_lowerCAmelCase ) def _lowerCamelCase ( ) -> Tuple: '''simple docstring''' UpperCAmelCase__ : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class UpperCAmelCase_ ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self ): return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224""" ) if is_vision_available() else None @slow def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[int] = TFViTForImageClassification.from_pretrained("""google/vit-base-patch16-224""" ) UpperCAmelCase__ : List[Any] = self.default_image_processor UpperCAmelCase__ : Union[str, Any] = prepare_img() UpperCAmelCase__ : Optional[Any] = image_processor(images=_lowerCAmelCase , return_tensors="""tf""" ) # forward pass UpperCAmelCase__ : int = model(**_lowerCAmelCase ) # verify the logits UpperCAmelCase__ : Tuple = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowerCAmelCase ) UpperCAmelCase__ : int = tf.constant([-0.2_7_4_4, 0.8_2_1_5, -0.0_8_3_6] ) tf.debugging.assert_near(outputs.logits[0, :3] , _lowerCAmelCase , atol=1e-4 )
79
1
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 SCREAMING_SNAKE_CASE__ : str = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Tuple = {"""vocab_file""": """sentencepiece.bpe.model"""} SCREAMING_SNAKE_CASE__ : Any = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, } SCREAMING_SNAKE_CASE__ : int = { """moussaKam/mbarthez""": 10_24, """moussaKam/barthez""": 10_24, """moussaKam/barthez-orangesum-title""": 10_24, } SCREAMING_SNAKE_CASE__ : Optional[Any] = """▁""" class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = VOCAB_FILES_NAMES __lowerCamelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase = ['input_ids', 'attention_mask'] def __init__( self , _lowerCAmelCase , _lowerCAmelCase="<s>" , _lowerCAmelCase="</s>" , _lowerCAmelCase="</s>" , _lowerCAmelCase="<s>" , _lowerCAmelCase="<unk>" , _lowerCAmelCase="<pad>" , _lowerCAmelCase="<mask>" , _lowerCAmelCase = None , **_lowerCAmelCase , ): # Mask token behave like a normal word, i.e. include the space before it UpperCAmelCase__ : str = AddedToken(_lowerCAmelCase , lstrip=_lowerCAmelCase , rstrip=_lowerCAmelCase ) if isinstance(_lowerCAmelCase , _lowerCAmelCase ) else mask_token UpperCAmelCase__ : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_lowerCAmelCase , eos_token=_lowerCAmelCase , unk_token=_lowerCAmelCase , sep_token=_lowerCAmelCase , cls_token=_lowerCAmelCase , pad_token=_lowerCAmelCase , mask_token=_lowerCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **_lowerCAmelCase , ) UpperCAmelCase__ : int = vocab_file UpperCAmelCase__ : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_lowerCAmelCase ) ) UpperCAmelCase__ : Dict = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} UpperCAmelCase__ : Union[str, Any] = len(self.sp_model ) - 1 UpperCAmelCase__ : Optional[int] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] UpperCAmelCase__ : int = [self.cls_token_id] UpperCAmelCase__ : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase = None , _lowerCAmelCase = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCAmelCase , token_ids_a=_lowerCAmelCase , already_has_special_tokens=_lowerCAmelCase ) if token_ids_a is None: return [1] + ([0] * len(_lowerCAmelCase )) + [1] return [1] + ([0] * len(_lowerCAmelCase )) + [1, 1] + ([0] * len(_lowerCAmelCase )) + [1] def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase = None ): UpperCAmelCase__ : int = [self.sep_token_id] UpperCAmelCase__ : Optional[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 __UpperCAmelCase ( self ): return len(self.sp_model ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[str] = {self.convert_ids_to_tokens(_lowerCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __UpperCAmelCase ( self , _lowerCAmelCase ): return self.sp_model.encode(_lowerCAmelCase , out_type=_lowerCAmelCase ) def __UpperCAmelCase ( self , _lowerCAmelCase ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] UpperCAmelCase__ : int = self.sp_model.PieceToId(_lowerCAmelCase ) return spm_id if spm_id else self.unk_token_id def __UpperCAmelCase ( self , _lowerCAmelCase ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(_lowerCAmelCase ) def __UpperCAmelCase ( self , _lowerCAmelCase ): UpperCAmelCase__ : int = [] UpperCAmelCase__ : List[str] = """""" UpperCAmelCase__ : Optional[Any] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_lowerCAmelCase ) + token UpperCAmelCase__ : Dict = True UpperCAmelCase__ : Tuple = [] else: current_sub_tokens.append(_lowerCAmelCase ) UpperCAmelCase__ : Optional[int] = False out_string += self.sp_model.decode(_lowerCAmelCase ) return out_string.strip() def __getstate__( self ): UpperCAmelCase__ : str = self.__dict__.copy() UpperCAmelCase__ : List[Any] = None return state def __setstate__( self , _lowerCAmelCase ): UpperCAmelCase__ : Union[str, Any] = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): UpperCAmelCase__ : int = {} UpperCAmelCase__ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase = None ): if not os.path.isdir(_lowerCAmelCase ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return UpperCAmelCase__ : Tuple = os.path.join( _lowerCAmelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCAmelCase , """wb""" ) as fi: UpperCAmelCase__ : str = self.sp_model.serialized_model_proto() fi.write(_lowerCAmelCase ) return (out_vocab_file,)
79
from functools import lru_cache @lru_cache def _lowerCamelCase ( __lowerCamelCase ) -> int: '''simple docstring''' if num < 0: raise ValueError("""Number should not be negative.""" ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
79
1
import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy SCREAMING_SNAKE_CASE__ : List[Any] = logging.getLogger(__name__) SCREAMING_SNAKE_CASE__ : List[str] = """pytorch_model.bin""" @dataclasses.dataclass class UpperCAmelCase_ : __lowerCamelCase = dataclasses.field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models.'} ) __lowerCamelCase = dataclasses.field( default=__lowerCamelCase , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co.'} , ) @dataclasses.dataclass class UpperCAmelCase_ : __lowerCamelCase = dataclasses.field(metadata={'help': 'A csv or a json file containing the training data.'} ) __lowerCamelCase = dataclasses.field(metadata={'help': 'A csv or a json file containing the data to predict on.'} ) __lowerCamelCase = dataclasses.field( default=__lowerCamelCase , metadata={'help': 'A csv or a json file containing the validation data.'} ) __lowerCamelCase = dataclasses.field( default=__lowerCamelCase , metadata={'help': 'The name of the task to train on.'} , ) __lowerCamelCase = dataclasses.field( default=__lowerCamelCase , metadata={'help': 'The list of labels for the task.'} ) @dataclasses.dataclass class UpperCAmelCase_ : __lowerCamelCase = dataclasses.field( metadata={'help': 'The output directory where the model predictions and checkpoints will be written.'} ) __lowerCamelCase = dataclasses.field( default='accuracy' , metadata={'help': 'The evaluation metric used for the task.'} ) __lowerCamelCase = dataclasses.field( default='no' , metadata={ 'help': 'The evaluation strategy to adopt during training. Possible values are: ["no", "step", "epoch]' } , ) __lowerCamelCase = dataclasses.field( default=10 , metadata={'help': 'Number of evaluation calls with no improvement after which training will be stopped.'} , ) __lowerCamelCase = dataclasses.field( default=0.0 , metadata={ 'help': 'How much the specified evaluation metric must improve to satisfy early stopping conditions.' } , ) __lowerCamelCase = dataclasses.field( default=__lowerCamelCase , metadata={'help': 'Whether to filter the pseudo-labeled data based on the confidence score.'} , ) __lowerCamelCase = dataclasses.field( default=__lowerCamelCase , metadata={'help': 'Whether to filter the pseudo-labeled data based on the validation performance.'} , ) __lowerCamelCase = dataclasses.field( default=__lowerCamelCase , metadata={'help': 'Whether to fine-tune on labeled data after pseudo training.'} , ) __lowerCamelCase = dataclasses.field( default=0.0 , metadata={'help': 'Confidence threshold for pseudo-labeled data filtering.'} , ) __lowerCamelCase = dataclasses.field( default=100 , metadata={'help': 'Number of evaluation calls with no improvement after which training will be stopped.'} , ) __lowerCamelCase = dataclasses.field( default=__lowerCamelCase , metadata={'help': 'Random seed for initialization.'} , ) def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[str]: '''simple docstring''' UpperCAmelCase__ : int = datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: UpperCAmelCase__ : Any = dataset.filter(lambda __lowerCamelCase : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 UpperCAmelCase__ : int = int(eval_result * len(__lowerCamelCase ) ) print(__lowerCamelCase ) UpperCAmelCase__ : Optional[int] = dataset.sort("""probability""" , reverse=__lowerCamelCase ) UpperCAmelCase__ : Dict = dataset.select(range(__lowerCamelCase ) ) UpperCAmelCase__ : str = dataset.remove_columns(["""label""", """probability"""] ) UpperCAmelCase__ : Any = dataset.rename_column("""prediction""" , """label""" ) UpperCAmelCase__ : int = dataset.map(lambda __lowerCamelCase : {"label": idalabel[example["label"]]} ) UpperCAmelCase__ : Tuple = dataset.shuffle(seed=args.seed ) UpperCAmelCase__ : Dict = os.path.join(__lowerCamelCase , F"train_pseudo.{args.data_file_extension}" ) if args.data_file_extension == "csv": dataset.to_csv(__lowerCamelCase , index=__lowerCamelCase ) else: dataset.to_json(__lowerCamelCase ) def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , **__lowerCamelCase ) -> Optional[int]: '''simple docstring''' UpperCAmelCase__ : Dict = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO , ) logger.info(accelerator.state ) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() UpperCAmelCase__ : str = STModelArguments(model_name_or_path=__lowerCamelCase ) UpperCAmelCase__ : int = STDataArguments(train_file=__lowerCamelCase , infer_file=__lowerCamelCase ) UpperCAmelCase__ : Dict = STTrainingArguments(output_dir=__lowerCamelCase ) UpperCAmelCase__ : Dict = argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(__lowerCamelCase ).items(): setattr(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) for key, value in kwargs.items(): if hasattr(__lowerCamelCase , __lowerCamelCase ): setattr(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # Sanity checks UpperCAmelCase__ : Tuple = {} UpperCAmelCase__ : Dict = None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None UpperCAmelCase__ : Tuple = args.train_file UpperCAmelCase__ : List[str] = args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None UpperCAmelCase__ : Union[str, Any] = args.eval_file for key in data_files: UpperCAmelCase__ : List[str] = data_files[key].split(""".""" )[-1] assert extension in ["csv", "json"], F"`{key}_file` should be a csv or a json file." if args.data_file_extension is None: UpperCAmelCase__ : Any = extension else: assert extension == args.data_file_extension, F"`{key}_file` should be a {args.data_file_extension} file`." assert ( args.eval_metric in datasets.list_metrics() ), F"{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}." # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed ) logger.info("""Creating the initial data directory for self-training...""" ) UpperCAmelCase__ : List[Any] = F"{args.output_dir}/self-train_iter-{{}}".format UpperCAmelCase__ : Any = data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=__lowerCamelCase ) os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) accelerator.wait_for_everyone() UpperCAmelCase__ : Union[str, Any] = None UpperCAmelCase__ : Tuple = None UpperCAmelCase__ : Dict = 0 UpperCAmelCase__ : Optional[int] = False # Show the progress bar UpperCAmelCase__ : int = tqdm(range(args.max_selftrain_iterations ) , disable=not accelerator.is_local_main_process ) # Self-train for iteration in range(0 , int(args.max_selftrain_iterations ) ): UpperCAmelCase__ : Tuple = data_dir_format(__lowerCamelCase ) assert os.path.exists(__lowerCamelCase ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 UpperCAmelCase__ : List[str] = os.path.join(__lowerCamelCase , """stage-1""" ) UpperCAmelCase__ : List[Any] = { """accelerator""": accelerator, """model_name_or_path""": args.model_name_or_path, """cache_dir""": args.cache_dir, """do_train""": True, """train_file""": data_files["""train"""] if iteration == 0 else data_files["""train_pseudo"""], """do_eval""": True if args.eval_file is not None else False, """eval_file""": data_files["""eval"""], """do_predict""": True, """infer_file""": data_files["""infer"""], """task_name""": args.task_name, """label_list""": args.label_list, """output_dir""": current_output_dir, """eval_metric""": args.eval_metric, """evaluation_strategy""": args.evaluation_strategy, """early_stopping_patience""": args.early_stopping_patience, """early_stopping_threshold""": args.early_stopping_threshold, """seed""": args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(__lowerCamelCase , __lowerCamelCase ): arguments_dict.update({key: value} ) UpperCAmelCase__ : List[Any] = os.path.join(__lowerCamelCase , """best-checkpoint""" , __lowerCamelCase ) if os.path.exists(__lowerCamelCase ): logger.info( """Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.""" , __lowerCamelCase , __lowerCamelCase , ) else: logger.info("""***** Running self-training: iteration: %d, stage: 1 *****""" , __lowerCamelCase ) finetune(**__lowerCamelCase ) accelerator.wait_for_everyone() assert os.path.exists(__lowerCamelCase ) logger.info("""Self-training job completed: iteration: %d, stage: 1.""" , __lowerCamelCase ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data UpperCAmelCase__ : Any = os.path.join(__lowerCamelCase , """best-checkpoint""" ) UpperCAmelCase__ : Any = os.path.join(__lowerCamelCase , """stage-2""" ) # Update arguments_dict UpperCAmelCase__ : Union[str, Any] = model_path UpperCAmelCase__ : Optional[Any] = data_files["""train"""] UpperCAmelCase__ : Tuple = current_output_dir UpperCAmelCase__ : Union[str, Any] = os.path.join(__lowerCamelCase , """best-checkpoint""" , __lowerCamelCase ) if os.path.exists(__lowerCamelCase ): logger.info( """Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.""" , __lowerCamelCase , __lowerCamelCase , ) else: logger.info("""***** Running self-training: iteration: %d, stage: 2 *****""" , __lowerCamelCase ) finetune(**__lowerCamelCase ) accelerator.wait_for_everyone() assert os.path.exists(__lowerCamelCase ) logger.info("""Self-training job completed: iteration: %d, stage: 2.""" , __lowerCamelCase ) UpperCAmelCase__ : str = iteration UpperCAmelCase__ : List[str] = data_dir_format(iteration + 1 ) UpperCAmelCase__ : Any = AutoConfig.from_pretrained(os.path.join(__lowerCamelCase , """best-checkpoint""" ) ) UpperCAmelCase__ : Optional[Any] = config.idalabel UpperCAmelCase__ : Tuple = os.path.join(__lowerCamelCase , """eval_results_best-checkpoint.json""" ) UpperCAmelCase__ : Dict = os.path.join(__lowerCamelCase , """test_results_best-checkpoint.json""" ) assert os.path.exists(__lowerCamelCase ) with open(__lowerCamelCase , """r""" ) as f: UpperCAmelCase__ : Optional[Any] = float(json.load(__lowerCamelCase )[args.eval_metric] ) UpperCAmelCase__ : Tuple = os.path.join(__lowerCamelCase , """infer_output_best-checkpoint.csv""" ) assert os.path.exists(__lowerCamelCase ) # Loading the dataset from local csv or json files. UpperCAmelCase__ : Union[str, Any] = load_dataset(args.data_file_extension , data_files={"""data""": data_files["""infer"""]} )["""data"""] UpperCAmelCase__ : List[Any] = load_dataset("""csv""" , data_files={"""data""": infer_output_file} )["""data"""] if accelerator.is_main_process: os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) shutil.copy(__lowerCamelCase , os.path.join(__lowerCamelCase , F"eval_results_iter-{iteration}.json" ) ) if os.path.exists(__lowerCamelCase ): shutil.copy(__lowerCamelCase , os.path.join(__lowerCamelCase , F"test_results_iter-{iteration}.json" ) ) create_pseudo_labeled_data(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) accelerator.wait_for_everyone() UpperCAmelCase__ : Tuple = os.path.join(__lowerCamelCase , F"train_pseudo.{args.data_file_extension}" ) if args.evaluation_strategy != IntervalStrategy.NO.value: UpperCAmelCase__ : Optional[Any] = eval_result if best_iteration is None: UpperCAmelCase__ : Tuple = new_iteration UpperCAmelCase__ : Tuple = new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: UpperCAmelCase__ : List[str] = new_iteration UpperCAmelCase__ : List[str] = new_eval_result UpperCAmelCase__ : Optional[int] = 0 else: if new_eval_result == best_eval_result: UpperCAmelCase__ : Tuple = new_iteration UpperCAmelCase__ : Union[str, Any] = new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: UpperCAmelCase__ : List[Any] = True progress_bar.update(1 ) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info("""Best iteration: %d""" , __lowerCamelCase ) logger.info("""Best evaluation result: %s = %f""" , args.eval_metric , __lowerCamelCase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(__lowerCamelCase , F"eval_results_iter-{iteration}.json" ) , os.path.join(__lowerCamelCase , """eval_results_best-iteration.json""" ) , ) else: # Assume that the last iteration is the best logger.info("""Best iteration: %d""" , args.max_selftrain_iterations - 1 ) logger.info("""Best evaluation result: %s = %f""" , args.eval_metric , __lowerCamelCase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(__lowerCamelCase , F"eval_results_iter-{args.max_selftrain_iterations - 1}.json" ) , os.path.join(__lowerCamelCase , """eval_results_best-iteration.json""" ) , )
79
import argparse import hashlib # hashlib is only used inside the Test class import struct class UpperCAmelCase_ : def __init__( self , _lowerCAmelCase ): UpperCAmelCase__ : Any = data UpperCAmelCase__ : List[Any] = [0X6745_2301, 0Xefcd_ab89, 0X98ba_dcfe, 0X1032_5476, 0Xc3d2_e1f0] @staticmethod def __UpperCAmelCase ( _lowerCAmelCase , _lowerCAmelCase ): return ((n << b) | (n >> (32 - b))) & 0Xffff_ffff def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = B"""\x80""" + B"""\x00""" * (63 - (len(self.data ) + 8) % 64) UpperCAmelCase__ : Optional[int] = self.data + padding + struct.pack(""">Q""" , 8 * len(self.data ) ) return padded_data def __UpperCAmelCase ( self ): return [ self.padded_data[i : i + 64] for i in range(0 , len(self.padded_data ) , 64 ) ] def __UpperCAmelCase ( self , _lowerCAmelCase ): UpperCAmelCase__ : Dict = list(struct.unpack(""">16L""" , _lowerCAmelCase ) ) + [0] * 64 for i in range(16 , 80 ): UpperCAmelCase__ : Optional[int] = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]) , 1 ) return w def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[str] = self.padding() UpperCAmelCase__ : List[str] = self.split_blocks() for block in self.blocks: UpperCAmelCase__ : Tuple = self.expand_block(_lowerCAmelCase ) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Tuple = self.h for i in range(0 , 80 ): if 0 <= i < 20: UpperCAmelCase__ : Optional[int] = (b & c) | ((~b) & d) UpperCAmelCase__ : int = 0X5a82_7999 elif 20 <= i < 40: UpperCAmelCase__ : Tuple = b ^ c ^ d UpperCAmelCase__ : int = 0X6ed9_eba1 elif 40 <= i < 60: UpperCAmelCase__ : List[str] = (b & c) | (b & d) | (c & d) UpperCAmelCase__ : Tuple = 0X8f1b_bcdc elif 60 <= i < 80: UpperCAmelCase__ : int = b ^ c ^ d UpperCAmelCase__ : str = 0Xca62_c1d6 UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Optional[Any] = ( self.rotate(_lowerCAmelCase , 5 ) + f + e + k + expanded_block[i] & 0Xffff_ffff, a, self.rotate(_lowerCAmelCase , 30 ), c, d, ) UpperCAmelCase__ : int = ( self.h[0] + a & 0Xffff_ffff, self.h[1] + b & 0Xffff_ffff, self.h[2] + c & 0Xffff_ffff, self.h[3] + d & 0Xffff_ffff, self.h[4] + e & 0Xffff_ffff, ) return ("{:08x}" * 5).format(*self.h ) def _lowerCamelCase ( ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase__ : Optional[Any] = B"""Test String""" assert SHAaHash(__lowerCamelCase ).final_hash() == hashlib.shaa(__lowerCamelCase ).hexdigest() # noqa: S324 def _lowerCamelCase ( ) -> str: '''simple docstring''' UpperCAmelCase__ : Optional[int] = argparse.ArgumentParser(description="""Process some strings or files""" ) parser.add_argument( """--string""" , dest="""input_string""" , default="""Hello World!! Welcome to Cryptography""" , help="""Hash the string""" , ) parser.add_argument("""--file""" , dest="""input_file""" , help="""Hash contents of a file""" ) UpperCAmelCase__ : str = parser.parse_args() UpperCAmelCase__ : Union[str, Any] = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , """rb""" ) as f: UpperCAmelCase__ : List[Any] = f.read() else: UpperCAmelCase__ : int = bytes(__lowerCamelCase , """utf-8""" ) print(SHAaHash(__lowerCamelCase ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
79
1
def _lowerCamelCase ( __lowerCamelCase ) -> int: '''simple docstring''' return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def _lowerCamelCase ( __lowerCamelCase ) -> bool: '''simple docstring''' UpperCAmelCase__ : Any = 0 UpperCAmelCase__ : Union[str, Any] = number while duplicate > 0: UpperCAmelCase__ , UpperCAmelCase__ : List[Any] = divmod(__lowerCamelCase , 10 ) fact_sum += factorial(__lowerCamelCase ) return fact_sum == number if __name__ == "__main__": print("""Program to check whether a number is a Krisnamurthy Number or not.""") SCREAMING_SNAKE_CASE__ : Optional[Any] = int(input("""Enter number: """).strip()) print( f'''{number} is {"" if krishnamurthy(number) else "not "}a Krishnamurthy Number.''' )
79
from importlib import import_module from .logging import get_logger SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_logger(__name__) class UpperCAmelCase_ : def __init__( self , _lowerCAmelCase , _lowerCAmelCase=None ): UpperCAmelCase__ : List[str] = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith("""__""" ): setattr(self , _lowerCAmelCase , getattr(_lowerCAmelCase , _lowerCAmelCase ) ) UpperCAmelCase__ : Tuple = module._original_module if isinstance(_lowerCAmelCase , _PatchedModuleObj ) else module class UpperCAmelCase_ : __lowerCamelCase = [] def __init__( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=None ): UpperCAmelCase__ : str = obj UpperCAmelCase__ : List[str] = target UpperCAmelCase__ : List[str] = new UpperCAmelCase__ : Any = target.split(""".""" )[0] UpperCAmelCase__ : Union[str, Any] = {} UpperCAmelCase__ : str = attrs or [] def __enter__( self ): *UpperCAmelCase__ , UpperCAmelCase__ : List[Any] = self.target.split(""".""" ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(_lowerCAmelCase ) ): try: UpperCAmelCase__ : Optional[int] = import_module(""".""".join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): UpperCAmelCase__ : Any = getattr(self.obj , _lowerCAmelCase ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(_lowerCAmelCase , _PatchedModuleObj ) and obj_attr._original_module is submodule) ): UpperCAmelCase__ : List[Any] = obj_attr # patch at top level setattr(self.obj , _lowerCAmelCase , _PatchedModuleObj(_lowerCAmelCase , attrs=self.attrs ) ) UpperCAmelCase__ : Optional[Any] = getattr(self.obj , _lowerCAmelCase ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(_lowerCAmelCase , _lowerCAmelCase , _PatchedModuleObj(getattr(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) , attrs=self.attrs ) ) UpperCAmelCase__ : Union[str, Any] = getattr(_lowerCAmelCase , _lowerCAmelCase ) # finally set the target attribute setattr(_lowerCAmelCase , _lowerCAmelCase , self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: UpperCAmelCase__ : Union[str, Any] = getattr(import_module(""".""".join(_lowerCAmelCase ) ) , _lowerCAmelCase ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj , _lowerCAmelCase ) is attr_value: UpperCAmelCase__ : Optional[int] = getattr(self.obj , _lowerCAmelCase ) setattr(self.obj , _lowerCAmelCase , self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" UpperCAmelCase__ : Dict = globals()["""__builtins__"""][target_attr] setattr(self.obj , _lowerCAmelCase , self.new ) else: raise RuntimeError(f"Tried to patch attribute {target_attr} instead of a submodule." ) def __exit__( self , *_lowerCAmelCase ): for attr in list(self.original ): setattr(self.obj , _lowerCAmelCase , self.original.pop(_lowerCAmelCase ) ) def __UpperCAmelCase ( self ): self.__enter__() self._active_patches.append(self ) def __UpperCAmelCase ( self ): try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
79
1
import requests SCREAMING_SNAKE_CASE__ : Optional[Any] = """""" # <-- Put your OpenWeatherMap appid here! SCREAMING_SNAKE_CASE__ : Optional[int] = """https://api.openweathermap.org/data/2.5/""" def _lowerCamelCase ( __lowerCamelCase = "Chicago" , __lowerCamelCase = APPID ) -> dict: '''simple docstring''' return requests.get(URL_BASE + """weather""" , params=locals() ).json() def _lowerCamelCase ( __lowerCamelCase = "Kolkata, India" , __lowerCamelCase = APPID ) -> dict: '''simple docstring''' return requests.get(URL_BASE + """forecast""" , params=locals() ).json() def _lowerCamelCase ( __lowerCamelCase = 55.68 , __lowerCamelCase = 12.57 , __lowerCamelCase = APPID ) -> dict: '''simple docstring''' return requests.get(URL_BASE + """onecall""" , params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: SCREAMING_SNAKE_CASE__ : int = input("""Enter a location:""").strip() if location: pprint(current_weather(location)) else: break
79
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : str = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { """huggingface/informer-tourism-monthly""": ( """https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json""" ), # See all Informer models at https://huggingface.co/models?filter=informer } class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = 'informer' __lowerCamelCase = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = "student_t" , _lowerCAmelCase = "nll" , _lowerCAmelCase = 1 , _lowerCAmelCase = None , _lowerCAmelCase = "mean" , _lowerCAmelCase = 0 , _lowerCAmelCase = 0 , _lowerCAmelCase = 0 , _lowerCAmelCase = 0 , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = 64 , _lowerCAmelCase = 32 , _lowerCAmelCase = 32 , _lowerCAmelCase = 2 , _lowerCAmelCase = 2 , _lowerCAmelCase = 2 , _lowerCAmelCase = 2 , _lowerCAmelCase = True , _lowerCAmelCase = "gelu" , _lowerCAmelCase = 0.0_5 , _lowerCAmelCase = 0.1 , _lowerCAmelCase = 0.1 , _lowerCAmelCase = 0.1 , _lowerCAmelCase = 0.1 , _lowerCAmelCase = 100 , _lowerCAmelCase = 0.0_2 , _lowerCAmelCase=True , _lowerCAmelCase = "prob" , _lowerCAmelCase = 5 , _lowerCAmelCase = True , **_lowerCAmelCase , ): # time series specific configuration UpperCAmelCase__ : List[str] = prediction_length UpperCAmelCase__ : Optional[Any] = context_length or prediction_length UpperCAmelCase__ : str = distribution_output UpperCAmelCase__ : int = loss UpperCAmelCase__ : Optional[Any] = input_size UpperCAmelCase__ : Any = num_time_features UpperCAmelCase__ : int = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7] UpperCAmelCase__ : Union[str, Any] = scaling UpperCAmelCase__ : Optional[Any] = num_dynamic_real_features UpperCAmelCase__ : List[str] = num_static_real_features UpperCAmelCase__ : str = num_static_categorical_features # set cardinality if cardinality and num_static_categorical_features > 0: if len(_lowerCAmelCase ) != num_static_categorical_features: raise ValueError( """The cardinality should be a list of the same length as `num_static_categorical_features`""" ) UpperCAmelCase__ : List[str] = cardinality else: UpperCAmelCase__ : Optional[Any] = [0] # set embedding_dimension if embedding_dimension and num_static_categorical_features > 0: if len(_lowerCAmelCase ) != num_static_categorical_features: raise ValueError( """The embedding dimension should be a list of the same length as `num_static_categorical_features`""" ) UpperCAmelCase__ : str = embedding_dimension else: UpperCAmelCase__ : List[str] = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] UpperCAmelCase__ : Union[str, Any] = num_parallel_samples # Transformer architecture configuration UpperCAmelCase__ : Dict = input_size * len(self.lags_sequence ) + self._number_of_features UpperCAmelCase__ : Any = d_model UpperCAmelCase__ : int = encoder_attention_heads UpperCAmelCase__ : Optional[Any] = decoder_attention_heads UpperCAmelCase__ : int = encoder_ffn_dim UpperCAmelCase__ : Tuple = decoder_ffn_dim UpperCAmelCase__ : List[Any] = encoder_layers UpperCAmelCase__ : Optional[Any] = decoder_layers UpperCAmelCase__ : Tuple = dropout UpperCAmelCase__ : int = attention_dropout UpperCAmelCase__ : List[str] = activation_dropout UpperCAmelCase__ : Any = encoder_layerdrop UpperCAmelCase__ : Union[str, Any] = decoder_layerdrop UpperCAmelCase__ : Tuple = activation_function UpperCAmelCase__ : Dict = init_std UpperCAmelCase__ : str = use_cache # Informer UpperCAmelCase__ : Union[str, Any] = attention_type UpperCAmelCase__ : int = sampling_factor UpperCAmelCase__ : Any = distil super().__init__(is_encoder_decoder=_lowerCAmelCase , **_lowerCAmelCase ) @property def __UpperCAmelCase ( self ): return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
79
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer SCREAMING_SNAKE_CASE__ : str = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : List[Any] = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} SCREAMING_SNAKE_CASE__ : Optional[Any] = { """vocab_file""": { """junnyu/roformer_chinese_small""": """https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt""", """junnyu/roformer_chinese_base""": """https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt""", """junnyu/roformer_chinese_char_small""": ( """https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt""" ), """junnyu/roformer_chinese_char_base""": ( """https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt""" ), """junnyu/roformer_small_discriminator""": ( """https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt""" ), """junnyu/roformer_small_generator""": ( """https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt""" ), } } SCREAMING_SNAKE_CASE__ : Optional[int] = { """junnyu/roformer_chinese_small""": 15_36, """junnyu/roformer_chinese_base""": 15_36, """junnyu/roformer_chinese_char_small""": 5_12, """junnyu/roformer_chinese_char_base""": 5_12, """junnyu/roformer_small_discriminator""": 1_28, """junnyu/roformer_small_generator""": 1_28, } SCREAMING_SNAKE_CASE__ : List[Any] = { """junnyu/roformer_chinese_small""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_base""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_char_small""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_char_base""": {"""do_lower_case""": True}, """junnyu/roformer_small_discriminator""": {"""do_lower_case""": True}, """junnyu/roformer_small_generator""": {"""do_lower_case""": True}, } class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = VOCAB_FILES_NAMES __lowerCamelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase = PRETRAINED_INIT_CONFIGURATION __lowerCamelCase = RoFormerTokenizer def __init__( self , _lowerCAmelCase=None , _lowerCAmelCase=None , _lowerCAmelCase=True , _lowerCAmelCase="[UNK]" , _lowerCAmelCase="[SEP]" , _lowerCAmelCase="[PAD]" , _lowerCAmelCase="[CLS]" , _lowerCAmelCase="[MASK]" , _lowerCAmelCase=True , _lowerCAmelCase=None , **_lowerCAmelCase , ): super().__init__( _lowerCAmelCase , tokenizer_file=_lowerCAmelCase , do_lower_case=_lowerCAmelCase , unk_token=_lowerCAmelCase , sep_token=_lowerCAmelCase , pad_token=_lowerCAmelCase , cls_token=_lowerCAmelCase , mask_token=_lowerCAmelCase , tokenize_chinese_chars=_lowerCAmelCase , strip_accents=_lowerCAmelCase , **_lowerCAmelCase , ) UpperCAmelCase__ : Union[str, Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("""lowercase""" , _lowerCAmelCase ) != do_lower_case or pre_tok_state.get("""strip_accents""" , _lowerCAmelCase ) != strip_accents ): UpperCAmelCase__ : Union[str, Any] = getattr(_lowerCAmelCase , pre_tok_state.pop("""type""" ) ) UpperCAmelCase__ : List[Any] = do_lower_case UpperCAmelCase__ : Union[str, Any] = strip_accents UpperCAmelCase__ : Tuple = pre_tok_class(**_lowerCAmelCase ) UpperCAmelCase__ : Dict = do_lower_case def __getstate__( self ): UpperCAmelCase__ : Any = self.__dict__.copy() UpperCAmelCase__ : int = BertPreTokenizer() return state def __setstate__( self , _lowerCAmelCase ): UpperCAmelCase__ : List[str] = d UpperCAmelCase__ : str = self.__dict__["""_tokenizer"""].get_vocab() UpperCAmelCase__ : Optional[Any] = PreTokenizer.custom(JiebaPreTokenizer(_lowerCAmelCase ) ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase=None ): UpperCAmelCase__ : List[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 __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase = None ): UpperCAmelCase__ : List[Any] = [self.sep_token_id] UpperCAmelCase__ : 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 ) * [0] + len(token_ids_a + sep ) * [1] def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase = None ): UpperCAmelCase__ : Dict = self._tokenizer.model.save(_lowerCAmelCase , name=_lowerCAmelCase ) return tuple(_lowerCAmelCase ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase=None , _lowerCAmelCase=None , _lowerCAmelCase=False , **_lowerCAmelCase , ): UpperCAmelCase__ : List[str] = BertPreTokenizer() return super().save_pretrained(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , **_lowerCAmelCase )
79
def _lowerCamelCase ( __lowerCamelCase ) -> bool: '''simple docstring''' if p < 2: raise ValueError("""p should not be less than 2!""" ) elif p == 2: return True UpperCAmelCase__ : Tuple = 4 UpperCAmelCase__ : Tuple = (1 << p) - 1 for _ in range(p - 2 ): UpperCAmelCase__ : List[str] = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
79
1
import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_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_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset SCREAMING_SNAKE_CASE__ : int = random.Random() def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase=1.0 , __lowerCamelCase=None , __lowerCamelCase=None ) -> Tuple: '''simple docstring''' if rng is None: UpperCAmelCase__ : Tuple = global_rng UpperCAmelCase__ : List[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCAmelCase_ ( unittest.TestCase ): def __init__( self , _lowerCAmelCase , _lowerCAmelCase=7 , _lowerCAmelCase=400 , _lowerCAmelCase=2000 , _lowerCAmelCase=2048 , _lowerCAmelCase=128 , _lowerCAmelCase=1 , _lowerCAmelCase=512 , _lowerCAmelCase=30 , _lowerCAmelCase=44100 , ): UpperCAmelCase__ : List[str] = parent UpperCAmelCase__ : List[str] = batch_size UpperCAmelCase__ : Optional[Any] = min_seq_length UpperCAmelCase__ : Tuple = max_seq_length UpperCAmelCase__ : Optional[Any] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) UpperCAmelCase__ : List[Any] = spectrogram_length UpperCAmelCase__ : int = feature_size UpperCAmelCase__ : int = num_audio_channels UpperCAmelCase__ : str = hop_length UpperCAmelCase__ : str = chunk_length UpperCAmelCase__ : Any = sampling_rate def __UpperCAmelCase ( self ): return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def __UpperCAmelCase ( self , _lowerCAmelCase=False , _lowerCAmelCase=False ): def _flatten(_lowerCAmelCase ): return list(itertools.chain(*_lowerCAmelCase ) ) if equal_length: UpperCAmelCase__ : str = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size UpperCAmelCase__ : int = [ 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__ : Optional[Any] = [np.asarray(_lowerCAmelCase ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class UpperCAmelCase_ ( __lowerCamelCase , unittest.TestCase ): __lowerCamelCase = TvltFeatureExtractor def __UpperCAmelCase ( self ): UpperCAmelCase__ : Tuple = TvltFeatureExtractionTester(self ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : str = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(_lowerCAmelCase , """spectrogram_length""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """feature_size""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """num_audio_channels""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """hop_length""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """chunk_length""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """sampling_rate""" ) ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[str] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase__ : str = feat_extract_first.save_pretrained(_lowerCAmelCase )[0] check_json_file_has_correct_format(_lowerCAmelCase ) UpperCAmelCase__ : Tuple = self.feature_extraction_class.from_pretrained(_lowerCAmelCase ) UpperCAmelCase__ : Any = feat_extract_first.to_dict() UpperCAmelCase__ : Optional[Any] = feat_extract_second.to_dict() UpperCAmelCase__ : Optional[Any] = dict_first.pop("""mel_filters""" ) UpperCAmelCase__ : List[Any] = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(_lowerCAmelCase , _lowerCAmelCase ) ) self.assertEqual(_lowerCAmelCase , _lowerCAmelCase ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : int = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase__ : List[str] = os.path.join(_lowerCAmelCase , """feat_extract.json""" ) feat_extract_first.to_json_file(_lowerCAmelCase ) UpperCAmelCase__ : List[str] = self.feature_extraction_class.from_json_file(_lowerCAmelCase ) UpperCAmelCase__ : str = feat_extract_first.to_dict() UpperCAmelCase__ : List[str] = feat_extract_second.to_dict() UpperCAmelCase__ : Optional[Any] = dict_first.pop("""mel_filters""" ) UpperCAmelCase__ : Optional[Any] = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(_lowerCAmelCase , _lowerCAmelCase ) ) self.assertEqual(_lowerCAmelCase , _lowerCAmelCase ) def __UpperCAmelCase ( self ): # Initialize feature_extractor UpperCAmelCase__ : List[str] = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 UpperCAmelCase__ : int = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] UpperCAmelCase__ : Optional[Any] = [np.asarray(_lowerCAmelCase ) for speech_input in speech_inputs] # Test not batched input UpperCAmelCase__ : int = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" , sampling_rate=44100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched UpperCAmelCase__ : Dict = feature_extractor(_lowerCAmelCase , return_tensors="""np""" , sampling_rate=44100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking UpperCAmelCase__ : Tuple = feature_extractor( _lowerCAmelCase , return_tensors="""np""" , sampling_rate=44100 , mask_audio=_lowerCAmelCase ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. UpperCAmelCase__ : Any = [floats_list((1, x) )[0] for x in (800, 800, 800)] UpperCAmelCase__ : Optional[int] = np.asarray(_lowerCAmelCase ) UpperCAmelCase__ : int = feature_extractor(_lowerCAmelCase , return_tensors="""np""" , sampling_rate=44100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def __UpperCAmelCase ( self , _lowerCAmelCase ): UpperCAmelCase__ : List[str] = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech UpperCAmelCase__ : str = ds.sort("""id""" ).select(range(_lowerCAmelCase ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def __UpperCAmelCase ( self ): UpperCAmelCase__ : int = self._load_datasamples(1 ) UpperCAmelCase__ : Dict = TvltFeatureExtractor() UpperCAmelCase__ : int = feature_extractor(_lowerCAmelCase , return_tensors="""pt""" ).audio_values self.assertEquals(audio_values.shape , (1, 1, 192, 128) ) UpperCAmelCase__ : Union[str, Any] = torch.tensor([[-0.3_0_3_2, -0.2_7_0_8], [-0.4_4_3_4, -0.4_0_0_7]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] , _lowerCAmelCase , atol=1e-4 ) )
79
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE__ : Any = { """configuration_mobilevit""": ["""MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MobileViTConfig""", """MobileViTOnnxConfig"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["""MobileViTFeatureExtractor"""] SCREAMING_SNAKE_CASE__ : Union[str, Any] = ["""MobileViTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Dict = [ """MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """MobileViTForImageClassification""", """MobileViTForSemanticSegmentation""", """MobileViTModel""", """MobileViTPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Any = [ """TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFMobileViTForImageClassification""", """TFMobileViTForSemanticSegmentation""", """TFMobileViTModel""", """TFMobileViTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilevit import MobileViTFeatureExtractor from .image_processing_mobilevit import MobileViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilevit import ( MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel, MobileViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilevit import ( TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel, TFMobileViTPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
79
1
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = 42 __lowerCamelCase = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer 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 StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.26.0""")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version(""">=""", """0.0.12""") ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = 42 __lowerCamelCase = 42 from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
79
from __future__ import annotations SCREAMING_SNAKE_CASE__ : List[str] = 8.988e9 # units = N * m^s * C^-2 def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> dict[str, float]: '''simple docstring''' UpperCAmelCase__ : int = abs(chargea * chargea ) if (force, chargea, chargea, distance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if distance < 0: raise ValueError("""Distance cannot be negative""" ) if force == 0: UpperCAmelCase__ : int = COULOMBS_CONSTANT * charge_product / (distance**2) return {"force": force} elif chargea == 0: UpperCAmelCase__ : str = abs(__lowerCamelCase ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge1": chargea} elif chargea == 0: UpperCAmelCase__ : Union[str, Any] = abs(__lowerCamelCase ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge2": chargea} elif distance == 0: UpperCAmelCase__ : Optional[Any] = (COULOMBS_CONSTANT * charge_product / abs(__lowerCamelCase )) ** 0.5 return {"distance": distance} raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
79
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Tuple = { """configuration_gpt_bigcode""": ["""GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTBigCodeConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ """GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTBigCodeForSequenceClassification""", """GPTBigCodeForTokenClassification""", """GPTBigCodeForCausalLM""", """GPTBigCodeModel""", """GPTBigCodePreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Any = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
79
class UpperCAmelCase_ : def __init__( self , _lowerCAmelCase ): # we need a list not a string, so do something to change the type UpperCAmelCase__ : Dict = arr.split(""",""" ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Tuple = [int(self.array[0] )] * len(self.array ) UpperCAmelCase__ : List[str] = [int(self.array[0] )] * len(self.array ) for i in range(1 , len(self.array ) ): UpperCAmelCase__ : Tuple = max( int(self.array[i] ) + sum_value[i - 1] , int(self.array[i] ) ) UpperCAmelCase__ : Union[str, Any] = max(sum_value[i] , rear[i - 1] ) return rear[len(self.array ) - 1] if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Tuple = input("""please input some numbers:""") SCREAMING_SNAKE_CASE__ : Dict = SubArray(whole_array) SCREAMING_SNAKE_CASE__ : Dict = array.solve_sub_array() print(("""the results is:""", re))
79
1
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path SCREAMING_SNAKE_CASE__ : Optional[Any] = [ {"""dataset""": """wikipedia""", """config_name""": """20220301.de"""}, {"""dataset""": """wikipedia""", """config_name""": """20220301.en"""}, {"""dataset""": """wikipedia""", """config_name""": """20220301.fr"""}, {"""dataset""": """wikipedia""", """config_name""": """20220301.frr"""}, {"""dataset""": """wikipedia""", """config_name""": """20220301.it"""}, {"""dataset""": """wikipedia""", """config_name""": """20220301.simple"""}, {"""dataset""": """snli""", """config_name""": """plain_text"""}, {"""dataset""": """eli5""", """config_name""": """LFQA_reddit"""}, {"""dataset""": """wiki40b""", """config_name""": """en"""}, {"""dataset""": """wiki_dpr""", """config_name""": """psgs_w100.nq.compressed"""}, {"""dataset""": """wiki_dpr""", """config_name""": """psgs_w100.nq.no_index"""}, {"""dataset""": """wiki_dpr""", """config_name""": """psgs_w100.multiset.no_index"""}, {"""dataset""": """natural_questions""", """config_name""": """default"""}, ] def _lowerCamelCase ( __lowerCamelCase=True ) -> Union[str, Any]: '''simple docstring''' if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=__lowerCamelCase ) ) class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = None __lowerCamelCase = None def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase ): with TemporaryDirectory() as tmp_dir: UpperCAmelCase__ : Optional[int] = dataset_module_factory(_lowerCAmelCase , cache_dir=_lowerCAmelCase ) UpperCAmelCase__ : int = import_main_class(dataset_module.module_path , dataset=_lowerCAmelCase ) UpperCAmelCase__ : DatasetBuilder = builder_cls( cache_dir=_lowerCAmelCase , config_name=_lowerCAmelCase , hash=dataset_module.hash , ) UpperCAmelCase__ : str = """/""".join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=_lowerCAmelCase ).replace(os.sep , """/""" ), config.DATASET_INFO_FILENAME, ] ) UpperCAmelCase__ : List[str] = cached_path(_lowerCAmelCase , cache_dir=_lowerCAmelCase ) self.assertTrue(os.path.exists(_lowerCAmelCase ) ) @pytest.mark.integration def _lowerCamelCase ( __lowerCamelCase ) -> str: '''simple docstring''' UpperCAmelCase__ : Dict = tmp_path_factory.mktemp("""test_hf_gcp""" ) / """test_wikipedia_simple""" UpperCAmelCase__ : List[str] = dataset_module_factory("""wikipedia""" , cache_dir=__lowerCamelCase ) UpperCAmelCase__ : Optional[int] = import_main_class(dataset_module.module_path ) UpperCAmelCase__ : DatasetBuilder = builder_cls( cache_dir=__lowerCamelCase , config_name="""20220301.frr""" , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam UpperCAmelCase__ : Dict = None builder_instance.download_and_prepare() UpperCAmelCase__ : int = builder_instance.as_dataset() assert ds @pytest.mark.integration def _lowerCamelCase ( __lowerCamelCase ) -> List[Any]: '''simple docstring''' UpperCAmelCase__ : Tuple = dataset_module_factory("""wikipedia""" , cache_dir=__lowerCamelCase ) UpperCAmelCase__ : int = import_main_class(dataset_module.module_path , dataset=__lowerCamelCase ) UpperCAmelCase__ : DatasetBuilder = builder_cls( cache_dir=__lowerCamelCase , config_name="""20220301.frr""" , hash=dataset_module.hash , ) UpperCAmelCase__ : Dict = builder_instance.as_streaming_dataset() assert ds assert isinstance(__lowerCamelCase , __lowerCamelCase ) assert "train" in ds assert isinstance(ds["""train"""] , __lowerCamelCase ) assert next(iter(ds["""train"""] ) )
79
from ....configuration_utils import PretrainedConfig from ....utils import logging SCREAMING_SNAKE_CASE__ : List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { """Visual-Attention-Network/van-base""": ( """https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json""" ), } class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = 'van' def __init__( self , _lowerCAmelCase=224 , _lowerCAmelCase=3 , _lowerCAmelCase=[7, 3, 3, 3] , _lowerCAmelCase=[4, 2, 2, 2] , _lowerCAmelCase=[64, 128, 320, 512] , _lowerCAmelCase=[3, 3, 12, 3] , _lowerCAmelCase=[8, 8, 4, 4] , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.0_2 , _lowerCAmelCase=1e-6 , _lowerCAmelCase=1e-2 , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.0 , **_lowerCAmelCase , ): super().__init__(**_lowerCAmelCase ) UpperCAmelCase__ : Tuple = image_size UpperCAmelCase__ : Optional[Any] = num_channels UpperCAmelCase__ : Optional[int] = patch_sizes UpperCAmelCase__ : int = strides UpperCAmelCase__ : Optional[int] = hidden_sizes UpperCAmelCase__ : str = depths UpperCAmelCase__ : Optional[Any] = mlp_ratios UpperCAmelCase__ : List[Any] = hidden_act UpperCAmelCase__ : Tuple = initializer_range UpperCAmelCase__ : Any = layer_norm_eps UpperCAmelCase__ : List[Any] = layer_scale_init_value UpperCAmelCase__ : int = drop_path_rate UpperCAmelCase__ : Dict = dropout_rate
79
1
import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : Dict = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right SCREAMING_SNAKE_CASE__ : str = 25_60_47 SCREAMING_SNAKE_CASE__ : Optional[int] = 25_61_45 @require_sentencepiece @require_tokenizers class UpperCAmelCase_ ( __lowerCamelCase , unittest.TestCase ): __lowerCamelCase = NllbTokenizer __lowerCamelCase = NllbTokenizerFast __lowerCamelCase = True __lowerCamelCase = True __lowerCamelCase = {} def __UpperCAmelCase ( self ): super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase__ : Any = NllbTokenizer(_lowerCAmelCase , keep_accents=_lowerCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = NllbTokenizer(_lowerCAmelCase , keep_accents=_lowerCAmelCase ) UpperCAmelCase__ : Optional[Any] = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(_lowerCAmelCase , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) UpperCAmelCase__ : List[Any] = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( _lowerCAmelCase , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) UpperCAmelCase__ : Optional[int] = tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) self.assertListEqual( _lowerCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) UpperCAmelCase__ : str = tokenizer.convert_ids_to_tokens(_lowerCAmelCase ) self.assertListEqual( _lowerCAmelCase , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : str = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-nllb""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCAmelCase__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) UpperCAmelCase__ : str = self.tokenizer_class.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) UpperCAmelCase__ : Dict = tempfile.mkdtemp() UpperCAmelCase__ : int = tokenizer_r.save_pretrained(_lowerCAmelCase ) UpperCAmelCase__ : Dict = tokenizer_p.save_pretrained(_lowerCAmelCase ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) UpperCAmelCase__ : Tuple = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(_lowerCAmelCase , _lowerCAmelCase ) # Checks everything loads correctly in the same way UpperCAmelCase__ : str = tokenizer_r.from_pretrained(_lowerCAmelCase ) UpperCAmelCase__ : Tuple = tokenizer_p.from_pretrained(_lowerCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_lowerCAmelCase , _lowerCAmelCase ) ) shutil.rmtree(_lowerCAmelCase ) # Save tokenizer rust, legacy_format=True UpperCAmelCase__ : List[str] = tempfile.mkdtemp() UpperCAmelCase__ : Union[str, Any] = tokenizer_r.save_pretrained(_lowerCAmelCase , legacy_format=_lowerCAmelCase ) UpperCAmelCase__ : int = tokenizer_p.save_pretrained(_lowerCAmelCase ) # Checks it save with the same files self.assertSequenceEqual(_lowerCAmelCase , _lowerCAmelCase ) # Checks everything loads correctly in the same way UpperCAmelCase__ : int = tokenizer_r.from_pretrained(_lowerCAmelCase ) UpperCAmelCase__ : List[Any] = tokenizer_p.from_pretrained(_lowerCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_lowerCAmelCase , _lowerCAmelCase ) ) shutil.rmtree(_lowerCAmelCase ) # Save tokenizer rust, legacy_format=False UpperCAmelCase__ : Optional[Any] = tempfile.mkdtemp() UpperCAmelCase__ : List[str] = tokenizer_r.save_pretrained(_lowerCAmelCase , legacy_format=_lowerCAmelCase ) UpperCAmelCase__ : Optional[int] = tokenizer_p.save_pretrained(_lowerCAmelCase ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way UpperCAmelCase__ : int = tokenizer_r.from_pretrained(_lowerCAmelCase ) UpperCAmelCase__ : str = tokenizer_p.from_pretrained(_lowerCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(_lowerCAmelCase , _lowerCAmelCase ) ) shutil.rmtree(_lowerCAmelCase ) @require_torch def __UpperCAmelCase ( self ): if not self.test_seqaseq: return UpperCAmelCase__ : Optional[int] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): # Longer text that will definitely require truncation. UpperCAmelCase__ : Optional[Any] = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for""" """ Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons""" """ will only worsen the violence and misery for millions of people.""", ] UpperCAmelCase__ : Optional[int] = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al""" """ Rusiei pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi""" """ că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] try: UpperCAmelCase__ : Union[str, Any] = tokenizer.prepare_seqaseq_batch( src_texts=_lowerCAmelCase , tgt_texts=_lowerCAmelCase , max_length=3 , max_target_length=10 , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified UpperCAmelCase__ : Optional[Any] = tokenizer.prepare_seqaseq_batch( _lowerCAmelCase , tgt_texts=_lowerCAmelCase , max_length=3 , return_tensors="""pt""" ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) UpperCAmelCase__ : Tuple = tokenizer.prepare_seqaseq_batch( src_texts=_lowerCAmelCase , max_length=3 , max_target_length=10 , return_tensors="""pt""" ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn("""decoder_input_ids""" , _lowerCAmelCase ) @unittest.skip("""Unfortunately way too slow to build a BPE with SentencePiece.""" ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCAmelCase__ : int = [AddedToken("""<special>""" , lstrip=_lowerCAmelCase )] UpperCAmelCase__ : Any = self.rust_tokenizer_class.from_pretrained( _lowerCAmelCase , additional_special_tokens=_lowerCAmelCase , **_lowerCAmelCase ) UpperCAmelCase__ : str = tokenizer_r.encode("""Hey this is a <special> token""" ) UpperCAmelCase__ : Optional[Any] = tokenizer_r.encode("""<special>""" , add_special_tokens=_lowerCAmelCase )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: UpperCAmelCase__ : int = self.rust_tokenizer_class.from_pretrained( _lowerCAmelCase , additional_special_tokens=_lowerCAmelCase , **_lowerCAmelCase , ) UpperCAmelCase__ : Any = self.tokenizer_class.from_pretrained( _lowerCAmelCase , additional_special_tokens=_lowerCAmelCase , **_lowerCAmelCase ) UpperCAmelCase__ : Optional[Any] = tokenizer_p.encode("""Hey this is a <special> token""" ) UpperCAmelCase__ : Dict = tokenizer_cr.encode("""Hey this is a <special> token""" ) self.assertEqual(_lowerCAmelCase , _lowerCAmelCase ) self.assertEqual(_lowerCAmelCase , _lowerCAmelCase ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class UpperCAmelCase_ ( unittest.TestCase ): __lowerCamelCase = 'facebook/nllb-200-distilled-600M' __lowerCamelCase = [ ' UN Chief Says There Is No Military Solution in Syria', ' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.', ] __lowerCamelCase = [ 'Şeful ONU declară că nu există o soluţie militară în Siria', 'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei' ' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor' ' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.', ] __lowerCamelCase = [ 256_047, 16_297, 134_408, 8_165, 248_066, 14_734, 950, 1_135, 105_721, 3_573, 83, 27_352, 108, 49_486, 2, ] @classmethod def __UpperCAmelCase ( cls ): UpperCAmelCase__ : NllbTokenizer = NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""eng_Latn""" , tgt_lang="""ron_Latn""" ) UpperCAmelCase__ : Union[str, Any] = 1 return cls def __UpperCAmelCase ( self ): self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Arab"""] , 256001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ace_Latn"""] , 256002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""fra_Latn"""] , 256057 ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[str] = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , _lowerCAmelCase ) def __UpperCAmelCase ( self ): self.assertIn(_lowerCAmelCase , self.tokenizer.all_special_ids ) # fmt: off UpperCAmelCase__ : Union[str, Any] = [RO_CODE, 4254, 98068, 112923, 39072, 3909, 713, 102767, 26, 17314, 35642, 14683, 33118, 2022, 66987, 2, 256047] # fmt: on UpperCAmelCase__ : Optional[Any] = self.tokenizer.decode(_lowerCAmelCase , skip_special_tokens=_lowerCAmelCase ) UpperCAmelCase__ : Tuple = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=_lowerCAmelCase ) self.assertEqual(_lowerCAmelCase , _lowerCAmelCase ) self.assertNotIn(self.tokenizer.eos_token , _lowerCAmelCase ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[Any] = ["""this is gunna be a long sentence """ * 20] assert isinstance(src_text[0] , _lowerCAmelCase ) UpperCAmelCase__ : Any = 10 UpperCAmelCase__ : Dict = self.tokenizer(_lowerCAmelCase , max_length=_lowerCAmelCase , truncation=_lowerCAmelCase ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , _lowerCAmelCase ) self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase ) def __UpperCAmelCase ( self ): self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [256203, 3] ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Dict = tempfile.mkdtemp() UpperCAmelCase__ : Union[str, Any] = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(_lowerCAmelCase ) UpperCAmelCase__ : List[str] = NllbTokenizer.from_pretrained(_lowerCAmelCase ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , _lowerCAmelCase ) @require_torch def __UpperCAmelCase ( self ): UpperCAmelCase__ : Union[str, Any] = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=_lowerCAmelCase , truncation=_lowerCAmelCase , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) UpperCAmelCase__ : Optional[int] = shift_tokens_right( batch["""labels"""] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id["""ron_Latn"""] ) self.assertIsInstance(_lowerCAmelCase , _lowerCAmelCase ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) UpperCAmelCase__ : Union[str, Any] = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , _lowerCAmelCase ) self.assertEqual(_lowerCAmelCase , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = self.tokenizer(self.src_text , padding=_lowerCAmelCase , truncation=_lowerCAmelCase , max_length=3 , return_tensors="""pt""" ) UpperCAmelCase__ : Optional[int] = self.tokenizer( text_target=self.tgt_text , padding=_lowerCAmelCase , truncation=_lowerCAmelCase , max_length=10 , return_tensors="""pt""" ) UpperCAmelCase__ : List[Any] = targets["""input_ids"""] UpperCAmelCase__ : Dict = shift_tokens_right( _lowerCAmelCase , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def __UpperCAmelCase ( self ): UpperCAmelCase__ : Union[str, Any] = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( nested_simplify(_lowerCAmelCase ) , { # A, test, EOS, en_XX """input_ids""": [[256047, 70, 7356, 2]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 256057, } , ) @require_torch def __UpperCAmelCase ( self ): UpperCAmelCase__ : int = True UpperCAmelCase__ : Tuple = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [16297, 134408, 25653, 6370, 248, 254, 103929, 94995, 108, 49486, 2, 256047] ) UpperCAmelCase__ : int = False UpperCAmelCase__ : Tuple = self.tokenizer( """UN Chief says there is no military solution in Syria""" , src_lang="""eng_Latn""" , tgt_lang="""fra_Latn""" ) self.assertEqual( inputs.input_ids , [256047, 16297, 134408, 25653, 6370, 248, 254, 103929, 94995, 108, 49486, 2] )
79
import argparse import os import torch from transformers import FlavaImageCodebook, FlavaImageCodebookConfig def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Any: '''simple docstring''' UpperCAmelCase__ : List[str] = s.rsplit(__lowerCamelCase , __lowerCamelCase ) return new.join(__lowerCamelCase ) def _lowerCamelCase ( __lowerCamelCase ) -> str: '''simple docstring''' # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if """encoder.embeddings""" not in key else 0 for key, param in state_dict.items() ) def _lowerCamelCase ( __lowerCamelCase ) -> int: '''simple docstring''' UpperCAmelCase__ : Union[str, Any] = {} UpperCAmelCase__ : Union[str, Any] = ["""group_1""", """group_2""", """group_3""", """group_4"""] for key, value in state_dict.items(): for group_key in group_keys: if group_key in key: UpperCAmelCase__ : Optional[Any] = key.replace(F"{group_key}." , F"{group_key}.group." ) if "res_path" in key: UpperCAmelCase__ : Optional[int] = key.replace("""res_path.""" , """res_path.path.""" ) if key.endswith(""".w""" ): UpperCAmelCase__ : List[Any] = rreplace(__lowerCamelCase , """.w""" , """.weight""" , 1 ) if key.endswith(""".b""" ): UpperCAmelCase__ : Optional[int] = rreplace(__lowerCamelCase , """.b""" , """.bias""" , 1 ) UpperCAmelCase__ : Union[str, Any] = value.float() return upgrade @torch.no_grad() def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=True ) -> str: '''simple docstring''' from dall_e import Encoder UpperCAmelCase__ : Dict = Encoder() if os.path.exists(__lowerCamelCase ): UpperCAmelCase__ : Optional[Any] = torch.load(__lowerCamelCase ) else: UpperCAmelCase__ : Tuple = torch.hub.load_state_dict_from_url(__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ): UpperCAmelCase__ : Any = ckpt.state_dict() encoder.load_state_dict(__lowerCamelCase ) if config_path is not None: UpperCAmelCase__ : Dict = FlavaImageCodebookConfig.from_pretrained(__lowerCamelCase ) else: UpperCAmelCase__ : Optional[Any] = FlavaImageCodebookConfig() UpperCAmelCase__ : Optional[Any] = FlavaImageCodebook(__lowerCamelCase ).eval() UpperCAmelCase__ : str = encoder.state_dict() UpperCAmelCase__ : Optional[int] = upgrade_state_dict(__lowerCamelCase ) hf_model.load_state_dict(__lowerCamelCase ) UpperCAmelCase__ : List[str] = hf_model.state_dict() UpperCAmelCase__ : Tuple = count_parameters(__lowerCamelCase ) UpperCAmelCase__ : int = count_parameters(__lowerCamelCase ) assert torch.allclose(__lowerCamelCase , __lowerCamelCase , atol=1E-3 ) if save_checkpoint: hf_model.save_pretrained(__lowerCamelCase ) else: return hf_state_dict if __name__ == "__main__": SCREAMING_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 flava checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") SCREAMING_SNAKE_CASE__ : int = parser.parse_args() convert_dalle_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
79
1
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : List[Any] = { """MIT/ast-finetuned-audioset-10-10-0.4593""": ( """https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json""" ), } class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = 'audio-spectrogram-transformer' def __init__( self , _lowerCAmelCase=768 , _lowerCAmelCase=12 , _lowerCAmelCase=12 , _lowerCAmelCase=3072 , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.0_2 , _lowerCAmelCase=1e-12 , _lowerCAmelCase=16 , _lowerCAmelCase=True , _lowerCAmelCase=10 , _lowerCAmelCase=10 , _lowerCAmelCase=1024 , _lowerCAmelCase=128 , **_lowerCAmelCase , ): super().__init__(**_lowerCAmelCase ) UpperCAmelCase__ : Optional[int] = hidden_size UpperCAmelCase__ : int = num_hidden_layers UpperCAmelCase__ : List[Any] = num_attention_heads UpperCAmelCase__ : Dict = intermediate_size UpperCAmelCase__ : Dict = hidden_act UpperCAmelCase__ : str = hidden_dropout_prob UpperCAmelCase__ : str = attention_probs_dropout_prob UpperCAmelCase__ : Tuple = initializer_range UpperCAmelCase__ : Dict = layer_norm_eps UpperCAmelCase__ : Optional[Any] = patch_size UpperCAmelCase__ : Tuple = qkv_bias UpperCAmelCase__ : Tuple = frequency_stride UpperCAmelCase__ : Union[str, Any] = time_stride UpperCAmelCase__ : Optional[Any] = max_length UpperCAmelCase__ : Optional[int] = num_mel_bins
79
def _lowerCamelCase ( __lowerCamelCase ) -> int: '''simple docstring''' return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def _lowerCamelCase ( __lowerCamelCase ) -> bool: '''simple docstring''' UpperCAmelCase__ : Any = 0 UpperCAmelCase__ : Union[str, Any] = number while duplicate > 0: UpperCAmelCase__ , UpperCAmelCase__ : List[Any] = divmod(__lowerCamelCase , 10 ) fact_sum += factorial(__lowerCamelCase ) return fact_sum == number if __name__ == "__main__": print("""Program to check whether a number is a Krisnamurthy Number or not.""") SCREAMING_SNAKE_CASE__ : Optional[Any] = int(input("""Enter number: """).strip()) print( f'''{number} is {"" if krishnamurthy(number) else "not "}a Krishnamurthy Number.''' )
79
1
# Copyright 2023 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. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available SCREAMING_SNAKE_CASE__ : List[Any] = { """configuration_vivit""": ["""VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """VivitConfig"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = ["""VivitImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Dict = [ """VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """VivitModel""", """VivitPreTrainedModel""", """VivitForVideoClassification""", ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
79
def _lowerCamelCase ( __lowerCamelCase = 100_0000 ) -> int: '''simple docstring''' UpperCAmelCase__ : Tuple = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , __lowerCamelCase ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
79
1
from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def _lowerCamelCase ( __lowerCamelCase ) -> Union[str, Any]: '''simple docstring''' return getitem, k def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase ) -> Optional[int]: '''simple docstring''' return setitem, k, v def _lowerCamelCase ( __lowerCamelCase ) -> List[Any]: '''simple docstring''' return delitem, k def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , *__lowerCamelCase ) -> Dict: '''simple docstring''' try: return fun(__lowerCamelCase , *__lowerCamelCase ), None except Exception as e: return None, e SCREAMING_SNAKE_CASE__ : int = ( _set("""key_a""", """val_a"""), _set("""key_b""", """val_b"""), ) SCREAMING_SNAKE_CASE__ : str = [ _set("""key_a""", """val_a"""), _set("""key_a""", """val_b"""), ] SCREAMING_SNAKE_CASE__ : int = [ _set("""key_a""", """val_a"""), _set("""key_b""", """val_b"""), _del("""key_a"""), _del("""key_b"""), _set("""key_a""", """val_a"""), _del("""key_a"""), ] SCREAMING_SNAKE_CASE__ : List[str] = [ _get("""key_a"""), _del("""key_a"""), _set("""key_a""", """val_a"""), _del("""key_a"""), _del("""key_a"""), _get("""key_a"""), ] SCREAMING_SNAKE_CASE__ : List[Any] = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] SCREAMING_SNAKE_CASE__ : Optional[int] = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set("""key_a""", """val_b"""), ] @pytest.mark.parametrize( """operations""" , ( pytest.param(_add_items , id="""add items""" ), pytest.param(_overwrite_items , id="""overwrite items""" ), pytest.param(_delete_items , id="""delete items""" ), pytest.param(_access_absent_items , id="""access absent items""" ), pytest.param(_add_with_resize_up , id="""add with resize up""" ), pytest.param(_add_with_resize_down , id="""add with resize down""" ), ) , ) def _lowerCamelCase ( __lowerCamelCase ) -> List[str]: '''simple docstring''' UpperCAmelCase__ : str = HashMap(initial_block_size=4 ) UpperCAmelCase__ : Any = {} for _, (fun, *args) in enumerate(__lowerCamelCase ): UpperCAmelCase__ , UpperCAmelCase__ : List[str] = _run_operation(__lowerCamelCase , __lowerCamelCase , *__lowerCamelCase ) UpperCAmelCase__ , UpperCAmelCase__ : List[Any] = _run_operation(__lowerCamelCase , __lowerCamelCase , *__lowerCamelCase ) assert my_res == py_res assert str(__lowerCamelCase ) == str(__lowerCamelCase ) assert set(__lowerCamelCase ) == set(__lowerCamelCase ) assert len(__lowerCamelCase ) == len(__lowerCamelCase ) assert set(my.items() ) == set(py.items() ) def _lowerCamelCase ( ) -> Dict: '''simple docstring''' def is_public(__lowerCamelCase ) -> bool: return not name.startswith("""_""" ) UpperCAmelCase__ : Tuple = {name for name in dir({} ) if is_public(__lowerCamelCase )} UpperCAmelCase__ : str = {name for name in dir(HashMap() ) if is_public(__lowerCamelCase )} assert dict_public_names > hash_public_names
79
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Tuple = { """google/realm-cc-news-pretrained-embedder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-encoder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-scorer""": ( """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-openqa""": ( """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json""" ), """google/realm-orqa-nq-openqa""": """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json""", """google/realm-orqa-nq-reader""": """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json""", """google/realm-orqa-wq-openqa""": """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json""", """google/realm-orqa-wq-reader""": """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json""", # See all REALM models at https://huggingface.co/models?filter=realm } class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = 'realm' def __init__( self , _lowerCAmelCase=30522 , _lowerCAmelCase=768 , _lowerCAmelCase=128 , _lowerCAmelCase=12 , _lowerCAmelCase=12 , _lowerCAmelCase=8 , _lowerCAmelCase=3072 , _lowerCAmelCase="gelu_new" , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.1 , _lowerCAmelCase=512 , _lowerCAmelCase=2 , _lowerCAmelCase=0.0_2 , _lowerCAmelCase=1e-12 , _lowerCAmelCase=256 , _lowerCAmelCase=10 , _lowerCAmelCase=1e-3 , _lowerCAmelCase=5 , _lowerCAmelCase=320 , _lowerCAmelCase=13353718 , _lowerCAmelCase=5000 , _lowerCAmelCase=1 , _lowerCAmelCase=0 , _lowerCAmelCase=2 , **_lowerCAmelCase , ): super().__init__(pad_token_id=_lowerCAmelCase , bos_token_id=_lowerCAmelCase , eos_token_id=_lowerCAmelCase , **_lowerCAmelCase ) # Common config UpperCAmelCase__ : List[Any] = vocab_size UpperCAmelCase__ : Dict = max_position_embeddings UpperCAmelCase__ : Any = hidden_size UpperCAmelCase__ : str = retriever_proj_size UpperCAmelCase__ : Tuple = num_hidden_layers UpperCAmelCase__ : List[str] = num_attention_heads UpperCAmelCase__ : List[Any] = num_candidates UpperCAmelCase__ : str = intermediate_size UpperCAmelCase__ : str = hidden_act UpperCAmelCase__ : Optional[Any] = hidden_dropout_prob UpperCAmelCase__ : str = attention_probs_dropout_prob UpperCAmelCase__ : Union[str, Any] = initializer_range UpperCAmelCase__ : Any = type_vocab_size UpperCAmelCase__ : Optional[Any] = layer_norm_eps # Reader config UpperCAmelCase__ : str = span_hidden_size UpperCAmelCase__ : Union[str, Any] = max_span_width UpperCAmelCase__ : List[str] = reader_layer_norm_eps UpperCAmelCase__ : Dict = reader_beam_size UpperCAmelCase__ : Union[str, Any] = reader_seq_len # Retrieval config UpperCAmelCase__ : List[Any] = num_block_records UpperCAmelCase__ : List[Any] = searcher_beam_size
79
1
def _lowerCamelCase ( __lowerCamelCase = 1000 ) -> int: '''simple docstring''' UpperCAmelCase__ : List[str] = 3 UpperCAmelCase__ : Any = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 return result if __name__ == "__main__": print(f'''{solution() = }''')
79
import gc import unittest from parameterized import parameterized from diffusers import FlaxUNetaDConditionModel from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import load_hf_numpy, require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp @slow @require_flax class UpperCAmelCase_ ( unittest.TestCase ): def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase ): return f"gaussian_noise_s={seed}_shape={'_'.join([str(_lowerCAmelCase ) for s in shape] )}.npy" def __UpperCAmelCase ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() def __UpperCAmelCase ( self , _lowerCAmelCase=0 , _lowerCAmelCase=(4, 4, 64, 64) , _lowerCAmelCase=False ): UpperCAmelCase__ : Optional[Any] = jnp.bfloataa if fpaa else jnp.floataa UpperCAmelCase__ : Union[str, Any] = jnp.array(load_hf_numpy(self.get_file_format(_lowerCAmelCase , _lowerCAmelCase ) ) , dtype=_lowerCAmelCase ) return image def __UpperCAmelCase ( self , _lowerCAmelCase=False , _lowerCAmelCase="CompVis/stable-diffusion-v1-4" ): UpperCAmelCase__ : int = jnp.bfloataa if fpaa else jnp.floataa UpperCAmelCase__ : Optional[Any] = """bf16""" if fpaa else None UpperCAmelCase__ , UpperCAmelCase__ : Optional[Any] = FlaxUNetaDConditionModel.from_pretrained( _lowerCAmelCase , subfolder="""unet""" , dtype=_lowerCAmelCase , revision=_lowerCAmelCase ) return model, params def __UpperCAmelCase ( self , _lowerCAmelCase=0 , _lowerCAmelCase=(4, 77, 768) , _lowerCAmelCase=False ): UpperCAmelCase__ : Optional[int] = jnp.bfloataa if fpaa else jnp.floataa UpperCAmelCase__ : Optional[int] = jnp.array(load_hf_numpy(self.get_file_format(_lowerCAmelCase , _lowerCAmelCase ) ) , dtype=_lowerCAmelCase ) return hidden_states @parameterized.expand( [ # fmt: off [83, 4, [-0.2_3_2_3, -0.1_3_0_4, 0.0_8_1_3, -0.3_0_9_3, -0.0_9_1_9, -0.1_5_7_1, -0.1_1_2_5, -0.5_8_0_6]], [17, 0.5_5, [-0.0_8_3_1, -0.2_4_4_3, 0.0_9_0_1, -0.0_9_1_9, 0.3_3_9_6, 0.0_1_0_3, -0.3_7_4_3, 0.0_7_0_1]], [8, 0.8_9, [-0.4_8_6_3, 0.0_8_5_9, 0.0_8_7_5, -0.1_6_5_8, 0.9_1_9_9, -0.0_1_1_4, 0.4_8_3_9, 0.4_6_3_9]], [3, 1000, [-0.5_6_4_9, 0.2_4_0_2, -0.5_5_1_8, 0.1_2_4_8, 1.1_3_2_8, -0.2_4_4_3, -0.0_3_2_5, -1.0_0_7_8]], # fmt: on ] ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ , UpperCAmelCase__ : Optional[Any] = self.get_unet_model(model_id="""CompVis/stable-diffusion-v1-4""" , fpaa=_lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = self.get_latents(_lowerCAmelCase , fpaa=_lowerCAmelCase ) UpperCAmelCase__ : Dict = self.get_encoder_hidden_states(_lowerCAmelCase , fpaa=_lowerCAmelCase ) UpperCAmelCase__ : Optional[Any] = model.apply( {"""params""": params} , _lowerCAmelCase , jnp.array(_lowerCAmelCase , dtype=jnp.intaa ) , encoder_hidden_states=_lowerCAmelCase , ).sample assert sample.shape == latents.shape UpperCAmelCase__ : Dict = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ) , dtype=jnp.floataa ) UpperCAmelCase__ : List[Any] = jnp.array(_lowerCAmelCase , dtype=jnp.floataa ) # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, in the same hardware assert jnp.allclose(_lowerCAmelCase , _lowerCAmelCase , atol=1e-2 ) @parameterized.expand( [ # fmt: off [83, 4, [0.1_5_1_4, 0.0_8_0_7, 0.1_6_2_4, 0.1_0_1_6, -0.1_8_9_6, 0.0_2_6_3, 0.0_6_7_7, 0.2_3_1_0]], [17, 0.5_5, [0.1_1_6_4, -0.0_2_1_6, 0.0_1_7_0, 0.1_5_8_9, -0.3_1_2_0, 0.1_0_0_5, -0.0_5_8_1, -0.1_4_5_8]], [8, 0.8_9, [-0.1_7_5_8, -0.0_1_6_9, 0.1_0_0_4, -0.1_4_1_1, 0.1_3_1_2, 0.1_1_0_3, -0.1_9_9_6, 0.2_1_3_9]], [3, 1000, [0.1_2_1_4, 0.0_3_5_2, -0.0_7_3_1, -0.1_5_6_2, -0.0_9_9_4, -0.0_9_0_6, -0.2_3_4_0, -0.0_5_3_9]], # fmt: on ] ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ , UpperCAmelCase__ : Tuple = self.get_unet_model(model_id="""stabilityai/stable-diffusion-2""" , fpaa=_lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = self.get_latents(_lowerCAmelCase , shape=(4, 4, 96, 96) , fpaa=_lowerCAmelCase ) UpperCAmelCase__ : Any = self.get_encoder_hidden_states(_lowerCAmelCase , shape=(4, 77, 1024) , fpaa=_lowerCAmelCase ) UpperCAmelCase__ : Dict = model.apply( {"""params""": params} , _lowerCAmelCase , jnp.array(_lowerCAmelCase , dtype=jnp.intaa ) , encoder_hidden_states=_lowerCAmelCase , ).sample assert sample.shape == latents.shape UpperCAmelCase__ : Any = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ) , dtype=jnp.floataa ) UpperCAmelCase__ : Any = jnp.array(_lowerCAmelCase , dtype=jnp.floataa ) # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, on the same hardware assert jnp.allclose(_lowerCAmelCase , _lowerCAmelCase , atol=1e-2 )
79
1
import argparse import json from tqdm import tqdm def _lowerCamelCase ( ) -> Optional[int]: '''simple docstring''' UpperCAmelCase__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( """--src_path""" , type=__lowerCamelCase , default="""biencoder-nq-dev.json""" , help="""Path to raw DPR training data""" , ) parser.add_argument( """--evaluation_set""" , type=__lowerCamelCase , help="""where to store parsed evaluation_set file""" , ) parser.add_argument( """--gold_data_path""" , type=__lowerCamelCase , help="""where to store parsed gold_data_path file""" , ) UpperCAmelCase__ : Any = parser.parse_args() with open(args.src_path , """r""" ) as src_file, open(args.evaluation_set , """w""" ) as eval_file, open( args.gold_data_path , """w""" ) as gold_file: UpperCAmelCase__ : int = json.load(__lowerCamelCase ) for dpr_record in tqdm(__lowerCamelCase ): UpperCAmelCase__ : Tuple = dpr_record["""question"""] UpperCAmelCase__ : Optional[int] = [context["""title"""] for context in dpr_record["""positive_ctxs"""]] eval_file.write(question + """\n""" ) gold_file.write("""\t""".join(__lowerCamelCase ) + """\n""" ) if __name__ == "__main__": main()
79
import json import os import tempfile import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class UpperCAmelCase_ ( unittest.TestCase ): def __init__( self , _lowerCAmelCase , _lowerCAmelCase=7 , _lowerCAmelCase=3 , _lowerCAmelCase=18 , _lowerCAmelCase=30 , _lowerCAmelCase=400 , _lowerCAmelCase=True , _lowerCAmelCase=None , _lowerCAmelCase=True , ): UpperCAmelCase__ : List[str] = size if size is not None else {"""height""": 18, """width""": 18} UpperCAmelCase__ : Union[str, Any] = parent UpperCAmelCase__ : int = batch_size UpperCAmelCase__ : Tuple = num_channels UpperCAmelCase__ : Dict = image_size UpperCAmelCase__ : List[Any] = min_resolution UpperCAmelCase__ : str = max_resolution UpperCAmelCase__ : Union[str, Any] = do_resize UpperCAmelCase__ : Tuple = size UpperCAmelCase__ : int = do_normalize def __UpperCAmelCase ( self ): return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8_8_6_6_4_4_3_6_3_4_0_3_3_2_0_3, 0.6_6_1_8_8_2_9_3_6_9_5_4_4_9_8_3, 0.3_8_9_1_7_4_6_4_0_1_7_8_6_8_0_4], [-0.6_0_4_2_5_5_9_1_4_6_8_8_1_1_0_4, -0.0_2_2_9_5_0_0_8_8_6_0_5_2_8_4_6_9, 0.5_4_2_3_7_9_7_3_6_9_0_0_3_2_9_6], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class UpperCAmelCase_ ( __lowerCamelCase , unittest.TestCase ): __lowerCamelCase = ImageGPTImageProcessor if is_vision_available() else None def __UpperCAmelCase ( self ): UpperCAmelCase__ : Any = ImageGPTImageProcessingTester(self ) @property def __UpperCAmelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __UpperCAmelCase ( self ): UpperCAmelCase__ : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCAmelCase , """clusters""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """do_resize""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """size""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """do_normalize""" ) ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) UpperCAmelCase__ : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) UpperCAmelCase__ : Optional[int] = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(_lowerCAmelCase , obj[key] ) ) else: self.assertEqual(obj[key] , _lowerCAmelCase ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase__ : Union[str, Any] = os.path.join(_lowerCAmelCase , """image_processor.json""" ) image_processor_first.to_json_file(_lowerCAmelCase ) UpperCAmelCase__ : Optional[Any] = self.image_processing_class.from_json_file(_lowerCAmelCase ).to_dict() UpperCAmelCase__ : Dict = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(_lowerCAmelCase , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , _lowerCAmelCase ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : str = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(_lowerCAmelCase ) UpperCAmelCase__ : List[Any] = self.image_processing_class.from_pretrained(_lowerCAmelCase ).to_dict() UpperCAmelCase__ : Tuple = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(_lowerCAmelCase , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , _lowerCAmelCase ) @unittest.skip("""ImageGPT requires clusters at initialization""" ) def __UpperCAmelCase ( self ): pass def _lowerCamelCase ( ) -> Tuple: '''simple docstring''' UpperCAmelCase__ : Any = load_dataset("""hf-internal-testing/fixtures_image_utils""" , split="""test""" ) UpperCAmelCase__ : Dict = Image.open(dataset[4]["""file"""] ) UpperCAmelCase__ : Optional[Any] = Image.open(dataset[5]["""file"""] ) UpperCAmelCase__ : List[Any] = [imagea, imagea] return images @require_vision @require_torch class UpperCAmelCase_ ( unittest.TestCase ): @slow def __UpperCAmelCase ( self ): UpperCAmelCase__ : Tuple = ImageGPTImageProcessor.from_pretrained("""openai/imagegpt-small""" ) UpperCAmelCase__ : int = prepare_images() # test non-batched UpperCAmelCase__ : List[str] = image_processing(images[0] , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 1024) ) UpperCAmelCase__ : List[Any] = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() , _lowerCAmelCase ) # test batched UpperCAmelCase__ : List[str] = image_processing(_lowerCAmelCase , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 1024) ) UpperCAmelCase__ : Any = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() , _lowerCAmelCase )
79
1
from __future__ import annotations import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFViTForImageClassification, TFViTModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class UpperCAmelCase_ : def __init__( self , _lowerCAmelCase , _lowerCAmelCase=13 , _lowerCAmelCase=30 , _lowerCAmelCase=2 , _lowerCAmelCase=3 , _lowerCAmelCase=True , _lowerCAmelCase=True , _lowerCAmelCase=32 , _lowerCAmelCase=2 , _lowerCAmelCase=4 , _lowerCAmelCase=37 , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.1 , _lowerCAmelCase=10 , _lowerCAmelCase=0.0_2 , _lowerCAmelCase=3 , _lowerCAmelCase=None , ): UpperCAmelCase__ : Tuple = parent UpperCAmelCase__ : Optional[int] = batch_size UpperCAmelCase__ : Union[str, Any] = image_size UpperCAmelCase__ : int = patch_size UpperCAmelCase__ : str = num_channels UpperCAmelCase__ : int = is_training UpperCAmelCase__ : List[str] = use_labels UpperCAmelCase__ : List[Any] = hidden_size UpperCAmelCase__ : int = num_hidden_layers UpperCAmelCase__ : Tuple = num_attention_heads UpperCAmelCase__ : Optional[int] = intermediate_size UpperCAmelCase__ : Optional[Any] = hidden_act UpperCAmelCase__ : int = hidden_dropout_prob UpperCAmelCase__ : int = attention_probs_dropout_prob UpperCAmelCase__ : List[str] = type_sequence_label_size UpperCAmelCase__ : Optional[int] = initializer_range UpperCAmelCase__ : Any = scope # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) UpperCAmelCase__ : Any = (image_size // patch_size) ** 2 UpperCAmelCase__ : Tuple = num_patches + 1 def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase__ : List[str] = None if self.use_labels: UpperCAmelCase__ : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase__ : Union[str, Any] = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self ): return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_lowerCAmelCase , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : str = TFViTModel(config=_lowerCAmelCase ) UpperCAmelCase__ : str = model(_lowerCAmelCase , training=_lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # Test with an image with different size than the one specified in config. UpperCAmelCase__ : Optional[Any] = self.image_size // 2 UpperCAmelCase__ : List[str] = pixel_values[:, :, :image_size, :image_size] UpperCAmelCase__ : List[Any] = model(_lowerCAmelCase , interpolate_pos_encoding=_lowerCAmelCase , training=_lowerCAmelCase ) UpperCAmelCase__ : str = (image_size // self.patch_size) ** 2 + 1 self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : Tuple = self.type_sequence_label_size UpperCAmelCase__ : List[Any] = TFViTForImageClassification(_lowerCAmelCase ) UpperCAmelCase__ : List[str] = model(_lowerCAmelCase , labels=_lowerCAmelCase , training=_lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # Test with an image with different size than the one specified in config. UpperCAmelCase__ : Tuple = self.image_size // 2 UpperCAmelCase__ : Union[str, Any] = pixel_values[:, :, :image_size, :image_size] UpperCAmelCase__ : List[str] = model(_lowerCAmelCase , interpolate_pos_encoding=_lowerCAmelCase , training=_lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCAmelCase__ : Union[str, Any] = 1 UpperCAmelCase__ : Optional[Any] = TFViTForImageClassification(_lowerCAmelCase ) UpperCAmelCase__ : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCAmelCase__ : List[str] = model(_lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[Any] = self.prepare_config_and_inputs() UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : int = config_and_inputs UpperCAmelCase__ : int = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class UpperCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): __lowerCamelCase = (TFViTModel, TFViTForImageClassification) if is_tf_available() else () __lowerCamelCase = ( {'feature-extraction': TFViTModel, 'image-classification': TFViTForImageClassification} if is_tf_available() else {} ) __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False def __UpperCAmelCase ( self ): UpperCAmelCase__ : Any = TFViTModelTester(self ) UpperCAmelCase__ : int = ConfigTester(self , config_class=_lowerCAmelCase , has_text_modality=_lowerCAmelCase , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): UpperCAmelCase__ , UpperCAmelCase__ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ : str = model_class(_lowerCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) UpperCAmelCase__ : Dict = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowerCAmelCase , tf.keras.layers.Layer ) ) def __UpperCAmelCase ( self ): UpperCAmelCase__ , UpperCAmelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ : Optional[int] = model_class(_lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase__ : Tuple = [*signature.parameters.keys()] UpperCAmelCase__ : str = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _lowerCAmelCase ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCAmelCase ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase ) @slow def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = TFViTModel.from_pretrained("""google/vit-base-patch16-224""" ) self.assertIsNotNone(_lowerCAmelCase ) def _lowerCamelCase ( ) -> Tuple: '''simple docstring''' UpperCAmelCase__ : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class UpperCAmelCase_ ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self ): return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224""" ) if is_vision_available() else None @slow def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[int] = TFViTForImageClassification.from_pretrained("""google/vit-base-patch16-224""" ) UpperCAmelCase__ : List[Any] = self.default_image_processor UpperCAmelCase__ : Union[str, Any] = prepare_img() UpperCAmelCase__ : Optional[Any] = image_processor(images=_lowerCAmelCase , return_tensors="""tf""" ) # forward pass UpperCAmelCase__ : int = model(**_lowerCAmelCase ) # verify the logits UpperCAmelCase__ : Tuple = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowerCAmelCase ) UpperCAmelCase__ : int = tf.constant([-0.2_7_4_4, 0.8_2_1_5, -0.0_8_3_6] ) tf.debugging.assert_near(outputs.logits[0, :3] , _lowerCAmelCase , atol=1e-4 )
79
import os import unittest from transformers import MobileBertTokenizer, MobileBertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCAmelCase_ ( __lowerCamelCase , unittest.TestCase ): __lowerCamelCase = MobileBertTokenizer __lowerCamelCase = MobileBertTokenizerFast __lowerCamelCase = True __lowerCamelCase = True __lowerCamelCase = filter_non_english __lowerCamelCase = 'google/mobilebert-uncased' def __UpperCAmelCase ( self ): super().setUp() UpperCAmelCase__ : Dict = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] UpperCAmelCase__ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) UpperCAmelCase__ : List[str] = [ (tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped for tokenizer_def in self.tokenizers_list ] def __UpperCAmelCase ( self , _lowerCAmelCase ): UpperCAmelCase__ : Tuple = """UNwant\u00E9d,running""" UpperCAmelCase__ : Union[str, Any] = """unwanted, running""" return input_text, output_text def __UpperCAmelCase ( self ): UpperCAmelCase__ : Tuple = self.tokenizer_class(self.vocab_file ) UpperCAmelCase__ : Tuple = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(_lowerCAmelCase , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) , [9, 6, 7, 12, 10, 11] ) def __UpperCAmelCase ( self ): if not self.test_rust_tokenizer: return UpperCAmelCase__ : Tuple = self.get_tokenizer() UpperCAmelCase__ : Dict = self.get_rust_tokenizer() UpperCAmelCase__ : List[str] = """UNwant\u00E9d,running""" UpperCAmelCase__ : Optional[int] = tokenizer.tokenize(_lowerCAmelCase ) UpperCAmelCase__ : List[Any] = rust_tokenizer.tokenize(_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) UpperCAmelCase__ : Optional[int] = tokenizer.encode(_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ) UpperCAmelCase__ : Optional[Any] = rust_tokenizer.encode(_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) UpperCAmelCase__ : Tuple = self.get_rust_tokenizer() UpperCAmelCase__ : Any = tokenizer.encode(_lowerCAmelCase ) UpperCAmelCase__ : str = rust_tokenizer.encode(_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) # With lower casing UpperCAmelCase__ : Tuple = self.get_tokenizer(do_lower_case=_lowerCAmelCase ) UpperCAmelCase__ : Tuple = self.get_rust_tokenizer(do_lower_case=_lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = """UNwant\u00E9d,running""" UpperCAmelCase__ : int = tokenizer.tokenize(_lowerCAmelCase ) UpperCAmelCase__ : Any = rust_tokenizer.tokenize(_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) UpperCAmelCase__ : List[Any] = tokenizer.encode(_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ) UpperCAmelCase__ : List[Any] = rust_tokenizer.encode(_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = self.get_rust_tokenizer() UpperCAmelCase__ : List[str] = tokenizer.encode(_lowerCAmelCase ) UpperCAmelCase__ : Optional[Any] = rust_tokenizer.encode(_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Any = BasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Tuple = BasicTokenizer(do_lower_case=_lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Union[str, Any] = BasicTokenizer(do_lower_case=_lowerCAmelCase , strip_accents=_lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Any = BasicTokenizer(do_lower_case=_lowerCAmelCase , strip_accents=_lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[str] = BasicTokenizer(do_lower_case=_lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[str] = BasicTokenizer(do_lower_case=_lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : int = BasicTokenizer(do_lower_case=_lowerCAmelCase , strip_accents=_lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = BasicTokenizer(do_lower_case=_lowerCAmelCase , strip_accents=_lowerCAmelCase ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = BasicTokenizer(do_lower_case=_lowerCAmelCase , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : int = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] UpperCAmelCase__ : List[str] = {} for i, token in enumerate(_lowerCAmelCase ): UpperCAmelCase__ : Optional[Any] = i UpperCAmelCase__ : str = WordpieceTokenizer(vocab=_lowerCAmelCase , unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ) , [] ) self.assertListEqual(tokenizer.tokenize("""unwanted running""" ) , ["""un""", """##want""", """##ed""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.tokenize("""unwantedX running""" ) , ["""[UNK]""", """runn""", """##ing"""] ) def __UpperCAmelCase ( self ): self.assertTrue(_is_whitespace(""" """ ) ) self.assertTrue(_is_whitespace("""\t""" ) ) self.assertTrue(_is_whitespace("""\r""" ) ) self.assertTrue(_is_whitespace("""\n""" ) ) self.assertTrue(_is_whitespace("""\u00A0""" ) ) self.assertFalse(_is_whitespace("""A""" ) ) self.assertFalse(_is_whitespace("""-""" ) ) def __UpperCAmelCase ( self ): self.assertTrue(_is_control("""\u0005""" ) ) self.assertFalse(_is_control("""A""" ) ) self.assertFalse(_is_control(""" """ ) ) self.assertFalse(_is_control("""\t""" ) ) self.assertFalse(_is_control("""\r""" ) ) def __UpperCAmelCase ( self ): self.assertTrue(_is_punctuation("""-""" ) ) self.assertTrue(_is_punctuation("""$""" ) ) self.assertTrue(_is_punctuation("""`""" ) ) self.assertTrue(_is_punctuation(""".""" ) ) self.assertFalse(_is_punctuation("""A""" ) ) self.assertFalse(_is_punctuation(""" """ ) ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[int] = self.get_tokenizer() UpperCAmelCase__ : Union[str, Any] = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(_lowerCAmelCase ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) self.assertListEqual( [rust_tokenizer.tokenize(_lowerCAmelCase ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) @slow def __UpperCAmelCase ( self ): UpperCAmelCase__ : Any = self.tokenizer_class.from_pretrained("""google/mobilebert-uncased""" ) UpperCAmelCase__ : List[Any] = tokenizer.encode("""sequence builders""" , add_special_tokens=_lowerCAmelCase ) UpperCAmelCase__ : List[Any] = tokenizer.encode("""multi-sequence build""" , add_special_tokens=_lowerCAmelCase ) UpperCAmelCase__ : List[Any] = tokenizer.build_inputs_with_special_tokens(_lowerCAmelCase ) UpperCAmelCase__ : List[str] = tokenizer.build_inputs_with_special_tokens(_lowerCAmelCase , _lowerCAmelCase ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def __UpperCAmelCase ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCAmelCase__ : Any = self.rust_tokenizer_class.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) UpperCAmelCase__ : Optional[int] = f"A, naïve {tokenizer_r.mask_token} AllenNLP sentence." UpperCAmelCase__ : Optional[Any] = tokenizer_r.encode_plus( _lowerCAmelCase , return_attention_mask=_lowerCAmelCase , return_token_type_ids=_lowerCAmelCase , return_offsets_mapping=_lowerCAmelCase , add_special_tokens=_lowerCAmelCase , ) UpperCAmelCase__ : Any = tokenizer_r.do_lower_case if hasattr(_lowerCAmelCase , """do_lower_case""" ) else False UpperCAmelCase__ : Optional[int] = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """A"""), ((1, 2), ""","""), ((3, 5), """na"""), ((5, 6), """##ï"""), ((6, 8), """##ve"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """Allen"""), ((21, 23), """##NL"""), ((23, 24), """##P"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """a"""), ((1, 2), ""","""), ((3, 8), """naive"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """allen"""), ((21, 23), """##nl"""), ((23, 24), """##p"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["""input_ids"""] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["""offset_mapping"""] ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Tuple = ["""的""", """人""", """有"""] UpperCAmelCase__ : Tuple = """""".join(_lowerCAmelCase ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCAmelCase__ : Tuple = True UpperCAmelCase__ : Optional[Any] = self.tokenizer_class.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) UpperCAmelCase__ : Tuple = self.rust_tokenizer_class.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = tokenizer_p.encode(_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ) UpperCAmelCase__ : List[Any] = tokenizer_r.encode(_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ) UpperCAmelCase__ : Any = tokenizer_r.convert_ids_to_tokens(_lowerCAmelCase ) UpperCAmelCase__ : Optional[int] = tokenizer_p.convert_ids_to_tokens(_lowerCAmelCase ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) UpperCAmelCase__ : List[Any] = False UpperCAmelCase__ : Union[str, Any] = self.rust_tokenizer_class.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) UpperCAmelCase__ : Tuple = self.tokenizer_class.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = tokenizer_r.encode(_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ) UpperCAmelCase__ : List[Any] = tokenizer_p.encode(_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ) UpperCAmelCase__ : Optional[int] = tokenizer_r.convert_ids_to_tokens(_lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = tokenizer_p.convert_ids_to_tokens(_lowerCAmelCase ) # it is expected that only the first Chinese character is not preceded by "##". UpperCAmelCase__ : List[str] = [ f"##{token}" if idx != 0 else token for idx, token in enumerate(_lowerCAmelCase ) ] self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase )
79
1
import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__ : str = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : int = {"""vocab_file""": """vocab.json"""} SCREAMING_SNAKE_CASE__ : Tuple = { """vocab_file""": { """mgp-str""": """https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json""", } } SCREAMING_SNAKE_CASE__ : List[Any] = {"""mgp-str""": 27} class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = VOCAB_FILES_NAMES __lowerCamelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _lowerCAmelCase , _lowerCAmelCase="[GO]" , _lowerCAmelCase="[GO]" , _lowerCAmelCase="[s]" , _lowerCAmelCase="[GO]" , **_lowerCAmelCase ): super().__init__( unk_token=_lowerCAmelCase , bos_token=_lowerCAmelCase , eos_token=_lowerCAmelCase , pad_token=_lowerCAmelCase , **_lowerCAmelCase , ) with open(_lowerCAmelCase , encoding="""utf-8""" ) as vocab_handle: UpperCAmelCase__ : Optional[int] = json.load(_lowerCAmelCase ) UpperCAmelCase__ : Any = {v: k for k, v in self.vocab.items()} @property def __UpperCAmelCase ( self ): return len(self.vocab ) def __UpperCAmelCase ( self ): return dict(self.vocab , **self.added_tokens_encoder ) def __UpperCAmelCase ( self , _lowerCAmelCase ): UpperCAmelCase__ : Tuple = [] for s in text: char_tokens.extend(_lowerCAmelCase ) return char_tokens def __UpperCAmelCase ( self , _lowerCAmelCase ): return self.vocab.get(_lowerCAmelCase , self.vocab.get(self.unk_token ) ) def __UpperCAmelCase ( self , _lowerCAmelCase ): return self.decoder.get(_lowerCAmelCase ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase = None ): if not os.path.isdir(_lowerCAmelCase ): logger.error("""Vocabulary path ({}) should be a directory""".format(_lowerCAmelCase ) ) return UpperCAmelCase__ : Optional[Any] = os.path.join( _lowerCAmelCase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) with open(_lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=_lowerCAmelCase , ensure_ascii=_lowerCAmelCase ) + """\n""" ) return (vocab_file,)
79
import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase__ : Union[str, Any] = """https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg""" UpperCAmelCase__ : int = Image.open(requests.get(__lowerCamelCase , stream=__lowerCamelCase ).raw ).convert("""RGB""" ) UpperCAmelCase__ : Any = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.48_145_466, 0.4_578_275, 0.40_821_073) , (0.26_862_954, 0.26_130_258, 0.27_577_711) ), ] ) UpperCAmelCase__ : Optional[int] = transform(__lowerCamelCase ).unsqueeze(0 ).to(__lowerCamelCase ) return image def _lowerCamelCase ( __lowerCamelCase ) -> str: '''simple docstring''' if "visual_encoder" in key: UpperCAmelCase__ : Dict = re.sub("""visual_encoder*""" , """vision_model.encoder""" , __lowerCamelCase ) if "blocks" in key: UpperCAmelCase__ : Optional[Any] = re.sub(r"""blocks""" , """layers""" , __lowerCamelCase ) if "attn" in key: UpperCAmelCase__ : List[str] = re.sub(r"""attn""" , """self_attn""" , __lowerCamelCase ) if "norm1" in key: UpperCAmelCase__ : Union[str, Any] = re.sub(r"""norm1""" , """layer_norm1""" , __lowerCamelCase ) if "norm2" in key: UpperCAmelCase__ : Any = re.sub(r"""norm2""" , """layer_norm2""" , __lowerCamelCase ) if "encoder.norm" in key: UpperCAmelCase__ : Dict = re.sub(r"""encoder.norm""" , """post_layernorm""" , __lowerCamelCase ) if "encoder.patch_embed.proj" in key: UpperCAmelCase__ : List[str] = re.sub(r"""encoder.patch_embed.proj""" , """embeddings.patch_embedding""" , __lowerCamelCase ) if "encoder.pos_embed" in key: UpperCAmelCase__ : List[str] = re.sub(r"""encoder.pos_embed""" , """embeddings.position_embedding""" , __lowerCamelCase ) if "encoder.cls_token" in key: UpperCAmelCase__ : List[Any] = re.sub(r"""encoder.cls_token""" , """embeddings.class_embedding""" , __lowerCamelCase ) if "self_attn" in key: UpperCAmelCase__ : List[Any] = re.sub(r"""self_attn.proj""" , """self_attn.projection""" , __lowerCamelCase ) return key @torch.no_grad() def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase=None ) -> Tuple: '''simple docstring''' if config_path is not None: UpperCAmelCase__ : Any = BlipConfig.from_pretrained(__lowerCamelCase ) else: UpperCAmelCase__ : str = BlipConfig(projection_dim=512 , text_config={} , vision_config={} ) UpperCAmelCase__ : int = BlipForConditionalGeneration(__lowerCamelCase ).eval() UpperCAmelCase__ : Any = """https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth""" UpperCAmelCase__ : List[str] = blip_decoder(pretrained=__lowerCamelCase , image_size=384 , vit="""base""" ) UpperCAmelCase__ : Union[str, Any] = pt_model.eval() UpperCAmelCase__ : Optional[int] = pt_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase__ : Dict = modified_state_dict.pop(__lowerCamelCase ) UpperCAmelCase__ : Union[str, Any] = rename_key(__lowerCamelCase ) UpperCAmelCase__ : List[str] = value hf_model.load_state_dict(__lowerCamelCase ) UpperCAmelCase__ : Tuple = 384 UpperCAmelCase__ : str = load_demo_image(image_size=__lowerCamelCase , device="""cpu""" ) UpperCAmelCase__ : str = BertTokenizer.from_pretrained("""bert-base-uncased""" ) UpperCAmelCase__ : Dict = tokenizer(["""a picture of"""] ).input_ids UpperCAmelCase__ : int = hf_model.generate(__lowerCamelCase , __lowerCamelCase ) assert out[0].tolist() == [3_0522, 1037, 3861, 1997, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] UpperCAmelCase__ : Any = hf_model.generate(__lowerCamelCase ) assert out[0].tolist() == [3_0522, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(__lowerCamelCase ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' UpperCAmelCase__ : Union[str, Any] = ( """https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth""" ) UpperCAmelCase__ : List[Any] = blip_vqa(pretrained=__lowerCamelCase , image_size=__lowerCamelCase , vit="""base""" ) vqa_model.eval() UpperCAmelCase__ : str = vqa_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase__ : Dict = modified_state_dict.pop(__lowerCamelCase ) UpperCAmelCase__ : Dict = rename_key(__lowerCamelCase ) UpperCAmelCase__ : int = value UpperCAmelCase__ : List[str] = BlipForQuestionAnswering(__lowerCamelCase ) hf_vqa_model.load_state_dict(__lowerCamelCase ) UpperCAmelCase__ : Tuple = ["""How many dogs are in this image?"""] UpperCAmelCase__ : Union[str, Any] = tokenizer(__lowerCamelCase , return_tensors="""pt""" ).input_ids UpperCAmelCase__ : Optional[Any] = hf_vqa_model.generate(__lowerCamelCase , __lowerCamelCase ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + """_vqa""" ) UpperCAmelCase__ : int = """https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth""" UpperCAmelCase__ : Any = blip_itm(pretrained=__lowerCamelCase , image_size=__lowerCamelCase , vit="""base""" ) itm_model.eval() UpperCAmelCase__ : List[Any] = itm_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase__ : Dict = modified_state_dict.pop(__lowerCamelCase ) UpperCAmelCase__ : int = rename_key(__lowerCamelCase ) UpperCAmelCase__ : Any = value UpperCAmelCase__ : Optional[int] = BlipForImageTextRetrieval(__lowerCamelCase ) UpperCAmelCase__ : Union[str, Any] = ["""A picture of a woman with a dog sitting in a beach"""] UpperCAmelCase__ : List[Any] = tokenizer( __lowerCamelCase , return_tensors="""pt""" , padding="""max_length""" , truncation=__lowerCamelCase , max_length=35 , ).input_ids hf_itm_model.load_state_dict(__lowerCamelCase ) hf_itm_model.eval() UpperCAmelCase__ : List[str] = hf_itm_model(__lowerCamelCase , __lowerCamelCase , use_itm_head=__lowerCamelCase ) UpperCAmelCase__ : List[str] = hf_itm_model(__lowerCamelCase , __lowerCamelCase , use_itm_head=__lowerCamelCase ) assert out[0].item() == 0.2_110_687_494_277_954 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.45_698_845_386_505_127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + """_itm""" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
79
1
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) class UpperCAmelCase_ ( __lowerCamelCase ): def __init__( self , *_lowerCAmelCase , **_lowerCAmelCase ): warnings.warn( """The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use GLPNImageProcessor instead.""" , _lowerCAmelCase , ) super().__init__(*_lowerCAmelCase , **_lowerCAmelCase )
79
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : List[Any] = { """MIT/ast-finetuned-audioset-10-10-0.4593""": ( """https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json""" ), } class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = 'audio-spectrogram-transformer' def __init__( self , _lowerCAmelCase=768 , _lowerCAmelCase=12 , _lowerCAmelCase=12 , _lowerCAmelCase=3072 , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.0_2 , _lowerCAmelCase=1e-12 , _lowerCAmelCase=16 , _lowerCAmelCase=True , _lowerCAmelCase=10 , _lowerCAmelCase=10 , _lowerCAmelCase=1024 , _lowerCAmelCase=128 , **_lowerCAmelCase , ): super().__init__(**_lowerCAmelCase ) UpperCAmelCase__ : Optional[int] = hidden_size UpperCAmelCase__ : int = num_hidden_layers UpperCAmelCase__ : List[Any] = num_attention_heads UpperCAmelCase__ : Dict = intermediate_size UpperCAmelCase__ : Dict = hidden_act UpperCAmelCase__ : str = hidden_dropout_prob UpperCAmelCase__ : str = attention_probs_dropout_prob UpperCAmelCase__ : Tuple = initializer_range UpperCAmelCase__ : Dict = layer_norm_eps UpperCAmelCase__ : Optional[Any] = patch_size UpperCAmelCase__ : Tuple = qkv_bias UpperCAmelCase__ : Tuple = frequency_stride UpperCAmelCase__ : Union[str, Any] = time_stride UpperCAmelCase__ : Optional[Any] = max_length UpperCAmelCase__ : Optional[int] = num_mel_bins
79
1
import os import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features SCREAMING_SNAKE_CASE__ : Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Optional[Any] = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys()) SCREAMING_SNAKE_CASE__ : List[Any] = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class UpperCAmelCase_ : __lowerCamelCase = field( default=__lowerCamelCase , metadata={'help': 'Model type selected in the list: ' + ', '.join(__lowerCamelCase )} ) __lowerCamelCase = field( default=__lowerCamelCase , metadata={'help': 'The input data dir. Should contain the .json files for the SQuAD task.'} ) __lowerCamelCase = field( default=128 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) __lowerCamelCase = field( default=128 , metadata={'help': 'When splitting up a long document into chunks, how much stride to take between chunks.'} , ) __lowerCamelCase = field( default=64 , metadata={ 'help': ( 'The maximum number of tokens for the question. Questions longer than this will ' 'be truncated to this length.' ) } , ) __lowerCamelCase = field( default=30 , metadata={ 'help': ( 'The maximum length of an answer that can be generated. This is needed because the start ' 'and end predictions are not conditioned on one another.' ) } , ) __lowerCamelCase = field( default=__lowerCamelCase , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) __lowerCamelCase = field( default=__lowerCamelCase , metadata={'help': 'If true, the SQuAD examples contain some that do not have an answer.'} ) __lowerCamelCase = field( default=0.0 , metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} ) __lowerCamelCase = field( default=20 , metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} ) __lowerCamelCase = field( default=0 , metadata={ 'help': ( 'language id of input for language-specific xlm models (see' ' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)' ) } , ) __lowerCamelCase = field(default=1 , metadata={'help': 'multiple threads for converting example to features'} ) class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = 'train' __lowerCamelCase = 'dev' class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = 42 __lowerCamelCase = 42 __lowerCamelCase = 42 __lowerCamelCase = 42 def __init__( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = None , _lowerCAmelCase = Split.train , _lowerCAmelCase = False , _lowerCAmelCase = None , _lowerCAmelCase = "pt" , ): UpperCAmelCase__ : Optional[int] = args UpperCAmelCase__ : List[str] = is_language_sensitive UpperCAmelCase__ : Optional[Any] = SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor() if isinstance(_lowerCAmelCase , _lowerCAmelCase ): try: UpperCAmelCase__ : Union[str, Any] = Split[mode] except KeyError: raise KeyError("""mode is not a valid split name""" ) UpperCAmelCase__ : List[Any] = mode # Load data features from cache or dataset file UpperCAmelCase__ : Optional[Any] = """v2""" if args.version_2_with_negative else """v1""" UpperCAmelCase__ : Union[str, Any] = os.path.join( cache_dir if cache_dir is not None else args.data_dir , f"cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}" , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. UpperCAmelCase__ : List[str] = cached_features_file + """.lock""" with FileLock(_lowerCAmelCase ): if os.path.exists(_lowerCAmelCase ) and not args.overwrite_cache: UpperCAmelCase__ : Dict = time.time() UpperCAmelCase__ : List[Any] = torch.load(_lowerCAmelCase ) # Legacy cache files have only features, while new cache files # will have dataset and examples also. UpperCAmelCase__ : str = self.old_features["""features"""] UpperCAmelCase__ : List[str] = self.old_features.get("""dataset""" , _lowerCAmelCase ) UpperCAmelCase__ : Dict = self.old_features.get("""examples""" , _lowerCAmelCase ) logger.info( f"Loading features from cached file {cached_features_file} [took %.3f s]" , time.time() - start ) if self.dataset is None or self.examples is None: logger.warning( f"Deleting cached file {cached_features_file} will allow dataset and examples to be cached in" """ future run""" ) else: if mode == Split.dev: UpperCAmelCase__ : List[str] = self.processor.get_dev_examples(args.data_dir ) else: UpperCAmelCase__ : Any = self.processor.get_train_examples(args.data_dir ) UpperCAmelCase__ , UpperCAmelCase__ : List[str] = squad_convert_examples_to_features( examples=self.examples , tokenizer=_lowerCAmelCase , max_seq_length=args.max_seq_length , doc_stride=args.doc_stride , max_query_length=args.max_query_length , is_training=mode == Split.train , threads=args.threads , return_dataset=_lowerCAmelCase , ) UpperCAmelCase__ : Dict = time.time() torch.save( {"""features""": self.features, """dataset""": self.dataset, """examples""": self.examples} , _lowerCAmelCase , ) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( f"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]" ) def __len__( self ): return len(self.features ) def __getitem__( self , _lowerCAmelCase ): # Convert to Tensors and build dataset UpperCAmelCase__ : Tuple = self.features[i] UpperCAmelCase__ : Union[str, Any] = torch.tensor(feature.input_ids , dtype=torch.long ) UpperCAmelCase__ : Tuple = torch.tensor(feature.attention_mask , dtype=torch.long ) UpperCAmelCase__ : str = torch.tensor(feature.token_type_ids , dtype=torch.long ) UpperCAmelCase__ : Tuple = torch.tensor(feature.cls_index , dtype=torch.long ) UpperCAmelCase__ : List[Any] = torch.tensor(feature.p_mask , dtype=torch.float ) UpperCAmelCase__ : Dict = torch.tensor(feature.is_impossible , dtype=torch.float ) UpperCAmelCase__ : int = { """input_ids""": input_ids, """attention_mask""": attention_mask, """token_type_ids""": token_type_ids, } if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]: del inputs["token_type_ids"] if self.args.model_type in ["xlnet", "xlm"]: inputs.update({"""cls_index""": cls_index, """p_mask""": p_mask} ) if self.args.version_2_with_negative: inputs.update({"""is_impossible""": is_impossible} ) if self.is_language_sensitive: inputs.update({"""langs""": (torch.ones(input_ids.shape , dtype=torch.intaa ) * self.args.lang_id)} ) if self.mode == Split.train: UpperCAmelCase__ : Any = torch.tensor(feature.start_position , dtype=torch.long ) UpperCAmelCase__ : Tuple = torch.tensor(feature.end_position , dtype=torch.long ) inputs.update({"""start_positions""": start_positions, """end_positions""": end_positions} ) return inputs
79
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) class UpperCAmelCase_ ( __lowerCamelCase ): def __init__( self , *_lowerCAmelCase , **_lowerCAmelCase ): warnings.warn( """The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use GLPNImageProcessor instead.""" , _lowerCAmelCase , ) super().__init__(*_lowerCAmelCase , **_lowerCAmelCase )
79
1
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : List[str] = { """facebook/s2t-small-librispeech-asr""": ( """https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/config.json""" ), # See all Speech2Text models at https://huggingface.co/models?filter=speech_to_text } class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = 'speech_to_text' __lowerCamelCase = ['past_key_values'] __lowerCamelCase = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , _lowerCAmelCase=10000 , _lowerCAmelCase=12 , _lowerCAmelCase=2048 , _lowerCAmelCase=4 , _lowerCAmelCase=6 , _lowerCAmelCase=2048 , _lowerCAmelCase=4 , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.0 , _lowerCAmelCase=True , _lowerCAmelCase=True , _lowerCAmelCase="relu" , _lowerCAmelCase=256 , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.0_2 , _lowerCAmelCase=2 , _lowerCAmelCase=True , _lowerCAmelCase=1 , _lowerCAmelCase=0 , _lowerCAmelCase=2 , _lowerCAmelCase=6000 , _lowerCAmelCase=1024 , _lowerCAmelCase=2 , _lowerCAmelCase=(5, 5) , _lowerCAmelCase=1024 , _lowerCAmelCase=80 , _lowerCAmelCase=1 , **_lowerCAmelCase , ): UpperCAmelCase__ : List[Any] = vocab_size UpperCAmelCase__ : Optional[Any] = d_model UpperCAmelCase__ : Any = encoder_ffn_dim UpperCAmelCase__ : Dict = encoder_layers UpperCAmelCase__ : Any = encoder_attention_heads UpperCAmelCase__ : Dict = decoder_ffn_dim UpperCAmelCase__ : Tuple = decoder_layers UpperCAmelCase__ : Dict = decoder_attention_heads UpperCAmelCase__ : Optional[Any] = dropout UpperCAmelCase__ : Optional[Any] = attention_dropout UpperCAmelCase__ : str = activation_dropout UpperCAmelCase__ : Dict = activation_function UpperCAmelCase__ : Optional[int] = init_std UpperCAmelCase__ : int = encoder_layerdrop UpperCAmelCase__ : Tuple = decoder_layerdrop UpperCAmelCase__ : Tuple = use_cache UpperCAmelCase__ : str = encoder_layers UpperCAmelCase__ : List[str] = scale_embedding # scale factor will be sqrt(d_model) if True UpperCAmelCase__ : Union[str, Any] = max_source_positions UpperCAmelCase__ : Union[str, Any] = max_target_positions UpperCAmelCase__ : Optional[Any] = num_conv_layers UpperCAmelCase__ : Dict = list(_lowerCAmelCase ) UpperCAmelCase__ : str = conv_channels UpperCAmelCase__ : Dict = input_feat_per_channel UpperCAmelCase__ : int = input_channels if len(self.conv_kernel_sizes ) != self.num_conv_layers: raise ValueError( """Configuration for convolutional module is incorrect. """ """It is required that `len(config.conv_kernel_sizes)` == `config.num_conv_layers` """ f"but is `len(config.conv_kernel_sizes) = {len(self.conv_kernel_sizes )}`, " f"`config.num_conv_layers = {self.num_conv_layers}`." ) super().__init__( pad_token_id=_lowerCAmelCase , bos_token_id=_lowerCAmelCase , eos_token_id=_lowerCAmelCase , is_encoder_decoder=_lowerCAmelCase , decoder_start_token_id=_lowerCAmelCase , **_lowerCAmelCase , )
79
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_realm import RealmTokenizer SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : int = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} SCREAMING_SNAKE_CASE__ : List[str] = { """vocab_file""": { """google/realm-cc-news-pretrained-embedder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt""" ), """google/realm-cc-news-pretrained-encoder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt""" ), """google/realm-cc-news-pretrained-scorer""": ( """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt""" ), """google/realm-cc-news-pretrained-openqa""": ( """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt""" ), """google/realm-orqa-nq-openqa""": """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt""", """google/realm-orqa-nq-reader""": """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt""", """google/realm-orqa-wq-openqa""": """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt""", """google/realm-orqa-wq-reader""": """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt""", }, """tokenizer_file""": { """google/realm-cc-news-pretrained-embedder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont""" ), """google/realm-cc-news-pretrained-encoder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json""" ), """google/realm-cc-news-pretrained-scorer""": ( """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json""" ), """google/realm-cc-news-pretrained-openqa""": ( """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json""" ), """google/realm-orqa-nq-openqa""": ( """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json""" ), """google/realm-orqa-nq-reader""": ( """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json""" ), """google/realm-orqa-wq-openqa""": ( """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json""" ), """google/realm-orqa-wq-reader""": ( """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json""" ), }, } SCREAMING_SNAKE_CASE__ : Optional[Any] = { """google/realm-cc-news-pretrained-embedder""": 5_12, """google/realm-cc-news-pretrained-encoder""": 5_12, """google/realm-cc-news-pretrained-scorer""": 5_12, """google/realm-cc-news-pretrained-openqa""": 5_12, """google/realm-orqa-nq-openqa""": 5_12, """google/realm-orqa-nq-reader""": 5_12, """google/realm-orqa-wq-openqa""": 5_12, """google/realm-orqa-wq-reader""": 5_12, } SCREAMING_SNAKE_CASE__ : Optional[Any] = { """google/realm-cc-news-pretrained-embedder""": {"""do_lower_case""": True}, """google/realm-cc-news-pretrained-encoder""": {"""do_lower_case""": True}, """google/realm-cc-news-pretrained-scorer""": {"""do_lower_case""": True}, """google/realm-cc-news-pretrained-openqa""": {"""do_lower_case""": True}, """google/realm-orqa-nq-openqa""": {"""do_lower_case""": True}, """google/realm-orqa-nq-reader""": {"""do_lower_case""": True}, """google/realm-orqa-wq-openqa""": {"""do_lower_case""": True}, """google/realm-orqa-wq-reader""": {"""do_lower_case""": True}, } class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = VOCAB_FILES_NAMES __lowerCamelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase = PRETRAINED_INIT_CONFIGURATION __lowerCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase = RealmTokenizer def __init__( self , _lowerCAmelCase=None , _lowerCAmelCase=None , _lowerCAmelCase=True , _lowerCAmelCase="[UNK]" , _lowerCAmelCase="[SEP]" , _lowerCAmelCase="[PAD]" , _lowerCAmelCase="[CLS]" , _lowerCAmelCase="[MASK]" , _lowerCAmelCase=True , _lowerCAmelCase=None , **_lowerCAmelCase , ): super().__init__( _lowerCAmelCase , tokenizer_file=_lowerCAmelCase , do_lower_case=_lowerCAmelCase , unk_token=_lowerCAmelCase , sep_token=_lowerCAmelCase , pad_token=_lowerCAmelCase , cls_token=_lowerCAmelCase , mask_token=_lowerCAmelCase , tokenize_chinese_chars=_lowerCAmelCase , strip_accents=_lowerCAmelCase , **_lowerCAmelCase , ) UpperCAmelCase__ : Tuple = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , _lowerCAmelCase ) != do_lower_case or normalizer_state.get("""strip_accents""" , _lowerCAmelCase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , _lowerCAmelCase ) != tokenize_chinese_chars ): UpperCAmelCase__ : Any = getattr(_lowerCAmelCase , normalizer_state.pop("""type""" ) ) UpperCAmelCase__ : str = do_lower_case UpperCAmelCase__ : Tuple = strip_accents UpperCAmelCase__ : Tuple = tokenize_chinese_chars UpperCAmelCase__ : Union[str, Any] = normalizer_class(**_lowerCAmelCase ) UpperCAmelCase__ : Dict = do_lower_case def __UpperCAmelCase ( self , _lowerCAmelCase , **_lowerCAmelCase ): UpperCAmelCase__ : List[Any] = PaddingStrategy.MAX_LENGTH UpperCAmelCase__ : Optional[int] = text UpperCAmelCase__ : Optional[int] = kwargs.pop("""text_pair""" , _lowerCAmelCase ) UpperCAmelCase__ : Optional[int] = kwargs.pop("""return_tensors""" , _lowerCAmelCase ) UpperCAmelCase__ : Optional[Any] = { """input_ids""": [], """attention_mask""": [], """token_type_ids""": [], } for idx, candidate_text in enumerate(_lowerCAmelCase ): if batch_text_pair is not None: UpperCAmelCase__ : str = batch_text_pair[idx] else: UpperCAmelCase__ : Any = None UpperCAmelCase__ : str = super().__call__(_lowerCAmelCase , _lowerCAmelCase , return_tensors=_lowerCAmelCase , **_lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = encoded_candidates.get("""input_ids""" ) UpperCAmelCase__ : str = encoded_candidates.get("""attention_mask""" ) UpperCAmelCase__ : Union[str, Any] = encoded_candidates.get("""token_type_ids""" ) if encoded_input_ids is not None: output_data["input_ids"].append(_lowerCAmelCase ) if encoded_attention_mask is not None: output_data["attention_mask"].append(_lowerCAmelCase ) if encoded_token_type_ids is not None: output_data["token_type_ids"].append(_lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = {key: item for key, item in output_data.items() if len(_lowerCAmelCase ) != 0} return BatchEncoding(_lowerCAmelCase , tensor_type=_lowerCAmelCase ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase=None ): UpperCAmelCase__ : List[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 __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase = None ): UpperCAmelCase__ : Any = [self.sep_token_id] UpperCAmelCase__ : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase = None ): UpperCAmelCase__ : List[str] = self._tokenizer.model.save(_lowerCAmelCase , name=_lowerCAmelCase ) return tuple(_lowerCAmelCase )
79
1
import torch def _lowerCamelCase ( ) -> List[str]: '''simple docstring''' if torch.cuda.is_available(): UpperCAmelCase__ : Optional[int] = torch.cuda.device_count() else: UpperCAmelCase__ : Any = 0 print(F"Successfully ran on {num_gpus} GPUs" ) if __name__ == "__main__": main()
79
# 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. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = 'facebook/bart-large-mnli' __lowerCamelCase = ( 'This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which ' 'should be the text to classify, and `labels`, which should be the list of labels to use for classification. ' 'It returns the most likely label in the list of provided `labels` for the input text.' ) __lowerCamelCase = 'text_classifier' __lowerCamelCase = AutoTokenizer __lowerCamelCase = AutoModelForSequenceClassification __lowerCamelCase = ['text', ['text']] __lowerCamelCase = ['text'] def __UpperCAmelCase ( self ): super().setup() UpperCAmelCase__ : Optional[Any] = self.model.config UpperCAmelCase__ : Tuple = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("""entail""" ): UpperCAmelCase__ : Dict = int(_lowerCAmelCase ) if self.entailment_id == -1: raise ValueError("""Could not determine the entailment ID from the model config, please pass it at init.""" ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : List[Any] = labels return self.pre_processor( [text] * len(_lowerCAmelCase ) , [f"This example is {label}" for label in labels] , return_tensors="""pt""" , padding="""max_length""" , ) def __UpperCAmelCase ( self , _lowerCAmelCase ): UpperCAmelCase__ : str = outputs.logits UpperCAmelCase__ : List[Any] = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
79
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE__ : Dict = { """configuration_convnext""": ["""CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ConvNextConfig""", """ConvNextOnnxConfig"""] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Dict = ["""ConvNextFeatureExtractor"""] SCREAMING_SNAKE_CASE__ : Tuple = ["""ConvNextImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = [ """CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """ConvNextForImageClassification""", """ConvNextModel""", """ConvNextPreTrainedModel""", """ConvNextBackbone""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ """TFConvNextForImageClassification""", """TFConvNextModel""", """TFConvNextPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_convnext import CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvNextConfig, ConvNextOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_convnext import ConvNextFeatureExtractor from .image_processing_convnext import ConvNextImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convnext import ( CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvNextBackbone, ConvNextForImageClassification, ConvNextModel, ConvNextPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convnext import TFConvNextForImageClassification, TFConvNextModel, TFConvNextPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
79
from __future__ import annotations import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFViTForImageClassification, TFViTModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class UpperCAmelCase_ : def __init__( self , _lowerCAmelCase , _lowerCAmelCase=13 , _lowerCAmelCase=30 , _lowerCAmelCase=2 , _lowerCAmelCase=3 , _lowerCAmelCase=True , _lowerCAmelCase=True , _lowerCAmelCase=32 , _lowerCAmelCase=2 , _lowerCAmelCase=4 , _lowerCAmelCase=37 , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.1 , _lowerCAmelCase=10 , _lowerCAmelCase=0.0_2 , _lowerCAmelCase=3 , _lowerCAmelCase=None , ): UpperCAmelCase__ : Tuple = parent UpperCAmelCase__ : Optional[int] = batch_size UpperCAmelCase__ : Union[str, Any] = image_size UpperCAmelCase__ : int = patch_size UpperCAmelCase__ : str = num_channels UpperCAmelCase__ : int = is_training UpperCAmelCase__ : List[str] = use_labels UpperCAmelCase__ : List[Any] = hidden_size UpperCAmelCase__ : int = num_hidden_layers UpperCAmelCase__ : Tuple = num_attention_heads UpperCAmelCase__ : Optional[int] = intermediate_size UpperCAmelCase__ : Optional[Any] = hidden_act UpperCAmelCase__ : int = hidden_dropout_prob UpperCAmelCase__ : int = attention_probs_dropout_prob UpperCAmelCase__ : List[str] = type_sequence_label_size UpperCAmelCase__ : Optional[int] = initializer_range UpperCAmelCase__ : Any = scope # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) UpperCAmelCase__ : Any = (image_size // patch_size) ** 2 UpperCAmelCase__ : Tuple = num_patches + 1 def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase__ : List[str] = None if self.use_labels: UpperCAmelCase__ : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase__ : Union[str, Any] = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self ): return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_lowerCAmelCase , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : str = TFViTModel(config=_lowerCAmelCase ) UpperCAmelCase__ : str = model(_lowerCAmelCase , training=_lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # Test with an image with different size than the one specified in config. UpperCAmelCase__ : Optional[Any] = self.image_size // 2 UpperCAmelCase__ : List[str] = pixel_values[:, :, :image_size, :image_size] UpperCAmelCase__ : List[Any] = model(_lowerCAmelCase , interpolate_pos_encoding=_lowerCAmelCase , training=_lowerCAmelCase ) UpperCAmelCase__ : str = (image_size // self.patch_size) ** 2 + 1 self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : Tuple = self.type_sequence_label_size UpperCAmelCase__ : List[Any] = TFViTForImageClassification(_lowerCAmelCase ) UpperCAmelCase__ : List[str] = model(_lowerCAmelCase , labels=_lowerCAmelCase , training=_lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # Test with an image with different size than the one specified in config. UpperCAmelCase__ : Tuple = self.image_size // 2 UpperCAmelCase__ : Union[str, Any] = pixel_values[:, :, :image_size, :image_size] UpperCAmelCase__ : List[str] = model(_lowerCAmelCase , interpolate_pos_encoding=_lowerCAmelCase , training=_lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCAmelCase__ : Union[str, Any] = 1 UpperCAmelCase__ : Optional[Any] = TFViTForImageClassification(_lowerCAmelCase ) UpperCAmelCase__ : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCAmelCase__ : List[str] = model(_lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[Any] = self.prepare_config_and_inputs() UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : int = config_and_inputs UpperCAmelCase__ : int = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class UpperCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): __lowerCamelCase = (TFViTModel, TFViTForImageClassification) if is_tf_available() else () __lowerCamelCase = ( {'feature-extraction': TFViTModel, 'image-classification': TFViTForImageClassification} if is_tf_available() else {} ) __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False def __UpperCAmelCase ( self ): UpperCAmelCase__ : Any = TFViTModelTester(self ) UpperCAmelCase__ : int = ConfigTester(self , config_class=_lowerCAmelCase , has_text_modality=_lowerCAmelCase , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def __UpperCAmelCase ( self ): pass @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): UpperCAmelCase__ , UpperCAmelCase__ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ : str = model_class(_lowerCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) UpperCAmelCase__ : Dict = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowerCAmelCase , tf.keras.layers.Layer ) ) def __UpperCAmelCase ( self ): UpperCAmelCase__ , UpperCAmelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ : Optional[int] = model_class(_lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase__ : Tuple = [*signature.parameters.keys()] UpperCAmelCase__ : str = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _lowerCAmelCase ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCAmelCase ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase ) @slow def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = TFViTModel.from_pretrained("""google/vit-base-patch16-224""" ) self.assertIsNotNone(_lowerCAmelCase ) def _lowerCamelCase ( ) -> Tuple: '''simple docstring''' UpperCAmelCase__ : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class UpperCAmelCase_ ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self ): return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224""" ) if is_vision_available() else None @slow def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[int] = TFViTForImageClassification.from_pretrained("""google/vit-base-patch16-224""" ) UpperCAmelCase__ : List[Any] = self.default_image_processor UpperCAmelCase__ : Union[str, Any] = prepare_img() UpperCAmelCase__ : Optional[Any] = image_processor(images=_lowerCAmelCase , return_tensors="""tf""" ) # forward pass UpperCAmelCase__ : int = model(**_lowerCAmelCase ) # verify the logits UpperCAmelCase__ : Tuple = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowerCAmelCase ) UpperCAmelCase__ : int = tf.constant([-0.2_7_4_4, 0.8_2_1_5, -0.0_8_3_6] ) tf.debugging.assert_near(outputs.logits[0, :3] , _lowerCAmelCase , atol=1e-4 )
79
1
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor SCREAMING_SNAKE_CASE__ : Optional[Any] = logging.get_logger(__name__) class UpperCAmelCase_ ( __lowerCamelCase ): def __init__( self , *_lowerCAmelCase , **_lowerCAmelCase ): warnings.warn( """The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use FlavaImageProcessor instead.""" , _lowerCAmelCase , ) super().__init__(*_lowerCAmelCase , **_lowerCAmelCase )
79
from functools import lru_cache @lru_cache def _lowerCamelCase ( __lowerCamelCase ) -> int: '''simple docstring''' if num < 0: raise ValueError("""Number should not be negative.""" ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
79
1
import unittest from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class UpperCAmelCase_ : @staticmethod def __UpperCAmelCase ( *_lowerCAmelCase , **_lowerCAmelCase ): pass @is_pipeline_test @require_vision @require_torch class UpperCAmelCase_ ( unittest.TestCase ): __lowerCamelCase = MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : Dict = pipeline( """zero-shot-object-detection""" , model="""hf-internal-testing/tiny-random-owlvit-object-detection""" ) UpperCAmelCase__ : Dict = [ { """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""", """candidate_labels""": ["""cat""", """remote""", """couch"""], } ] return object_detector, examples def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : Tuple = object_detector(examples[0] , threshold=0.0 ) UpperCAmelCase__ : List[str] = len(_lowerCAmelCase ) self.assertGreater(_lowerCAmelCase , 0 ) self.assertEqual( _lowerCAmelCase , [ { """score""": ANY(_lowerCAmelCase ), """label""": ANY(_lowerCAmelCase ), """box""": {"""xmin""": ANY(_lowerCAmelCase ), """ymin""": ANY(_lowerCAmelCase ), """xmax""": ANY(_lowerCAmelCase ), """ymax""": ANY(_lowerCAmelCase )}, } for i in range(_lowerCAmelCase ) ] , ) @require_tf @unittest.skip("""Zero Shot Object Detection not implemented in TF""" ) def __UpperCAmelCase ( self ): pass @require_torch def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[str] = pipeline( """zero-shot-object-detection""" , model="""hf-internal-testing/tiny-random-owlvit-object-detection""" ) UpperCAmelCase__ : str = object_detector( """./tests/fixtures/tests_samples/COCO/000000039769.png""" , candidate_labels=["""cat""", """remote""", """couch"""] , threshold=0.6_4 , ) self.assertEqual( nested_simplify(_lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.7_2_3_5, """label""": """cat""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.7_2_1_8, """label""": """remote""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.7_1_8_4, """label""": """couch""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.6_7_4_8, """label""": """remote""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6_6_5_6, """label""": """cat""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6_6_1_4, """label""": """couch""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6_4_5_6, """label""": """remote""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}}, {"""score""": 0.6_4_2, """label""": """remote""", """box""": {"""xmin""": 67, """ymin""": 274, """xmax""": 93, """ymax""": 297}}, {"""score""": 0.6_4_1_9, """label""": """cat""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}}, ] , ) UpperCAmelCase__ : int = object_detector( [ { """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""", """candidate_labels""": ["""cat""", """remote""", """couch"""], } ] , threshold=0.6_4 , ) self.assertEqual( nested_simplify(_lowerCAmelCase , decimals=4 ) , [ [ {"""score""": 0.7_2_3_5, """label""": """cat""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.7_2_1_8, """label""": """remote""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.7_1_8_4, """label""": """couch""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}}, {"""score""": 0.6_7_4_8, """label""": """remote""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6_6_5_6, """label""": """cat""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6_6_1_4, """label""": """couch""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}}, {"""score""": 0.6_4_5_6, """label""": """remote""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}}, {"""score""": 0.6_4_2, """label""": """remote""", """box""": {"""xmin""": 67, """ymin""": 274, """xmax""": 93, """ymax""": 297}}, {"""score""": 0.6_4_1_9, """label""": """cat""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}}, ] ] , ) @require_torch @slow def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[Any] = pipeline("""zero-shot-object-detection""" ) UpperCAmelCase__ : Optional[Any] = object_detector( """http://images.cocodataset.org/val2017/000000039769.jpg""" , candidate_labels=["""cat""", """remote""", """couch"""] , ) self.assertEqual( nested_simplify(_lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}}, {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}}, {"""score""": 0.2_5_3_7, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}}, {"""score""": 0.1_4_7_4, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}}, {"""score""": 0.1_2_0_8, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}}, ] , ) UpperCAmelCase__ : Union[str, Any] = object_detector( [ { """image""": """http://images.cocodataset.org/val2017/000000039769.jpg""", """candidate_labels""": ["""cat""", """remote""", """couch"""], }, { """image""": """http://images.cocodataset.org/val2017/000000039769.jpg""", """candidate_labels""": ["""cat""", """remote""", """couch"""], }, ] , ) self.assertEqual( nested_simplify(_lowerCAmelCase , decimals=4 ) , [ [ {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}}, {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}}, {"""score""": 0.2_5_3_7, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}}, {"""score""": 0.1_4_7_4, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}}, {"""score""": 0.1_2_0_8, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}}, ], [ {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}}, {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}}, {"""score""": 0.2_5_3_7, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}}, {"""score""": 0.1_4_7_4, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}}, {"""score""": 0.1_2_0_8, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}}, ], ] , ) @require_tf @unittest.skip("""Zero Shot Object Detection not implemented in TF""" ) def __UpperCAmelCase ( self ): pass @require_torch @slow def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = 0.2 UpperCAmelCase__ : List[Any] = pipeline("""zero-shot-object-detection""" ) UpperCAmelCase__ : Tuple = object_detector( """http://images.cocodataset.org/val2017/000000039769.jpg""" , candidate_labels=["""cat""", """remote""", """couch"""] , threshold=_lowerCAmelCase , ) self.assertEqual( nested_simplify(_lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}}, {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}}, {"""score""": 0.2_5_3_7, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}}, ] , ) @require_torch @slow def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[Any] = 2 UpperCAmelCase__ : int = pipeline("""zero-shot-object-detection""" ) UpperCAmelCase__ : Any = object_detector( """http://images.cocodataset.org/val2017/000000039769.jpg""" , candidate_labels=["""cat""", """remote""", """couch"""] , top_k=_lowerCAmelCase , ) self.assertEqual( nested_simplify(_lowerCAmelCase , decimals=4 ) , [ {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}}, {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}}, ] , )
79
import argparse import hashlib # hashlib is only used inside the Test class import struct class UpperCAmelCase_ : def __init__( self , _lowerCAmelCase ): UpperCAmelCase__ : Any = data UpperCAmelCase__ : List[Any] = [0X6745_2301, 0Xefcd_ab89, 0X98ba_dcfe, 0X1032_5476, 0Xc3d2_e1f0] @staticmethod def __UpperCAmelCase ( _lowerCAmelCase , _lowerCAmelCase ): return ((n << b) | (n >> (32 - b))) & 0Xffff_ffff def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = B"""\x80""" + B"""\x00""" * (63 - (len(self.data ) + 8) % 64) UpperCAmelCase__ : Optional[int] = self.data + padding + struct.pack(""">Q""" , 8 * len(self.data ) ) return padded_data def __UpperCAmelCase ( self ): return [ self.padded_data[i : i + 64] for i in range(0 , len(self.padded_data ) , 64 ) ] def __UpperCAmelCase ( self , _lowerCAmelCase ): UpperCAmelCase__ : Dict = list(struct.unpack(""">16L""" , _lowerCAmelCase ) ) + [0] * 64 for i in range(16 , 80 ): UpperCAmelCase__ : Optional[int] = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]) , 1 ) return w def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[str] = self.padding() UpperCAmelCase__ : List[str] = self.split_blocks() for block in self.blocks: UpperCAmelCase__ : Tuple = self.expand_block(_lowerCAmelCase ) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Tuple = self.h for i in range(0 , 80 ): if 0 <= i < 20: UpperCAmelCase__ : Optional[int] = (b & c) | ((~b) & d) UpperCAmelCase__ : int = 0X5a82_7999 elif 20 <= i < 40: UpperCAmelCase__ : Tuple = b ^ c ^ d UpperCAmelCase__ : int = 0X6ed9_eba1 elif 40 <= i < 60: UpperCAmelCase__ : List[str] = (b & c) | (b & d) | (c & d) UpperCAmelCase__ : Tuple = 0X8f1b_bcdc elif 60 <= i < 80: UpperCAmelCase__ : int = b ^ c ^ d UpperCAmelCase__ : str = 0Xca62_c1d6 UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Optional[Any] = ( self.rotate(_lowerCAmelCase , 5 ) + f + e + k + expanded_block[i] & 0Xffff_ffff, a, self.rotate(_lowerCAmelCase , 30 ), c, d, ) UpperCAmelCase__ : int = ( self.h[0] + a & 0Xffff_ffff, self.h[1] + b & 0Xffff_ffff, self.h[2] + c & 0Xffff_ffff, self.h[3] + d & 0Xffff_ffff, self.h[4] + e & 0Xffff_ffff, ) return ("{:08x}" * 5).format(*self.h ) def _lowerCamelCase ( ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase__ : Optional[Any] = B"""Test String""" assert SHAaHash(__lowerCamelCase ).final_hash() == hashlib.shaa(__lowerCamelCase ).hexdigest() # noqa: S324 def _lowerCamelCase ( ) -> str: '''simple docstring''' UpperCAmelCase__ : Optional[int] = argparse.ArgumentParser(description="""Process some strings or files""" ) parser.add_argument( """--string""" , dest="""input_string""" , default="""Hello World!! Welcome to Cryptography""" , help="""Hash the string""" , ) parser.add_argument("""--file""" , dest="""input_file""" , help="""Hash contents of a file""" ) UpperCAmelCase__ : str = parser.parse_args() UpperCAmelCase__ : Union[str, Any] = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , """rb""" ) as f: UpperCAmelCase__ : List[Any] = f.read() else: UpperCAmelCase__ : int = bytes(__lowerCamelCase , """utf-8""" ) print(SHAaHash(__lowerCamelCase ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
79
1
import unittest import torch from torch import nn from diffusers.models.activations import get_activation class UpperCAmelCase_ ( unittest.TestCase ): def __UpperCAmelCase ( self ): UpperCAmelCase__ : Any = get_activation("""swish""" ) self.assertIsInstance(_lowerCAmelCase , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Union[str, Any] = get_activation("""silu""" ) self.assertIsInstance(_lowerCAmelCase , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Tuple = get_activation("""mish""" ) self.assertIsInstance(_lowerCAmelCase , nn.Mish ) self.assertEqual(act(torch.tensor(-200 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Tuple = get_activation("""gelu""" ) self.assertIsInstance(_lowerCAmelCase , nn.GELU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
79
from importlib import import_module from .logging import get_logger SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_logger(__name__) class UpperCAmelCase_ : def __init__( self , _lowerCAmelCase , _lowerCAmelCase=None ): UpperCAmelCase__ : List[str] = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith("""__""" ): setattr(self , _lowerCAmelCase , getattr(_lowerCAmelCase , _lowerCAmelCase ) ) UpperCAmelCase__ : Tuple = module._original_module if isinstance(_lowerCAmelCase , _PatchedModuleObj ) else module class UpperCAmelCase_ : __lowerCamelCase = [] def __init__( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=None ): UpperCAmelCase__ : str = obj UpperCAmelCase__ : List[str] = target UpperCAmelCase__ : List[str] = new UpperCAmelCase__ : Any = target.split(""".""" )[0] UpperCAmelCase__ : Union[str, Any] = {} UpperCAmelCase__ : str = attrs or [] def __enter__( self ): *UpperCAmelCase__ , UpperCAmelCase__ : List[Any] = self.target.split(""".""" ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(_lowerCAmelCase ) ): try: UpperCAmelCase__ : Optional[int] = import_module(""".""".join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): UpperCAmelCase__ : Any = getattr(self.obj , _lowerCAmelCase ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(_lowerCAmelCase , _PatchedModuleObj ) and obj_attr._original_module is submodule) ): UpperCAmelCase__ : List[Any] = obj_attr # patch at top level setattr(self.obj , _lowerCAmelCase , _PatchedModuleObj(_lowerCAmelCase , attrs=self.attrs ) ) UpperCAmelCase__ : Optional[Any] = getattr(self.obj , _lowerCAmelCase ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(_lowerCAmelCase , _lowerCAmelCase , _PatchedModuleObj(getattr(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) , attrs=self.attrs ) ) UpperCAmelCase__ : Union[str, Any] = getattr(_lowerCAmelCase , _lowerCAmelCase ) # finally set the target attribute setattr(_lowerCAmelCase , _lowerCAmelCase , self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: UpperCAmelCase__ : Union[str, Any] = getattr(import_module(""".""".join(_lowerCAmelCase ) ) , _lowerCAmelCase ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj , _lowerCAmelCase ) is attr_value: UpperCAmelCase__ : Optional[int] = getattr(self.obj , _lowerCAmelCase ) setattr(self.obj , _lowerCAmelCase , self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" UpperCAmelCase__ : Dict = globals()["""__builtins__"""][target_attr] setattr(self.obj , _lowerCAmelCase , self.new ) else: raise RuntimeError(f"Tried to patch attribute {target_attr} instead of a submodule." ) def __exit__( self , *_lowerCAmelCase ): for attr in list(self.original ): setattr(self.obj , _lowerCAmelCase , self.original.pop(_lowerCAmelCase ) ) def __UpperCAmelCase ( self ): self.__enter__() self._active_patches.append(self ) def __UpperCAmelCase ( self ): try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
79
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : int = { """configuration_blenderbot""": [ """BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BlenderbotConfig""", """BlenderbotOnnxConfig""", ], """tokenization_blenderbot""": ["""BlenderbotTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = ["""BlenderbotTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = [ """BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST""", """BlenderbotForCausalLM""", """BlenderbotForConditionalGeneration""", """BlenderbotModel""", """BlenderbotPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = [ """TFBlenderbotForConditionalGeneration""", """TFBlenderbotModel""", """TFBlenderbotPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ """FlaxBlenderbotForConditionalGeneration""", """FlaxBlenderbotModel""", """FlaxBlenderbotPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Dict = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
79
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : str = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { """huggingface/informer-tourism-monthly""": ( """https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json""" ), # See all Informer models at https://huggingface.co/models?filter=informer } class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = 'informer' __lowerCamelCase = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = "student_t" , _lowerCAmelCase = "nll" , _lowerCAmelCase = 1 , _lowerCAmelCase = None , _lowerCAmelCase = "mean" , _lowerCAmelCase = 0 , _lowerCAmelCase = 0 , _lowerCAmelCase = 0 , _lowerCAmelCase = 0 , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = 64 , _lowerCAmelCase = 32 , _lowerCAmelCase = 32 , _lowerCAmelCase = 2 , _lowerCAmelCase = 2 , _lowerCAmelCase = 2 , _lowerCAmelCase = 2 , _lowerCAmelCase = True , _lowerCAmelCase = "gelu" , _lowerCAmelCase = 0.0_5 , _lowerCAmelCase = 0.1 , _lowerCAmelCase = 0.1 , _lowerCAmelCase = 0.1 , _lowerCAmelCase = 0.1 , _lowerCAmelCase = 100 , _lowerCAmelCase = 0.0_2 , _lowerCAmelCase=True , _lowerCAmelCase = "prob" , _lowerCAmelCase = 5 , _lowerCAmelCase = True , **_lowerCAmelCase , ): # time series specific configuration UpperCAmelCase__ : List[str] = prediction_length UpperCAmelCase__ : Optional[Any] = context_length or prediction_length UpperCAmelCase__ : str = distribution_output UpperCAmelCase__ : int = loss UpperCAmelCase__ : Optional[Any] = input_size UpperCAmelCase__ : Any = num_time_features UpperCAmelCase__ : int = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7] UpperCAmelCase__ : Union[str, Any] = scaling UpperCAmelCase__ : Optional[Any] = num_dynamic_real_features UpperCAmelCase__ : List[str] = num_static_real_features UpperCAmelCase__ : str = num_static_categorical_features # set cardinality if cardinality and num_static_categorical_features > 0: if len(_lowerCAmelCase ) != num_static_categorical_features: raise ValueError( """The cardinality should be a list of the same length as `num_static_categorical_features`""" ) UpperCAmelCase__ : List[str] = cardinality else: UpperCAmelCase__ : Optional[Any] = [0] # set embedding_dimension if embedding_dimension and num_static_categorical_features > 0: if len(_lowerCAmelCase ) != num_static_categorical_features: raise ValueError( """The embedding dimension should be a list of the same length as `num_static_categorical_features`""" ) UpperCAmelCase__ : str = embedding_dimension else: UpperCAmelCase__ : List[str] = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] UpperCAmelCase__ : Union[str, Any] = num_parallel_samples # Transformer architecture configuration UpperCAmelCase__ : Dict = input_size * len(self.lags_sequence ) + self._number_of_features UpperCAmelCase__ : Any = d_model UpperCAmelCase__ : int = encoder_attention_heads UpperCAmelCase__ : Optional[Any] = decoder_attention_heads UpperCAmelCase__ : int = encoder_ffn_dim UpperCAmelCase__ : Tuple = decoder_ffn_dim UpperCAmelCase__ : List[Any] = encoder_layers UpperCAmelCase__ : Optional[Any] = decoder_layers UpperCAmelCase__ : Tuple = dropout UpperCAmelCase__ : int = attention_dropout UpperCAmelCase__ : List[str] = activation_dropout UpperCAmelCase__ : Any = encoder_layerdrop UpperCAmelCase__ : Union[str, Any] = decoder_layerdrop UpperCAmelCase__ : Tuple = activation_function UpperCAmelCase__ : Dict = init_std UpperCAmelCase__ : str = use_cache # Informer UpperCAmelCase__ : Union[str, Any] = attention_type UpperCAmelCase__ : int = sampling_factor UpperCAmelCase__ : Any = distil super().__init__(is_encoder_decoder=_lowerCAmelCase , **_lowerCAmelCase ) @property def __UpperCAmelCase ( self ): return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
79
1
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { """studio-ousia/luke-base""": """https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json""", """studio-ousia/luke-large""": """https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json""", } class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = 'luke' def __init__( self , _lowerCAmelCase=50267 , _lowerCAmelCase=500000 , _lowerCAmelCase=768 , _lowerCAmelCase=256 , _lowerCAmelCase=12 , _lowerCAmelCase=12 , _lowerCAmelCase=3072 , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.1 , _lowerCAmelCase=512 , _lowerCAmelCase=2 , _lowerCAmelCase=0.0_2 , _lowerCAmelCase=1e-12 , _lowerCAmelCase=True , _lowerCAmelCase=None , _lowerCAmelCase=1 , _lowerCAmelCase=0 , _lowerCAmelCase=2 , **_lowerCAmelCase , ): super().__init__(pad_token_id=_lowerCAmelCase , bos_token_id=_lowerCAmelCase , eos_token_id=_lowerCAmelCase , **_lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = vocab_size UpperCAmelCase__ : List[Any] = entity_vocab_size UpperCAmelCase__ : Optional[Any] = hidden_size UpperCAmelCase__ : Optional[Any] = entity_emb_size UpperCAmelCase__ : Optional[Any] = num_hidden_layers UpperCAmelCase__ : str = num_attention_heads UpperCAmelCase__ : Any = hidden_act UpperCAmelCase__ : Optional[Any] = intermediate_size UpperCAmelCase__ : Optional[Any] = hidden_dropout_prob UpperCAmelCase__ : Union[str, Any] = attention_probs_dropout_prob UpperCAmelCase__ : List[str] = max_position_embeddings UpperCAmelCase__ : int = type_vocab_size UpperCAmelCase__ : List[str] = initializer_range UpperCAmelCase__ : List[Any] = layer_norm_eps UpperCAmelCase__ : Optional[Any] = use_entity_aware_attention UpperCAmelCase__ : Optional[int] = classifier_dropout
79
def _lowerCamelCase ( __lowerCamelCase ) -> bool: '''simple docstring''' if p < 2: raise ValueError("""p should not be less than 2!""" ) elif p == 2: return True UpperCAmelCase__ : Tuple = 4 UpperCAmelCase__ : Tuple = (1 << p) - 1 for _ in range(p - 2 ): UpperCAmelCase__ : List[str] = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
79
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Any = {"""configuration_plbart""": ["""PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PLBartConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = ["""PLBartTokenizer"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ """PLBART_PRETRAINED_MODEL_ARCHIVE_LIST""", """PLBartForCausalLM""", """PLBartForConditionalGeneration""", """PLBartForSequenceClassification""", """PLBartModel""", """PLBartPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_plbart import PLBartTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_plbart import ( PLBART_PRETRAINED_MODEL_ARCHIVE_LIST, PLBartForCausalLM, PLBartForConditionalGeneration, PLBartForSequenceClassification, PLBartModel, PLBartPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
79
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE__ : Any = { """configuration_mobilevit""": ["""MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MobileViTConfig""", """MobileViTOnnxConfig"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["""MobileViTFeatureExtractor"""] SCREAMING_SNAKE_CASE__ : Union[str, Any] = ["""MobileViTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Dict = [ """MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """MobileViTForImageClassification""", """MobileViTForSemanticSegmentation""", """MobileViTModel""", """MobileViTPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Any = [ """TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFMobileViTForImageClassification""", """TFMobileViTForSemanticSegmentation""", """TFMobileViTModel""", """TFMobileViTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilevit import MobileViTFeatureExtractor from .image_processing_mobilevit import MobileViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilevit import ( MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel, MobileViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilevit import ( TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel, TFMobileViTPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
79
1
from __future__ import annotations from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ : Any = TypeVar("""T""") class UpperCAmelCase_ ( Generic[T] ): def __init__( self , _lowerCAmelCase ): UpperCAmelCase__ : Union[str, Any] = data UpperCAmelCase__ : Tuple = self UpperCAmelCase__ : Optional[int] = 0 class UpperCAmelCase_ ( Generic[T] ): def __init__( self ): # map from node name to the node object UpperCAmelCase__ : dict[T, DisjointSetTreeNode[T]] = {} def __UpperCAmelCase ( self , _lowerCAmelCase ): # create a new set with x as its member UpperCAmelCase__ : Any = DisjointSetTreeNode(_lowerCAmelCase ) def __UpperCAmelCase ( self , _lowerCAmelCase ): # find the set x belongs to (with path-compression) UpperCAmelCase__ : Dict = self.map[data] if elem_ref != elem_ref.parent: UpperCAmelCase__ : str = self.find_set(elem_ref.parent.data ) return elem_ref.parent def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase ): # helper function for union operation if nodea.rank > nodea.rank: UpperCAmelCase__ : Optional[int] = nodea else: UpperCAmelCase__ : Optional[Any] = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase ): # merge 2 disjoint sets self.link(self.find_set(_lowerCAmelCase ) , self.find_set(_lowerCAmelCase ) ) class UpperCAmelCase_ ( Generic[T] ): def __init__( self ): # connections: map from the node to the neighbouring nodes (with weights) UpperCAmelCase__ : dict[T, dict[T, int]] = {} def __UpperCAmelCase ( self , _lowerCAmelCase ): # add a node ONLY if its not present in the graph if node not in self.connections: UpperCAmelCase__ : Union[str, Any] = {} def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): # add an edge with the given weight self.add_node(_lowerCAmelCase ) self.add_node(_lowerCAmelCase ) UpperCAmelCase__ : List[Any] = weight UpperCAmelCase__ : int = weight def __UpperCAmelCase ( self ): UpperCAmelCase__ : Union[str, Any] = [] UpperCAmelCase__ : Any = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda _lowerCAmelCase : x[2] ) # creating the disjoint set UpperCAmelCase__ : Optional[Any] = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(_lowerCAmelCase ) # MST generation UpperCAmelCase__ : int = 0 UpperCAmelCase__ : Optional[Any] = 0 UpperCAmelCase__ : str = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Optional[Any] = edges[index] index += 1 UpperCAmelCase__ : Optional[int] = disjoint_set.find_set(_lowerCAmelCase ) UpperCAmelCase__ : str = disjoint_set.find_set(_lowerCAmelCase ) if parent_u != parent_v: num_edges += 1 graph.add_edge(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) disjoint_set.union(_lowerCAmelCase , _lowerCAmelCase ) return graph
79
from __future__ import annotations SCREAMING_SNAKE_CASE__ : List[str] = 8.988e9 # units = N * m^s * C^-2 def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> dict[str, float]: '''simple docstring''' UpperCAmelCase__ : int = abs(chargea * chargea ) if (force, chargea, chargea, distance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if distance < 0: raise ValueError("""Distance cannot be negative""" ) if force == 0: UpperCAmelCase__ : int = COULOMBS_CONSTANT * charge_product / (distance**2) return {"force": force} elif chargea == 0: UpperCAmelCase__ : str = abs(__lowerCamelCase ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge1": chargea} elif chargea == 0: UpperCAmelCase__ : Union[str, Any] = abs(__lowerCamelCase ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge2": chargea} elif distance == 0: UpperCAmelCase__ : Optional[Any] = (COULOMBS_CONSTANT * charge_product / abs(__lowerCamelCase )) ** 0.5 return {"distance": distance} raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
79
1
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments SCREAMING_SNAKE_CASE__ : Union[str, Any] = logging.getLogger(__name__) @dataclass class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = field( default=0.0 , metadata={'help': 'The label smoothing epsilon to apply (if not zero).'} ) __lowerCamelCase = field(default=__lowerCamelCase , metadata={'help': 'Whether to SortishSamler or not.'} ) __lowerCamelCase = field( default=__lowerCamelCase , metadata={'help': 'Whether to use generate to calculate generative metrics (ROUGE, BLEU).'} ) __lowerCamelCase = field(default=__lowerCamelCase , metadata={'help': 'whether to use adafactor'} ) __lowerCamelCase = field( default=__lowerCamelCase , metadata={'help': 'Encoder layer dropout probability. Goes into model.config.'} ) __lowerCamelCase = field( default=__lowerCamelCase , metadata={'help': 'Decoder layer dropout probability. Goes into model.config.'} ) __lowerCamelCase = field(default=__lowerCamelCase , metadata={'help': 'Dropout probability. Goes into model.config.'} ) __lowerCamelCase = field( default=__lowerCamelCase , metadata={'help': 'Attention dropout probability. Goes into model.config.'} ) __lowerCamelCase = field( default='linear' , metadata={'help': f"Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}"} , )
79
class UpperCAmelCase_ : def __init__( self , _lowerCAmelCase ): # we need a list not a string, so do something to change the type UpperCAmelCase__ : Dict = arr.split(""",""" ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Tuple = [int(self.array[0] )] * len(self.array ) UpperCAmelCase__ : List[str] = [int(self.array[0] )] * len(self.array ) for i in range(1 , len(self.array ) ): UpperCAmelCase__ : Tuple = max( int(self.array[i] ) + sum_value[i - 1] , int(self.array[i] ) ) UpperCAmelCase__ : Union[str, Any] = max(sum_value[i] , rear[i - 1] ) return rear[len(self.array ) - 1] if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Tuple = input("""please input some numbers:""") SCREAMING_SNAKE_CASE__ : Dict = SubArray(whole_array) SCREAMING_SNAKE_CASE__ : Dict = array.solve_sub_array() print(("""the results is:""", re))
79
1
def _lowerCamelCase ( __lowerCamelCase ) -> float: '''simple docstring''' if not nums: # Makes sure that the list is not empty raise ValueError("""List is empty""" ) UpperCAmelCase__ : Optional[Any] = sum(__lowerCamelCase ) / len(__lowerCamelCase ) # Calculate the average return sum(abs(x - average ) for x in nums ) / len(__lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
79
from ....configuration_utils import PretrainedConfig from ....utils import logging SCREAMING_SNAKE_CASE__ : List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { """Visual-Attention-Network/van-base""": ( """https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json""" ), } class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = 'van' def __init__( self , _lowerCAmelCase=224 , _lowerCAmelCase=3 , _lowerCAmelCase=[7, 3, 3, 3] , _lowerCAmelCase=[4, 2, 2, 2] , _lowerCAmelCase=[64, 128, 320, 512] , _lowerCAmelCase=[3, 3, 12, 3] , _lowerCAmelCase=[8, 8, 4, 4] , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.0_2 , _lowerCAmelCase=1e-6 , _lowerCAmelCase=1e-2 , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.0 , **_lowerCAmelCase , ): super().__init__(**_lowerCAmelCase ) UpperCAmelCase__ : Tuple = image_size UpperCAmelCase__ : Optional[Any] = num_channels UpperCAmelCase__ : Optional[int] = patch_sizes UpperCAmelCase__ : int = strides UpperCAmelCase__ : Optional[int] = hidden_sizes UpperCAmelCase__ : str = depths UpperCAmelCase__ : Optional[Any] = mlp_ratios UpperCAmelCase__ : List[Any] = hidden_act UpperCAmelCase__ : Tuple = initializer_range UpperCAmelCase__ : Any = layer_norm_eps UpperCAmelCase__ : List[Any] = layer_scale_init_value UpperCAmelCase__ : int = drop_path_rate UpperCAmelCase__ : Dict = dropout_rate
79
1
import copy import re class UpperCAmelCase_ : __lowerCamelCase = 'hp' __lowerCamelCase = {} __lowerCamelCase = None @classmethod def __UpperCAmelCase ( cls , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : List[str] = prefix UpperCAmelCase__ : Tuple = defaults cls.build_naming_info() @staticmethod def __UpperCAmelCase ( _lowerCAmelCase , _lowerCAmelCase ): if len(_lowerCAmelCase ) == 0: return "" UpperCAmelCase__ : int = None if any(char.isdigit() for char in word ): raise Exception(f"Parameters should not contain numbers: '{word}' contains a number" ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(_lowerCAmelCase ) + 1 ): UpperCAmelCase__ : List[str] = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: UpperCAmelCase__ : List[str] = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(_lowerCAmelCase ): UpperCAmelCase__ : Optional[int] = """""" while integer != 0: UpperCAmelCase__ : List[Any] = chr(ord("""A""" ) + integer % 10 ) + s integer //= 10 return s UpperCAmelCase__ : List[str] = 0 while True: UpperCAmelCase__ : List[str] = word + """#""" + int_to_alphabetic(_lowerCAmelCase ) if sword in info["reverse_short_word"]: continue else: UpperCAmelCase__ : List[str] = sword break UpperCAmelCase__ : str = short_word UpperCAmelCase__ : Tuple = word return short_word @staticmethod def __UpperCAmelCase ( _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : Dict = param_name.split("""_""" ) UpperCAmelCase__ : str = [TrialShortNamer.shortname_for_word(_lowerCAmelCase , _lowerCAmelCase ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name UpperCAmelCase__ : Union[str, Any] = ["""""", """_"""] for separator in separators: UpperCAmelCase__ : Optional[Any] = separator.join(_lowerCAmelCase ) if shortname not in info["reverse_short_param"]: UpperCAmelCase__ : Any = shortname UpperCAmelCase__ : Dict = param_name return shortname return param_name @staticmethod def __UpperCAmelCase ( _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : Optional[int] = TrialShortNamer.shortname_for_key(_lowerCAmelCase , _lowerCAmelCase ) UpperCAmelCase__ : Tuple = short_name UpperCAmelCase__ : Union[str, Any] = param_name @classmethod def __UpperCAmelCase ( cls ): if cls.NAMING_INFO is not None: return UpperCAmelCase__ : str = { """short_word""": {}, """reverse_short_word""": {}, """short_param""": {}, """reverse_short_param""": {}, } UpperCAmelCase__ : List[str] = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(_lowerCAmelCase , _lowerCAmelCase ) UpperCAmelCase__ : int = info @classmethod def __UpperCAmelCase ( cls , _lowerCAmelCase ): cls.build_naming_info() assert cls.PREFIX is not None UpperCAmelCase__ : Optional[Any] = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(f"You should provide a default value for the param name {k} with value {v}" ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue UpperCAmelCase__ : int = cls.NAMING_INFO["""short_param"""][k] if isinstance(_lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : Tuple = 1 if v else 0 UpperCAmelCase__ : int = """""" if isinstance(_lowerCAmelCase , (int, float) ) else """-""" UpperCAmelCase__ : Union[str, Any] = f"{key}{sep}{v}" name.append(_lowerCAmelCase ) return "_".join(_lowerCAmelCase ) @classmethod def __UpperCAmelCase ( cls , _lowerCAmelCase ): UpperCAmelCase__ : Union[str, Any] = repr[len(cls.PREFIX ) + 1 :] if repr == "": UpperCAmelCase__ : Union[str, Any] = [] else: UpperCAmelCase__ : List[Any] = repr.split("""_""" ) UpperCAmelCase__ : Union[str, Any] = {} for value in values: if "-" in value: UpperCAmelCase__ , UpperCAmelCase__ : int = value.split("""-""" ) else: UpperCAmelCase__ : int = re.sub("""[0-9.]""" , """""" , _lowerCAmelCase ) UpperCAmelCase__ : int = float(re.sub("""[^0-9.]""" , """""" , _lowerCAmelCase ) ) UpperCAmelCase__ : Any = cls.NAMING_INFO["""reverse_short_param"""][p_k] UpperCAmelCase__ : Optional[Any] = p_v for k in cls.DEFAULTS: if k not in parameters: UpperCAmelCase__ : Dict = cls.DEFAULTS[k] return parameters
79
import argparse import os import torch from transformers import FlavaImageCodebook, FlavaImageCodebookConfig def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Any: '''simple docstring''' UpperCAmelCase__ : List[str] = s.rsplit(__lowerCamelCase , __lowerCamelCase ) return new.join(__lowerCamelCase ) def _lowerCamelCase ( __lowerCamelCase ) -> str: '''simple docstring''' # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if """encoder.embeddings""" not in key else 0 for key, param in state_dict.items() ) def _lowerCamelCase ( __lowerCamelCase ) -> int: '''simple docstring''' UpperCAmelCase__ : Union[str, Any] = {} UpperCAmelCase__ : Union[str, Any] = ["""group_1""", """group_2""", """group_3""", """group_4"""] for key, value in state_dict.items(): for group_key in group_keys: if group_key in key: UpperCAmelCase__ : Optional[Any] = key.replace(F"{group_key}." , F"{group_key}.group." ) if "res_path" in key: UpperCAmelCase__ : Optional[int] = key.replace("""res_path.""" , """res_path.path.""" ) if key.endswith(""".w""" ): UpperCAmelCase__ : List[Any] = rreplace(__lowerCamelCase , """.w""" , """.weight""" , 1 ) if key.endswith(""".b""" ): UpperCAmelCase__ : Optional[int] = rreplace(__lowerCamelCase , """.b""" , """.bias""" , 1 ) UpperCAmelCase__ : Union[str, Any] = value.float() return upgrade @torch.no_grad() def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=True ) -> str: '''simple docstring''' from dall_e import Encoder UpperCAmelCase__ : Dict = Encoder() if os.path.exists(__lowerCamelCase ): UpperCAmelCase__ : Optional[Any] = torch.load(__lowerCamelCase ) else: UpperCAmelCase__ : Tuple = torch.hub.load_state_dict_from_url(__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ): UpperCAmelCase__ : Any = ckpt.state_dict() encoder.load_state_dict(__lowerCamelCase ) if config_path is not None: UpperCAmelCase__ : Dict = FlavaImageCodebookConfig.from_pretrained(__lowerCamelCase ) else: UpperCAmelCase__ : Optional[Any] = FlavaImageCodebookConfig() UpperCAmelCase__ : Optional[Any] = FlavaImageCodebook(__lowerCamelCase ).eval() UpperCAmelCase__ : str = encoder.state_dict() UpperCAmelCase__ : Optional[int] = upgrade_state_dict(__lowerCamelCase ) hf_model.load_state_dict(__lowerCamelCase ) UpperCAmelCase__ : List[str] = hf_model.state_dict() UpperCAmelCase__ : Tuple = count_parameters(__lowerCamelCase ) UpperCAmelCase__ : int = count_parameters(__lowerCamelCase ) assert torch.allclose(__lowerCamelCase , __lowerCamelCase , atol=1E-3 ) if save_checkpoint: hf_model.save_pretrained(__lowerCamelCase ) else: return hf_state_dict if __name__ == "__main__": SCREAMING_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 flava checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") SCREAMING_SNAKE_CASE__ : int = parser.parse_args() convert_dalle_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
79
1
import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase_ ( __lowerCamelCase , unittest.TestCase ): __lowerCamelCase = CLIPTokenizer __lowerCamelCase = CLIPTokenizerFast __lowerCamelCase = True __lowerCamelCase = {} __lowerCamelCase = False def __UpperCAmelCase ( self ): super().setUp() # fmt: off UpperCAmelCase__ : Dict = ["""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 UpperCAmelCase__ : Union[str, Any] = dict(zip(_lowerCAmelCase , range(len(_lowerCAmelCase ) ) ) ) UpperCAmelCase__ : Optional[int] = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>"""] UpperCAmelCase__ : Any = {"""unk_token""": """<unk>"""} UpperCAmelCase__ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCAmelCase__ : str = 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(_lowerCAmelCase ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(_lowerCAmelCase ) ) def __UpperCAmelCase ( self , **_lowerCAmelCase ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **_lowerCAmelCase ) def __UpperCAmelCase ( self , **_lowerCAmelCase ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **_lowerCAmelCase ) def __UpperCAmelCase ( self , _lowerCAmelCase ): UpperCAmelCase__ : Union[str, Any] = """lower newer""" UpperCAmelCase__ : str = """lower newer""" return input_text, output_text def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[int] = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCAmelCase__ : int = """lower newer""" UpperCAmelCase__ : List[str] = ["""lo""", """w""", """er</w>""", """n""", """e""", """w""", """er</w>"""] UpperCAmelCase__ : str = tokenizer.tokenize(_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) UpperCAmelCase__ : List[str] = tokens + [tokenizer.unk_token] UpperCAmelCase__ : Dict = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) , _lowerCAmelCase ) @require_ftfy def __UpperCAmelCase ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCAmelCase__ : Tuple = self.tokenizer_class.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) UpperCAmelCase__ : List[Any] = self.rust_tokenizer_class.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = """A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d.""" UpperCAmelCase__ : Dict = tokenizer_s.tokenize(_lowerCAmelCase ) UpperCAmelCase__ : List[str] = tokenizer_r.tokenize(_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways UpperCAmelCase__ : Optional[int] = """xa\u0303y""" + """ """ + """x\xe3y""" UpperCAmelCase__ : int = tokenizer_s.tokenize(_lowerCAmelCase ) UpperCAmelCase__ : int = tokenizer_r.tokenize(_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) # Test that the tokenization is identical on unicode of space type UpperCAmelCase__ : Tuple = [ """\u0009""", # (horizontal tab, '\t') """\u000B""", # (vertical tab) """\u000C""", # (form feed) """\u0020""", # (space, ' ') """\u200E""", # (left-to-right mark):w """\u200F""", # (right-to-left mark) ] for unicode_seq in spaces_unicodes: UpperCAmelCase__ : Optional[Any] = tokenizer_s.tokenize(_lowerCAmelCase ) UpperCAmelCase__ : List[Any] = tokenizer_r.tokenize(_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) # Test that the tokenization is identical on unicode of line break type UpperCAmelCase__ : List[Any] = [ """\u000A""", # (line feed, '\n') """\r\n""", # (carriage return and line feed, '\r\n') """\u000D""", # (carriage return, '\r') """\r""", # (carriage return, '\r') """\u000D""", # (carriage return, '\r') """\u2028""", # (line separator) """\u2029""", # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: UpperCAmelCase__ : Optional[int] = tokenizer_s.tokenize(_lowerCAmelCase ) UpperCAmelCase__ : int = tokenizer_r.tokenize(_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) def __UpperCAmelCase ( self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCAmelCase__ : Union[str, Any] = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` UpperCAmelCase__ : Dict = f"{text_of_1_token} {text_of_1_token}" UpperCAmelCase__ : Dict = self.rust_tokenizer_class.from_pretrained( _lowerCAmelCase , use_fast=_lowerCAmelCase , ) UpperCAmelCase__ : Optional[int] = tokenizer_r(_lowerCAmelCase , return_offsets_mapping=_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ) self.assertEqual(encoding.offset_mapping[0] , (0, len(_lowerCAmelCase )) ) self.assertEqual( encoding.offset_mapping[1] , (len(_lowerCAmelCase ) + 1, len(_lowerCAmelCase ) + 1 + len(_lowerCAmelCase )) , ) UpperCAmelCase__ : int = f" {text}" UpperCAmelCase__ : Optional[int] = self.rust_tokenizer_class.from_pretrained( _lowerCAmelCase , use_fast=_lowerCAmelCase , ) UpperCAmelCase__ : Optional[Any] = tokenizer_r(_lowerCAmelCase , return_offsets_mapping=_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(_lowerCAmelCase )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(_lowerCAmelCase ) + 1, 1 + len(_lowerCAmelCase ) + 1 + len(_lowerCAmelCase )) , ) def __UpperCAmelCase ( self ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(_lowerCAmelCase ) as context: self.rust_tokenizer_class.from_pretrained("""robot-test/old-clip-tokenizer""" ) self.assertTrue( context.exception.args[0].startswith( """The `backend_tokenizer` provided does not match the expected format.""" ) ) @require_ftfy def __UpperCAmelCase ( self ): super().test_tokenization_python_rust_equals() def __UpperCAmelCase ( self ): # CLIP always lower cases letters pass
79
def _lowerCamelCase ( __lowerCamelCase ) -> int: '''simple docstring''' return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def _lowerCamelCase ( __lowerCamelCase ) -> bool: '''simple docstring''' UpperCAmelCase__ : Any = 0 UpperCAmelCase__ : Union[str, Any] = number while duplicate > 0: UpperCAmelCase__ , UpperCAmelCase__ : List[Any] = divmod(__lowerCamelCase , 10 ) fact_sum += factorial(__lowerCamelCase ) return fact_sum == number if __name__ == "__main__": print("""Program to check whether a number is a Krisnamurthy Number or not.""") SCREAMING_SNAKE_CASE__ : Optional[Any] = int(input("""Enter number: """).strip()) print( f'''{number} is {"" if krishnamurthy(number) else "not "}a Krishnamurthy Number.''' )
79
1
import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType SCREAMING_SNAKE_CASE__ : Optional[List[str]] = None SCREAMING_SNAKE_CASE__ : Optional[Any] = """<""" if sys.byteorder == """little""" else """>""" # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image SCREAMING_SNAKE_CASE__ : List[Any] = [ np.dtype("""|b1"""), np.dtype("""|u1"""), np.dtype("""<u2"""), np.dtype(""">u2"""), np.dtype("""<i2"""), np.dtype(""">i2"""), np.dtype("""<u4"""), np.dtype(""">u4"""), np.dtype("""<i4"""), np.dtype(""">i4"""), np.dtype("""<f4"""), np.dtype(""">f4"""), np.dtype("""<f8"""), np.dtype(""">f8"""), ] @dataclass class UpperCAmelCase_ : __lowerCamelCase = True __lowerCamelCase = None # Automatically constructed __lowerCamelCase = "PIL.Image.Image" __lowerCamelCase = pa.struct({'bytes': pa.binary(), 'path': pa.string()} ) __lowerCamelCase = field(default='Image' , init=__lowerCamelCase , repr=__lowerCamelCase ) def __call__( self ): return self.pa_type def __UpperCAmelCase ( self , _lowerCAmelCase ): if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) if isinstance(_lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : Dict = np.array(_lowerCAmelCase ) if isinstance(_lowerCAmelCase , _lowerCAmelCase ): return {"path": value, "bytes": None} elif isinstance(_lowerCAmelCase , _lowerCAmelCase ): return {"path": None, "bytes": value} elif isinstance(_lowerCAmelCase , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(_lowerCAmelCase ) elif isinstance(_lowerCAmelCase , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(_lowerCAmelCase ) elif value.get("""path""" ) is not None and os.path.isfile(value["""path"""] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get("""path""" )} elif value.get("""bytes""" ) is not None or value.get("""path""" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("""bytes""" ), "path": value.get("""path""" )} else: raise ValueError( f"An image sample should have one of 'path' or 'bytes' but they are missing or None in {value}." ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase=None ): if not self.decode: raise RuntimeError("""Decoding is disabled for this feature. Please use Image(decode=True) instead.""" ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support decoding images, please install 'Pillow'.""" ) if token_per_repo_id is None: UpperCAmelCase__ : Union[str, Any] = {} UpperCAmelCase__ , UpperCAmelCase__ : Tuple = value["""path"""], value["""bytes"""] if bytes_ is None: if path is None: raise ValueError(f"An image should have one of 'path' or 'bytes' but both are None in {value}." ) else: if is_local_path(_lowerCAmelCase ): UpperCAmelCase__ : str = PIL.Image.open(_lowerCAmelCase ) else: UpperCAmelCase__ : Any = path.split("""::""" )[-1] try: UpperCAmelCase__ : int = string_to_dict(_lowerCAmelCase , config.HUB_DATASETS_URL )["""repo_id"""] UpperCAmelCase__ : int = token_per_repo_id.get(_lowerCAmelCase ) except ValueError: UpperCAmelCase__ : Any = None with xopen(_lowerCAmelCase , """rb""" , use_auth_token=_lowerCAmelCase ) as f: UpperCAmelCase__ : str = BytesIO(f.read() ) UpperCAmelCase__ : str = PIL.Image.open(bytes_ ) else: UpperCAmelCase__ : List[Any] = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def __UpperCAmelCase ( self ): from .features import Value return ( self if self.decode else { "bytes": Value("""binary""" ), "path": Value("""string""" ), } ) def __UpperCAmelCase ( self , _lowerCAmelCase ): if pa.types.is_string(storage.type ): UpperCAmelCase__ : Any = pa.array([None] * len(_lowerCAmelCase ) , type=pa.binary() ) UpperCAmelCase__ : Union[str, Any] = pa.StructArray.from_arrays([bytes_array, storage] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): UpperCAmelCase__ : Optional[int] = pa.array([None] * len(_lowerCAmelCase ) , type=pa.string() ) UpperCAmelCase__ : int = pa.StructArray.from_arrays([storage, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("""bytes""" ) >= 0: UpperCAmelCase__ : Optional[Any] = storage.field("""bytes""" ) else: UpperCAmelCase__ : int = pa.array([None] * len(_lowerCAmelCase ) , type=pa.binary() ) if storage.type.get_field_index("""path""" ) >= 0: UpperCAmelCase__ : Dict = storage.field("""path""" ) else: UpperCAmelCase__ : Dict = pa.array([None] * len(_lowerCAmelCase ) , type=pa.string() ) UpperCAmelCase__ : Tuple = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): UpperCAmelCase__ : str = pa.array( [encode_np_array(np.array(_lowerCAmelCase ) )["""bytes"""] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) UpperCAmelCase__ : Any = pa.array([None] * len(_lowerCAmelCase ) , type=pa.string() ) UpperCAmelCase__ : Optional[int] = pa.StructArray.from_arrays( [bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(_lowerCAmelCase , self.pa_type ) def __UpperCAmelCase ( self , _lowerCAmelCase ): @no_op_if_value_is_null def path_to_bytes(_lowerCAmelCase ): with xopen(_lowerCAmelCase , """rb""" ) as f: UpperCAmelCase__ : Optional[int] = f.read() return bytes_ UpperCAmelCase__ : Optional[Any] = pa.array( [ (path_to_bytes(x["""path"""] ) if x["""bytes"""] is None else x["""bytes"""]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) UpperCAmelCase__ : Optional[int] = pa.array( [os.path.basename(_lowerCAmelCase ) if path is not None else None for path in storage.field("""path""" ).to_pylist()] , type=pa.string() , ) UpperCAmelCase__ : List[Any] = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(_lowerCAmelCase , self.pa_type ) def _lowerCamelCase ( ) -> List[str]: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() UpperCAmelCase__ : List[Any] = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def _lowerCamelCase ( __lowerCamelCase ) -> bytes: '''simple docstring''' UpperCAmelCase__ : Tuple = BytesIO() if image.format in list_image_compression_formats(): UpperCAmelCase__ : Union[str, Any] = image.format else: UpperCAmelCase__ : List[str] = """PNG""" if image.mode in ["""1""", """L""", """LA""", """RGB""", """RGBA"""] else """TIFF""" image.save(__lowerCamelCase , format=__lowerCamelCase ) return buffer.getvalue() def _lowerCamelCase ( __lowerCamelCase ) -> dict: '''simple docstring''' if hasattr(__lowerCamelCase , """filename""" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(__lowerCamelCase )} def _lowerCamelCase ( __lowerCamelCase ) -> dict: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) UpperCAmelCase__ : Optional[int] = array.dtype UpperCAmelCase__ : Optional[Any] = dtype.byteorder if dtype.byteorder != """=""" else _NATIVE_BYTEORDER UpperCAmelCase__ : List[Any] = dtype.kind UpperCAmelCase__ : Dict = dtype.itemsize UpperCAmelCase__ : Union[str, Any] = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: UpperCAmelCase__ : Union[str, Any] = np.dtype("""|u1""" ) if dtype_kind not in ["u", "i"]: raise TypeError( F"Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays." ) if dtype is not dest_dtype: warnings.warn(F"Downcasting array dtype {dtype} to {dest_dtype} to be compatible with 'Pillow'" ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: UpperCAmelCase__ : List[Any] = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: UpperCAmelCase__ : int = dtype_byteorder + dtype_kind + str(__lowerCamelCase ) UpperCAmelCase__ : Union[str, Any] = np.dtype(__lowerCamelCase ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(F"Downcasting array dtype {dtype} to {dest_dtype} to be compatible with 'Pillow'" ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( F"Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}" ) UpperCAmelCase__ : int = PIL.Image.fromarray(array.astype(__lowerCamelCase ) ) return {"path": None, "bytes": image_to_bytes(__lowerCamelCase )} def _lowerCamelCase ( __lowerCamelCase ) -> List[dict]: '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) if objs: UpperCAmelCase__ , UpperCAmelCase__ : List[str] = first_non_null_value(__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(__lowerCamelCase , np.ndarray ): UpperCAmelCase__ : str = no_op_if_value_is_null(__lowerCamelCase ) return [obj_to_image_dict_func(__lowerCamelCase ) for obj in objs] elif isinstance(__lowerCamelCase , PIL.Image.Image ): UpperCAmelCase__ : List[str] = no_op_if_value_is_null(__lowerCamelCase ) return [obj_to_image_dict_func(__lowerCamelCase ) for obj in objs] else: return objs else: return objs
79
def _lowerCamelCase ( __lowerCamelCase = 100_0000 ) -> int: '''simple docstring''' UpperCAmelCase__ : Tuple = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , __lowerCamelCase ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
79
1
SCREAMING_SNAKE_CASE__ : Dict = [0, 2, 4, 6, 8] SCREAMING_SNAKE_CASE__ : Optional[Any] = [1, 3, 5, 7, 9] def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> int: '''simple docstring''' if remaining_length == 0: if digits[0] == 0 or digits[-1] == 0: return 0 for i in range(length // 2 - 1 , -1 , -1 ): remainder += digits[i] + digits[length - i - 1] if remainder % 2 == 0: return 0 remainder //= 10 return 1 if remaining_length == 1: if remainder % 2 == 0: return 0 UpperCAmelCase__ : Optional[int] = 0 for digit in range(10 ): UpperCAmelCase__ : Dict = digit result += reversible_numbers( 0 , (remainder + 2 * digit) // 10 , __lowerCamelCase , __lowerCamelCase ) return result UpperCAmelCase__ : Dict = 0 for digita in range(10 ): UpperCAmelCase__ : Union[str, Any] = digita if (remainder + digita) % 2 == 0: UpperCAmelCase__ : Any = ODD_DIGITS else: UpperCAmelCase__ : Optional[Any] = EVEN_DIGITS for digita in other_parity_digits: UpperCAmelCase__ : Optional[Any] = digita result += reversible_numbers( remaining_length - 2 , (remainder + digita + digita) // 10 , __lowerCamelCase , __lowerCamelCase , ) return result def _lowerCamelCase ( __lowerCamelCase = 9 ) -> int: '''simple docstring''' UpperCAmelCase__ : Union[str, Any] = 0 for length in range(1 , max_power + 1 ): result += reversible_numbers(__lowerCamelCase , 0 , [0] * length , __lowerCamelCase ) return result if __name__ == "__main__": print(f'''{solution() = }''')
79
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Tuple = { """google/realm-cc-news-pretrained-embedder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-encoder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-scorer""": ( """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-openqa""": ( """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json""" ), """google/realm-orqa-nq-openqa""": """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json""", """google/realm-orqa-nq-reader""": """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json""", """google/realm-orqa-wq-openqa""": """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json""", """google/realm-orqa-wq-reader""": """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json""", # See all REALM models at https://huggingface.co/models?filter=realm } class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = 'realm' def __init__( self , _lowerCAmelCase=30522 , _lowerCAmelCase=768 , _lowerCAmelCase=128 , _lowerCAmelCase=12 , _lowerCAmelCase=12 , _lowerCAmelCase=8 , _lowerCAmelCase=3072 , _lowerCAmelCase="gelu_new" , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.1 , _lowerCAmelCase=512 , _lowerCAmelCase=2 , _lowerCAmelCase=0.0_2 , _lowerCAmelCase=1e-12 , _lowerCAmelCase=256 , _lowerCAmelCase=10 , _lowerCAmelCase=1e-3 , _lowerCAmelCase=5 , _lowerCAmelCase=320 , _lowerCAmelCase=13353718 , _lowerCAmelCase=5000 , _lowerCAmelCase=1 , _lowerCAmelCase=0 , _lowerCAmelCase=2 , **_lowerCAmelCase , ): super().__init__(pad_token_id=_lowerCAmelCase , bos_token_id=_lowerCAmelCase , eos_token_id=_lowerCAmelCase , **_lowerCAmelCase ) # Common config UpperCAmelCase__ : List[Any] = vocab_size UpperCAmelCase__ : Dict = max_position_embeddings UpperCAmelCase__ : Any = hidden_size UpperCAmelCase__ : str = retriever_proj_size UpperCAmelCase__ : Tuple = num_hidden_layers UpperCAmelCase__ : List[str] = num_attention_heads UpperCAmelCase__ : List[Any] = num_candidates UpperCAmelCase__ : str = intermediate_size UpperCAmelCase__ : str = hidden_act UpperCAmelCase__ : Optional[Any] = hidden_dropout_prob UpperCAmelCase__ : str = attention_probs_dropout_prob UpperCAmelCase__ : Union[str, Any] = initializer_range UpperCAmelCase__ : Any = type_vocab_size UpperCAmelCase__ : Optional[Any] = layer_norm_eps # Reader config UpperCAmelCase__ : str = span_hidden_size UpperCAmelCase__ : Union[str, Any] = max_span_width UpperCAmelCase__ : List[str] = reader_layer_norm_eps UpperCAmelCase__ : Dict = reader_beam_size UpperCAmelCase__ : Union[str, Any] = reader_seq_len # Retrieval config UpperCAmelCase__ : List[Any] = num_block_records UpperCAmelCase__ : List[Any] = searcher_beam_size
79
1
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : str = { """microsoft/markuplm-base""": """https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json""", """microsoft/markuplm-large""": """https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json""", } class UpperCAmelCase_ ( __lowerCamelCase ): __lowerCamelCase = 'markuplm' def __init__( self , _lowerCAmelCase=30522 , _lowerCAmelCase=768 , _lowerCAmelCase=12 , _lowerCAmelCase=12 , _lowerCAmelCase=3072 , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.1 , _lowerCAmelCase=512 , _lowerCAmelCase=2 , _lowerCAmelCase=0.0_2 , _lowerCAmelCase=1e-12 , _lowerCAmelCase=0 , _lowerCAmelCase=0 , _lowerCAmelCase=2 , _lowerCAmelCase=256 , _lowerCAmelCase=1024 , _lowerCAmelCase=216 , _lowerCAmelCase=1001 , _lowerCAmelCase=32 , _lowerCAmelCase=50 , _lowerCAmelCase="absolute" , _lowerCAmelCase=True , _lowerCAmelCase=None , **_lowerCAmelCase , ): super().__init__( pad_token_id=_lowerCAmelCase , bos_token_id=_lowerCAmelCase , eos_token_id=_lowerCAmelCase , **_lowerCAmelCase , ) UpperCAmelCase__ : Optional[int] = vocab_size UpperCAmelCase__ : Any = hidden_size UpperCAmelCase__ : Dict = num_hidden_layers UpperCAmelCase__ : List[str] = num_attention_heads UpperCAmelCase__ : int = hidden_act UpperCAmelCase__ : List[Any] = intermediate_size UpperCAmelCase__ : Dict = hidden_dropout_prob UpperCAmelCase__ : Optional[int] = attention_probs_dropout_prob UpperCAmelCase__ : Tuple = max_position_embeddings UpperCAmelCase__ : Dict = type_vocab_size UpperCAmelCase__ : Any = initializer_range UpperCAmelCase__ : Dict = layer_norm_eps UpperCAmelCase__ : Optional[Any] = position_embedding_type UpperCAmelCase__ : List[str] = use_cache UpperCAmelCase__ : Union[str, Any] = classifier_dropout # additional properties UpperCAmelCase__ : List[str] = max_depth UpperCAmelCase__ : int = max_xpath_tag_unit_embeddings UpperCAmelCase__ : Union[str, Any] = max_xpath_subs_unit_embeddings UpperCAmelCase__ : Union[str, Any] = tag_pad_id UpperCAmelCase__ : List[str] = subs_pad_id UpperCAmelCase__ : Optional[int] = xpath_unit_hidden_size
79
import gc import unittest from parameterized import parameterized from diffusers import FlaxUNetaDConditionModel from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import load_hf_numpy, require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp @slow @require_flax class UpperCAmelCase_ ( unittest.TestCase ): def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase ): return f"gaussian_noise_s={seed}_shape={'_'.join([str(_lowerCAmelCase ) for s in shape] )}.npy" def __UpperCAmelCase ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() def __UpperCAmelCase ( self , _lowerCAmelCase=0 , _lowerCAmelCase=(4, 4, 64, 64) , _lowerCAmelCase=False ): UpperCAmelCase__ : Optional[Any] = jnp.bfloataa if fpaa else jnp.floataa UpperCAmelCase__ : Union[str, Any] = jnp.array(load_hf_numpy(self.get_file_format(_lowerCAmelCase , _lowerCAmelCase ) ) , dtype=_lowerCAmelCase ) return image def __UpperCAmelCase ( self , _lowerCAmelCase=False , _lowerCAmelCase="CompVis/stable-diffusion-v1-4" ): UpperCAmelCase__ : int = jnp.bfloataa if fpaa else jnp.floataa UpperCAmelCase__ : Optional[Any] = """bf16""" if fpaa else None UpperCAmelCase__ , UpperCAmelCase__ : Optional[Any] = FlaxUNetaDConditionModel.from_pretrained( _lowerCAmelCase , subfolder="""unet""" , dtype=_lowerCAmelCase , revision=_lowerCAmelCase ) return model, params def __UpperCAmelCase ( self , _lowerCAmelCase=0 , _lowerCAmelCase=(4, 77, 768) , _lowerCAmelCase=False ): UpperCAmelCase__ : Optional[int] = jnp.bfloataa if fpaa else jnp.floataa UpperCAmelCase__ : Optional[int] = jnp.array(load_hf_numpy(self.get_file_format(_lowerCAmelCase , _lowerCAmelCase ) ) , dtype=_lowerCAmelCase ) return hidden_states @parameterized.expand( [ # fmt: off [83, 4, [-0.2_3_2_3, -0.1_3_0_4, 0.0_8_1_3, -0.3_0_9_3, -0.0_9_1_9, -0.1_5_7_1, -0.1_1_2_5, -0.5_8_0_6]], [17, 0.5_5, [-0.0_8_3_1, -0.2_4_4_3, 0.0_9_0_1, -0.0_9_1_9, 0.3_3_9_6, 0.0_1_0_3, -0.3_7_4_3, 0.0_7_0_1]], [8, 0.8_9, [-0.4_8_6_3, 0.0_8_5_9, 0.0_8_7_5, -0.1_6_5_8, 0.9_1_9_9, -0.0_1_1_4, 0.4_8_3_9, 0.4_6_3_9]], [3, 1000, [-0.5_6_4_9, 0.2_4_0_2, -0.5_5_1_8, 0.1_2_4_8, 1.1_3_2_8, -0.2_4_4_3, -0.0_3_2_5, -1.0_0_7_8]], # fmt: on ] ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ , UpperCAmelCase__ : Optional[Any] = self.get_unet_model(model_id="""CompVis/stable-diffusion-v1-4""" , fpaa=_lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = self.get_latents(_lowerCAmelCase , fpaa=_lowerCAmelCase ) UpperCAmelCase__ : Dict = self.get_encoder_hidden_states(_lowerCAmelCase , fpaa=_lowerCAmelCase ) UpperCAmelCase__ : Optional[Any] = model.apply( {"""params""": params} , _lowerCAmelCase , jnp.array(_lowerCAmelCase , dtype=jnp.intaa ) , encoder_hidden_states=_lowerCAmelCase , ).sample assert sample.shape == latents.shape UpperCAmelCase__ : Dict = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ) , dtype=jnp.floataa ) UpperCAmelCase__ : List[Any] = jnp.array(_lowerCAmelCase , dtype=jnp.floataa ) # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, in the same hardware assert jnp.allclose(_lowerCAmelCase , _lowerCAmelCase , atol=1e-2 ) @parameterized.expand( [ # fmt: off [83, 4, [0.1_5_1_4, 0.0_8_0_7, 0.1_6_2_4, 0.1_0_1_6, -0.1_8_9_6, 0.0_2_6_3, 0.0_6_7_7, 0.2_3_1_0]], [17, 0.5_5, [0.1_1_6_4, -0.0_2_1_6, 0.0_1_7_0, 0.1_5_8_9, -0.3_1_2_0, 0.1_0_0_5, -0.0_5_8_1, -0.1_4_5_8]], [8, 0.8_9, [-0.1_7_5_8, -0.0_1_6_9, 0.1_0_0_4, -0.1_4_1_1, 0.1_3_1_2, 0.1_1_0_3, -0.1_9_9_6, 0.2_1_3_9]], [3, 1000, [0.1_2_1_4, 0.0_3_5_2, -0.0_7_3_1, -0.1_5_6_2, -0.0_9_9_4, -0.0_9_0_6, -0.2_3_4_0, -0.0_5_3_9]], # fmt: on ] ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ , UpperCAmelCase__ : Tuple = self.get_unet_model(model_id="""stabilityai/stable-diffusion-2""" , fpaa=_lowerCAmelCase ) UpperCAmelCase__ : Union[str, Any] = self.get_latents(_lowerCAmelCase , shape=(4, 4, 96, 96) , fpaa=_lowerCAmelCase ) UpperCAmelCase__ : Any = self.get_encoder_hidden_states(_lowerCAmelCase , shape=(4, 77, 1024) , fpaa=_lowerCAmelCase ) UpperCAmelCase__ : Dict = model.apply( {"""params""": params} , _lowerCAmelCase , jnp.array(_lowerCAmelCase , dtype=jnp.intaa ) , encoder_hidden_states=_lowerCAmelCase , ).sample assert sample.shape == latents.shape UpperCAmelCase__ : Any = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ) , dtype=jnp.floataa ) UpperCAmelCase__ : Any = jnp.array(_lowerCAmelCase , dtype=jnp.floataa ) # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, on the same hardware assert jnp.allclose(_lowerCAmelCase , _lowerCAmelCase , atol=1e-2 )
79
1
from math import log from scipy.constants import Boltzmann, physical_constants SCREAMING_SNAKE_CASE__ : Optional[int] = 3_00 # TEMPERATURE (unit = K) def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) -> float: '''simple docstring''' if donor_conc <= 0: raise ValueError("""Donor concentration should be positive""" ) elif acceptor_conc <= 0: raise ValueError("""Acceptor concentration should be positive""" ) elif intrinsic_conc <= 0: raise ValueError("""Intrinsic concentration should be positive""" ) elif donor_conc <= intrinsic_conc: raise ValueError( """Donor concentration should be greater than intrinsic concentration""" ) elif acceptor_conc <= intrinsic_conc: raise ValueError( """Acceptor concentration should be greater than intrinsic concentration""" ) else: return ( Boltzmann * T * log((donor_conc * acceptor_conc) / intrinsic_conc**2 ) / physical_constants["electron volt"][0] ) if __name__ == "__main__": import doctest doctest.testmod()
79
import json import os import tempfile import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class UpperCAmelCase_ ( unittest.TestCase ): def __init__( self , _lowerCAmelCase , _lowerCAmelCase=7 , _lowerCAmelCase=3 , _lowerCAmelCase=18 , _lowerCAmelCase=30 , _lowerCAmelCase=400 , _lowerCAmelCase=True , _lowerCAmelCase=None , _lowerCAmelCase=True , ): UpperCAmelCase__ : List[str] = size if size is not None else {"""height""": 18, """width""": 18} UpperCAmelCase__ : Union[str, Any] = parent UpperCAmelCase__ : int = batch_size UpperCAmelCase__ : Tuple = num_channels UpperCAmelCase__ : Dict = image_size UpperCAmelCase__ : List[Any] = min_resolution UpperCAmelCase__ : str = max_resolution UpperCAmelCase__ : Union[str, Any] = do_resize UpperCAmelCase__ : Tuple = size UpperCAmelCase__ : int = do_normalize def __UpperCAmelCase ( self ): return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8_8_6_6_4_4_3_6_3_4_0_3_3_2_0_3, 0.6_6_1_8_8_2_9_3_6_9_5_4_4_9_8_3, 0.3_8_9_1_7_4_6_4_0_1_7_8_6_8_0_4], [-0.6_0_4_2_5_5_9_1_4_6_8_8_1_1_0_4, -0.0_2_2_9_5_0_0_8_8_6_0_5_2_8_4_6_9, 0.5_4_2_3_7_9_7_3_6_9_0_0_3_2_9_6], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class UpperCAmelCase_ ( __lowerCamelCase , unittest.TestCase ): __lowerCamelCase = ImageGPTImageProcessor if is_vision_available() else None def __UpperCAmelCase ( self ): UpperCAmelCase__ : Any = ImageGPTImageProcessingTester(self ) @property def __UpperCAmelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __UpperCAmelCase ( self ): UpperCAmelCase__ : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCAmelCase , """clusters""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """do_resize""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """size""" ) ) self.assertTrue(hasattr(_lowerCAmelCase , """do_normalize""" ) ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) UpperCAmelCase__ : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) UpperCAmelCase__ : Optional[int] = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(_lowerCAmelCase , obj[key] ) ) else: self.assertEqual(obj[key] , _lowerCAmelCase ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase__ : Union[str, Any] = os.path.join(_lowerCAmelCase , """image_processor.json""" ) image_processor_first.to_json_file(_lowerCAmelCase ) UpperCAmelCase__ : Optional[Any] = self.image_processing_class.from_json_file(_lowerCAmelCase ).to_dict() UpperCAmelCase__ : Dict = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(_lowerCAmelCase , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , _lowerCAmelCase ) def __UpperCAmelCase ( self ): UpperCAmelCase__ : str = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(_lowerCAmelCase ) UpperCAmelCase__ : List[Any] = self.image_processing_class.from_pretrained(_lowerCAmelCase ).to_dict() UpperCAmelCase__ : Tuple = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(_lowerCAmelCase , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , _lowerCAmelCase ) @unittest.skip("""ImageGPT requires clusters at initialization""" ) def __UpperCAmelCase ( self ): pass def _lowerCamelCase ( ) -> Tuple: '''simple docstring''' UpperCAmelCase__ : Any = load_dataset("""hf-internal-testing/fixtures_image_utils""" , split="""test""" ) UpperCAmelCase__ : Dict = Image.open(dataset[4]["""file"""] ) UpperCAmelCase__ : Optional[Any] = Image.open(dataset[5]["""file"""] ) UpperCAmelCase__ : List[Any] = [imagea, imagea] return images @require_vision @require_torch class UpperCAmelCase_ ( unittest.TestCase ): @slow def __UpperCAmelCase ( self ): UpperCAmelCase__ : Tuple = ImageGPTImageProcessor.from_pretrained("""openai/imagegpt-small""" ) UpperCAmelCase__ : int = prepare_images() # test non-batched UpperCAmelCase__ : List[str] = image_processing(images[0] , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 1024) ) UpperCAmelCase__ : List[Any] = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() , _lowerCAmelCase ) # test batched UpperCAmelCase__ : List[str] = image_processing(_lowerCAmelCase , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 1024) ) UpperCAmelCase__ : Any = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() , _lowerCAmelCase )
79
1