code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" lowercase_ : Optional[Any] = checkpoints.load_tax_checkpoint(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = flatten_dict(__SCREAMING_SNAKE_CASE ) return flax_params def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" lowercase_ : List[Any] = {} lowercase_ : List[Any] = { '''token_embedder''': '''embeddings''', '''encoder_norm''': '''layernorm''', '''kernel''': '''weight''', '''.out''': '''.output''', '''scale''': '''weight''', '''embedders_0.pos_embedding''': '''row_embedder.weight''', '''embedders_1.pos_embedding''': '''column_embedder.weight''', } lowercase_ : str = { '''query''': '''attention.query''', '''key''': '''attention.key''', '''value''': '''attention.value''', '''output.dense''': '''output''', '''encoder_decoder_attention.o''': '''encoder_decoder_attention.attention.o''', '''pre_self_attention_layer_norm''': '''self_attention.layer_norm''', '''pre_cross_attention_layer_norm''': '''encoder_decoder_attention.layer_norm''', '''mlp.''': '''mlp.DenseReluDense.''', '''pre_mlp_layer_norm''': '''mlp.layer_norm''', '''self_attention.o''': '''self_attention.attention.o''', '''decoder.embeddings.embedding''': '''decoder.embed_tokens.weight''', '''decoder.relpos_bias.rel_embedding''': '''decoder.layer.0.self_attention.attention.relative_attention_bias.weight''', '''decoder.decoder_norm.weight''': '''decoder.final_layer_norm.weight''', '''decoder.logits_dense.weight''': '''decoder.lm_head.weight''', } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key lowercase_ : Dict = '''.'''.join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): lowercase_ : List[str] = new_key.replace(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): lowercase_ : int = new_key.replace(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number lowercase_ : List[str] = re.sub(R'''layers_(\d+)''' , R'''layer.\1''' , __SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = new_key.replace('''encoder''' , '''encoder.encoder''' ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number lowercase_ : Any = re.sub(R'''layers_(\d+)''' , R'''layer.\1''' , __SCREAMING_SNAKE_CASE ) lowercase_ : str = flax_dict[key] lowercase_ : List[str] = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): lowercase_ : Tuple = torch.from_numpy(converted_dict[key].T ) else: lowercase_ : Dict = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : Union[str, Any]=False ): """simple docstring""" lowercase_ : Tuple = get_flax_param(__SCREAMING_SNAKE_CASE ) if not use_large: lowercase_ : Any = PixaStructVisionConfig() lowercase_ : Optional[Any] = PixaStructTextConfig() else: lowercase_ : Tuple = PixaStructVisionConfig( hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 ) lowercase_ : int = PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 ) lowercase_ : Any = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=__SCREAMING_SNAKE_CASE ) lowercase_ : Any = PixaStructForConditionalGeneration(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = rename_and_convert_flax_params(__SCREAMING_SNAKE_CASE ) model.load_state_dict(__SCREAMING_SNAKE_CASE ) lowercase_ : str = AutoTokenizer.from_pretrained('''ybelkada/test-pix2struct-tokenizer''' ) lowercase_ : List[str] = PixaStructImageProcessor() lowercase_ : Tuple = PixaStructProcessor(image_processor=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE ) if use_large: lowercase_ : str = 4096 lowercase_ : Dict = True # mkdir if needed os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) processor.save_pretrained(__SCREAMING_SNAKE_CASE ) print('''Model saved in {}'''.format(__SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": _lowercase : Tuple = argparse.ArgumentParser() parser.add_argument("--t5x_checkpoint_path", default=None, type=str, help="Path to the original T5x checkpoint.") parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--use_large", action="store_true", help="Use large model.") parser.add_argument("--is_vqa", action="store_true", help="Use large model.") _lowercase : Tuple = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
93
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : str = logging.get_logger(__name__) _lowercase : List[Any] = "▁" _lowercase : List[Any] = {"vocab_file": "sentencepiece.bpe.model"} _lowercase : Optional[int] = { "vocab_file": { "facebook/mbart-large-en-ro": ( "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model" ), "facebook/mbart-large-cc25": ( "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model" ), } } _lowercase : str = { "facebook/mbart-large-en-ro": 1_0_2_4, "facebook/mbart-large-cc25": 1_0_2_4, } # fmt: off _lowercase : List[Any] = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"] class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase_ = [] lowerCAmelCase_ = [] def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="</s>" , __SCREAMING_SNAKE_CASE="<s>" , __SCREAMING_SNAKE_CASE="<unk>" , __SCREAMING_SNAKE_CASE="<pad>" , __SCREAMING_SNAKE_CASE="<mask>" , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : Any = AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else mask_token lowercase_ : int = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , mask_token=__SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , src_lang=__SCREAMING_SNAKE_CASE , tgt_lang=__SCREAMING_SNAKE_CASE , additional_special_tokens=__SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__SCREAMING_SNAKE_CASE ) ) lowercase_ : List[str] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token lowercase_ : Tuple = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab lowercase_ : str = 1 lowercase_ : str = len(self.sp_model ) lowercase_ : List[Any] = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__SCREAMING_SNAKE_CASE ) } lowercase_ : Union[str, Any] = {v: k for k, v in self.lang_code_to_id.items()} lowercase_ : List[Any] = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) lowercase_ : Union[str, Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} lowercase_ : Optional[Any] = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) lowercase_ : Optional[Any] = src_lang if src_lang is not None else '''en_XX''' lowercase_ : str = self.lang_code_to_id[self._src_lang] lowercase_ : Optional[Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self ): """simple docstring""" lowercase_ : Optional[int] = self.__dict__.copy() lowercase_ : Dict = None lowercase_ : Any = self.sp_model.serialized_model_proto() return state def __setstate__( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase_ : Dict = {} lowercase_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def _snake_case ( self ): """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def _snake_case ( self ): """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__SCREAMING_SNAKE_CASE , token_ids_a=__SCREAMING_SNAKE_CASE , already_has_special_tokens=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = [1] * len(self.prefix_tokens ) lowercase_ : Tuple = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE )) + ([0] * len(__SCREAMING_SNAKE_CASE )) + suffix_ones def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" lowercase_ : Optional[int] = [self.sep_token_id] lowercase_ : 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] def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) lowercase_ : Optional[Any] = src_lang lowercase_ : Dict = self(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = self.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = tgt_lang_id return inputs def _snake_case ( self ): """simple docstring""" lowercase_ : str = {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" return self.sp_model.encode(__SCREAMING_SNAKE_CASE , out_type=__SCREAMING_SNAKE_CASE ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowercase_ : Any = self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : int = ''''''.join(__SCREAMING_SNAKE_CASE ).replace(__SCREAMING_SNAKE_CASE , ''' ''' ).strip() return out_string def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): """simple docstring""" if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowercase_ : Tuple = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(__SCREAMING_SNAKE_CASE , '''wb''' ) as fi: lowercase_ : List[str] = self.sp_model.serialized_model_proto() fi.write(__SCREAMING_SNAKE_CASE ) return (out_vocab_file,) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = "en_XX" , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = "ro_RO" , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" lowercase_ : List[str] = src_lang lowercase_ : int = tgt_lang return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self ): """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Dict = self.lang_code_to_id[src_lang] lowercase_ : Optional[Any] = [] lowercase_ : List[str] = [self.eos_token_id, self.cur_lang_code] def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.lang_code_to_id[lang] lowercase_ : Dict = [] lowercase_ : Union[str, Any] = [self.eos_token_id, self.cur_lang_code]
93
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = { '''microsoft/table-transformer-detection''': ( '''https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json''' ), } class UpperCamelCase_ (__A ): __magic_name__ = '''table-transformer''' __magic_name__ = ['''past_key_values'''] __magic_name__ = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self : List[Any] , lowerCAmelCase_ : List[Any]=True , lowerCAmelCase_ : Union[str, Any]=None , lowerCAmelCase_ : Optional[Any]=3 , lowerCAmelCase_ : Optional[Any]=100 , lowerCAmelCase_ : Optional[int]=6 , lowerCAmelCase_ : List[Any]=2_048 , lowerCAmelCase_ : Tuple=8 , lowerCAmelCase_ : Dict=6 , lowerCAmelCase_ : List[Any]=2_048 , lowerCAmelCase_ : Optional[int]=8 , lowerCAmelCase_ : Tuple=0.0 , lowerCAmelCase_ : str=0.0 , lowerCAmelCase_ : str=True , lowerCAmelCase_ : Optional[int]="relu" , lowerCAmelCase_ : List[Any]=256 , lowerCAmelCase_ : Optional[Any]=0.1 , lowerCAmelCase_ : Optional[int]=0.0 , lowerCAmelCase_ : Union[str, Any]=0.0 , lowerCAmelCase_ : Dict=0.0_2 , lowerCAmelCase_ : Any=1.0 , lowerCAmelCase_ : Any=False , lowerCAmelCase_ : Dict="sine" , lowerCAmelCase_ : Optional[Any]="resnet50" , lowerCAmelCase_ : int=True , lowerCAmelCase_ : Union[str, Any]=False , lowerCAmelCase_ : int=1 , lowerCAmelCase_ : int=5 , lowerCAmelCase_ : Union[str, Any]=2 , lowerCAmelCase_ : Any=1 , lowerCAmelCase_ : List[str]=1 , lowerCAmelCase_ : List[Any]=5 , lowerCAmelCase_ : Optional[Any]=2 , lowerCAmelCase_ : Optional[Any]=0.1 , **lowerCAmelCase_ : Dict , ) -> Union[str, Any]: if backbone_config is not None and use_timm_backbone: raise ValueError("You can't specify both `backbone_config` and `use_timm_backbone`." ) if not use_timm_backbone: if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) UpperCAmelCase_ : Union[str, Any] = CONFIG_MAPPING["resnet"](out_features=["stage4"] ) elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): UpperCAmelCase_ : Dict = backbone_config.get("model_type" ) UpperCAmelCase_ : str = CONFIG_MAPPING[backbone_model_type] UpperCAmelCase_ : Any = config_class.from_dict(lowerCAmelCase_ ) # set timm attributes to None UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : str = None, None, None UpperCAmelCase_ : int = use_timm_backbone UpperCAmelCase_ : int = backbone_config UpperCAmelCase_ : Dict = num_channels UpperCAmelCase_ : Optional[Any] = num_queries UpperCAmelCase_ : List[str] = d_model UpperCAmelCase_ : Union[str, Any] = encoder_ffn_dim UpperCAmelCase_ : Optional[Any] = encoder_layers UpperCAmelCase_ : List[str] = encoder_attention_heads UpperCAmelCase_ : int = decoder_ffn_dim UpperCAmelCase_ : int = decoder_layers UpperCAmelCase_ : Optional[int] = decoder_attention_heads UpperCAmelCase_ : List[str] = dropout UpperCAmelCase_ : Dict = attention_dropout UpperCAmelCase_ : Union[str, Any] = activation_dropout UpperCAmelCase_ : Optional[int] = activation_function UpperCAmelCase_ : int = init_std UpperCAmelCase_ : Any = init_xavier_std UpperCAmelCase_ : Union[str, Any] = encoder_layerdrop UpperCAmelCase_ : Dict = decoder_layerdrop UpperCAmelCase_ : Union[str, Any] = encoder_layers UpperCAmelCase_ : Any = auxiliary_loss UpperCAmelCase_ : List[str] = position_embedding_type UpperCAmelCase_ : Dict = backbone UpperCAmelCase_ : Optional[int] = use_pretrained_backbone UpperCAmelCase_ : Tuple = dilation # Hungarian matcher UpperCAmelCase_ : Optional[Any] = class_cost UpperCAmelCase_ : List[Any] = bbox_cost UpperCAmelCase_ : Optional[int] = giou_cost # Loss coefficients UpperCAmelCase_ : Optional[int] = mask_loss_coefficient UpperCAmelCase_ : List[str] = dice_loss_coefficient UpperCAmelCase_ : Union[str, Any] = bbox_loss_coefficient UpperCAmelCase_ : Union[str, Any] = giou_loss_coefficient UpperCAmelCase_ : Dict = eos_coefficient super().__init__(is_encoder_decoder=lowerCAmelCase_ , **lowerCAmelCase_ ) @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: return self.encoder_attention_heads @property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> int: return self.d_model class UpperCamelCase_ (__A ): __magic_name__ = version.parse('''1.11''' ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ("pixel_mask", {0: "batch"}), ] ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> float: return 1e-5 @property def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> int: return 12
253
"""simple docstring""" from __future__ import annotations from collections.abc import MutableSequence class UpperCamelCase_ : def __init__( self : Optional[int] , lowerCAmelCase_ : int , lowerCAmelCase_ : MutableSequence[float] ) -> None: if len(lowerCAmelCase_ ) != degree + 1: raise ValueError( "The number of coefficients should be equal to the degree + 1." ) UpperCAmelCase_ : list[float] = list(lowerCAmelCase_ ) UpperCAmelCase_ : Union[str, Any] = degree def __add__( self : int , lowerCAmelCase_ : Polynomial ) -> Polynomial: if self.degree > polynomial_a.degree: UpperCAmelCase_ : List[str] = self.coefficients[:] for i in range(polynomial_a.degree + 1 ): coefficients[i] += polynomial_a.coefficients[i] return Polynomial(self.degree , lowerCAmelCase_ ) else: UpperCAmelCase_ : Optional[Any] = polynomial_a.coefficients[:] for i in range(self.degree + 1 ): coefficients[i] += self.coefficients[i] return Polynomial(polynomial_a.degree , lowerCAmelCase_ ) def __sub__( self : Union[str, Any] , lowerCAmelCase_ : Polynomial ) -> Polynomial: return self + polynomial_a * Polynomial(0 , [-1] ) def __neg__( self : List[str] ) -> Polynomial: return Polynomial(self.degree , [-c for c in self.coefficients] ) def __mul__( self : Optional[Any] , lowerCAmelCase_ : Polynomial ) -> Polynomial: UpperCAmelCase_ : list[float] = [0] * (self.degree + polynomial_a.degree + 1) for i in range(self.degree + 1 ): for j in range(polynomial_a.degree + 1 ): coefficients[i + j] += ( self.coefficients[i] * polynomial_a.coefficients[j] ) return Polynomial(self.degree + polynomial_a.degree , lowerCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : str , lowerCAmelCase_ : int | float ) -> int | float: UpperCAmelCase_ : int | float = 0 for i in range(self.degree + 1 ): result += self.coefficients[i] * (substitution**i) return result def __str__( self : Tuple ) -> str: UpperCAmelCase_ : str = "" for i in range(self.degree , -1 , -1 ): if self.coefficients[i] == 0: continue elif self.coefficients[i] > 0: if polynomial: polynomial += " + " else: polynomial += " - " if i == 0: polynomial += str(abs(self.coefficients[i] ) ) elif i == 1: polynomial += str(abs(self.coefficients[i] ) ) + "x" else: polynomial += str(abs(self.coefficients[i] ) ) + "x^" + str(lowerCAmelCase_ ) return polynomial def __repr__( self : Union[str, Any] ) -> str: return self.__str__() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Polynomial: UpperCAmelCase_ : list[float] = [0] * self.degree for i in range(self.degree ): UpperCAmelCase_ : List[Any] = self.coefficients[i + 1] * (i + 1) return Polynomial(self.degree - 1 , lowerCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowerCAmelCase_ : int | float = 0 ) -> Polynomial: UpperCAmelCase_ : list[float] = [0] * (self.degree + 2) UpperCAmelCase_ : List[Any] = constant for i in range(self.degree + 1 ): UpperCAmelCase_ : Union[str, Any] = self.coefficients[i] / (i + 1) return Polynomial(self.degree + 1 , lowerCAmelCase_ ) def __eq__( self : Union[str, Any] , lowerCAmelCase_ : object ) -> bool: if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return False if self.degree != polynomial_a.degree: return False for i in range(self.degree + 1 ): if self.coefficients[i] != polynomial_a.coefficients[i]: return False return True def __ne__( self : Tuple , lowerCAmelCase_ : object ) -> bool: return not self.__eq__(lowerCAmelCase_ )
253
1
from __future__ import annotations __lowerCamelCase = 1.6_021e-19 # units = C def UpperCamelCase ( __lowerCamelCase : float , __lowerCamelCase : float , __lowerCamelCase : float , ): if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError("You cannot supply more or less than 2 values" ) elif conductivity < 0: raise ValueError("Conductivity cannot be negative" ) elif electron_conc < 0: raise ValueError("Electron concentration cannot be negative" ) elif mobility < 0: raise ValueError("mobility cannot be negative" ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
59
'''simple docstring''' import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCamelCase = logging.get_logger(__name__) __lowerCamelCase = { '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json''', } class A__ ( _snake_case ): lowercase = "mvp" lowercase = ["past_key_values"] lowercase = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self , UpperCamelCase__=50267 , UpperCamelCase__=1024 , UpperCamelCase__=12 , UpperCamelCase__=4096 , UpperCamelCase__=16 , UpperCamelCase__=12 , UpperCamelCase__=4096 , UpperCamelCase__=16 , UpperCamelCase__=0.0 , UpperCamelCase__=0.0 , UpperCamelCase__="gelu" , UpperCamelCase__=1024 , UpperCamelCase__=0.1 , UpperCamelCase__=0.0 , UpperCamelCase__=0.0 , UpperCamelCase__=0.02 , UpperCamelCase__=0.0 , UpperCamelCase__=False , UpperCamelCase__=True , UpperCamelCase__=1 , UpperCamelCase__=0 , UpperCamelCase__=2 , UpperCamelCase__=True , UpperCamelCase__=2 , UpperCamelCase__=2 , UpperCamelCase__=False , UpperCamelCase__=100 , UpperCamelCase__=800 , **UpperCamelCase__ , ) -> Tuple: '''simple docstring''' A_ = vocab_size A_ = max_position_embeddings A_ = d_model A_ = encoder_ffn_dim A_ = encoder_layers A_ = encoder_attention_heads A_ = decoder_ffn_dim A_ = decoder_layers A_ = decoder_attention_heads A_ = dropout A_ = attention_dropout A_ = activation_dropout A_ = activation_function A_ = init_std A_ = encoder_layerdrop A_ = decoder_layerdrop A_ = classifier_dropout A_ = use_cache A_ = encoder_layers A_ = scale_embedding # scale factor will be sqrt(d_model) if True A_ = use_prompt A_ = prompt_length A_ = prompt_mid_dim super().__init__( pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , is_encoder_decoder=UpperCamelCase__ , decoder_start_token_id=UpperCamelCase__ , forced_eos_token_id=UpperCamelCase__ , **UpperCamelCase__ , ) if self.forced_bos_token_id is None and kwargs.get("""force_bos_token_to_be_generated""" , UpperCamelCase__ ): A_ = self.bos_token_id warnings.warn( f'''Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. ''' """The config can simply be saved and uploaded again to be fixed.""" )
162
0
import numpy as np def _a ( UpperCAmelCase ) -> np.array: """simple docstring""" return (2 / (1 + np.exp(-2 * vector ))) - 1 if __name__ == "__main__": import doctest doctest.testmod()
351
from __future__ import annotations _A : List[str] = '#' class __SCREAMING_SNAKE_CASE : def __init__( self : List[Any] ) ->None: lowerCamelCase__ : dict = {} def __lowerCamelCase ( self : Union[str, Any] , A : str ) ->None: lowerCamelCase__ : Any = self._trie for char in text: if char not in trie: lowerCamelCase__ : Any = {} lowerCamelCase__ : Any = trie[char] lowerCamelCase__ : List[str] = True def __lowerCamelCase ( self : List[Any] , A : str ) ->tuple | list: lowerCamelCase__ : Dict = self._trie for char in prefix: if char in trie: lowerCamelCase__ : List[Any] = trie[char] else: return [] return self._elements(A ) def __lowerCamelCase ( self : Dict , A : dict ) ->tuple: lowerCamelCase__ : Optional[Any] = [] for c, v in d.items(): lowerCamelCase__ : Any = [''' '''] if c == END else [(c + s) for s in self._elements(A )] result.extend(A ) return tuple(A ) _A : str = Trie() _A : List[Any] = ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal') for word in words: trie.insert_word(word) def _a ( UpperCAmelCase ) -> tuple: """simple docstring""" lowerCamelCase__ : Optional[int] = trie.find_word(UpperCAmelCase ) return tuple(string + word for word in suffixes ) def _a ( ) -> None: """simple docstring""" print(autocomplete_using_trie('''de''' ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
265
0
from typing import List, Optional, TypeVar from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .info import DatasetInfo from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasets from .splits import NamedSplit from .utils import logging from .utils.py_utils import Literal __snake_case :List[Any] = logging.get_logger(__name__) __snake_case :Tuple = TypeVar('''DatasetType''', Dataset, IterableDataset) def __snake_case ( _UpperCAmelCase , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = "first_exhausted" , ): from .arrow_dataset import Dataset from .iterable_dataset import IterableDataset if not datasets: raise ValueError('''Unable to interleave an empty list of datasets.''' ) for i, dataset in enumerate(_UpperCAmelCase ): if not isinstance(_UpperCAmelCase , (Dataset, IterableDataset) ): if isinstance(_UpperCAmelCase , (DatasetDict, IterableDatasetDict) ): if not dataset: raise ValueError( f'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} ' '''is an empty dataset dictionary.''' ) raise ValueError( f'Dataset at position {i} has at least one split: {list(_UpperCAmelCase )}\n' f'Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(_UpperCAmelCase ) )}\']' ) raise ValueError( f'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(_UpperCAmelCase ).__name__}.' ) if i == 0: __a , __a = ( (Dataset, IterableDataset) if isinstance(_UpperCAmelCase , _UpperCAmelCase ) else (IterableDataset, Dataset) ) elif not isinstance(_UpperCAmelCase , _UpperCAmelCase ): raise ValueError( f'Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.' ) if stopping_strategy not in ["first_exhausted", "all_exhausted"]: raise ValueError(f'{stopping_strategy} is not supported. Please enter a valid stopping_strategy.' ) if dataset_type is Dataset: return _interleave_map_style_datasets( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , info=_UpperCAmelCase , split=_UpperCAmelCase , stopping_strategy=_UpperCAmelCase ) else: return _interleave_iterable_datasets( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , info=_UpperCAmelCase , split=_UpperCAmelCase , stopping_strategy=_UpperCAmelCase ) def __snake_case ( _UpperCAmelCase , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = 0 , ): if not dsets: raise ValueError('''Unable to concatenate an empty list of datasets.''' ) for i, dataset in enumerate(_UpperCAmelCase ): if not isinstance(_UpperCAmelCase , (Dataset, IterableDataset) ): if isinstance(_UpperCAmelCase , (DatasetDict, IterableDatasetDict) ): if not dataset: raise ValueError( f'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} ' '''is an empty dataset dictionary.''' ) raise ValueError( f'Dataset at position {i} has at least one split: {list(_UpperCAmelCase )}\n' f'Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(_UpperCAmelCase ) )}\']' ) raise ValueError( f'Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(_UpperCAmelCase ).__name__}.' ) if i == 0: __a , __a = ( (Dataset, IterableDataset) if isinstance(_UpperCAmelCase , _UpperCAmelCase ) else (IterableDataset, Dataset) ) elif not isinstance(_UpperCAmelCase , _UpperCAmelCase ): raise ValueError( f'Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.' ) if dataset_type is Dataset: return _concatenate_map_style_datasets(_UpperCAmelCase , info=_UpperCAmelCase , split=_UpperCAmelCase , axis=_UpperCAmelCase ) else: return _concatenate_iterable_datasets(_UpperCAmelCase , info=_UpperCAmelCase , split=_UpperCAmelCase , axis=_UpperCAmelCase )
49
"""simple docstring""" from __future__ import annotations _snake_case : str = [] def A__ ( UpperCamelCase , UpperCamelCase , UpperCamelCase ): for i in range(len(UpperCamelCase ) ): if board[row][i] == 1: return False for i in range(len(UpperCamelCase ) ): if board[i][column] == 1: return False for i, j in zip(range(UpperCamelCase , -1 , -1 ) , range(UpperCamelCase , -1 , -1 ) ): if board[i][j] == 1: return False for i, j in zip(range(UpperCamelCase , -1 , -1 ) , range(UpperCamelCase , len(UpperCamelCase ) ) ): if board[i][j] == 1: return False return True def A__ ( UpperCamelCase , UpperCamelCase ): if row >= len(UpperCamelCase ): solution.append(UpperCamelCase ) printboard(UpperCamelCase ) print() return True for i in range(len(UpperCamelCase ) ): if is_safe(UpperCamelCase , UpperCamelCase , UpperCamelCase ): A = 1 solve(UpperCamelCase , row + 1 ) A = 0 return False def A__ ( UpperCamelCase ): for i in range(len(UpperCamelCase ) ): for j in range(len(UpperCamelCase ) ): if board[i][j] == 1: print("Q" , end=" " ) else: print("." , end=" " ) print() # n=int(input("The no. of queens")) _snake_case : List[str] = 8 _snake_case : List[str] = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print('The total no. of solutions are :', len(solution))
292
0
'''simple docstring''' import math def _lowerCamelCase ( lowerCamelCase_ : int = 100 ): """simple docstring""" UpperCAmelCase_ : Tuple = sum(i * i for i in range(1 , n + 1 ) ) UpperCAmelCase_ : Union[str, Any] = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(f'''{solution() = }''')
274
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig snake_case__ : Dict = { '''albert-base-v1''': '''https://huggingface.co/albert-base-v1/resolve/main/config.json''', '''albert-large-v1''': '''https://huggingface.co/albert-large-v1/resolve/main/config.json''', '''albert-xlarge-v1''': '''https://huggingface.co/albert-xlarge-v1/resolve/main/config.json''', '''albert-xxlarge-v1''': '''https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json''', '''albert-base-v2''': '''https://huggingface.co/albert-base-v2/resolve/main/config.json''', '''albert-large-v2''': '''https://huggingface.co/albert-large-v2/resolve/main/config.json''', '''albert-xlarge-v2''': '''https://huggingface.co/albert-xlarge-v2/resolve/main/config.json''', '''albert-xxlarge-v2''': '''https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json''', } class __SCREAMING_SNAKE_CASE ( lowerCamelCase_ ): '''simple docstring''' lowerCamelCase_ :str = '''albert''' def __init__( self , snake_case_=3_0_0_0_0 , snake_case_=1_2_8 , snake_case_=4_0_9_6 , snake_case_=1_2 , snake_case_=1 , snake_case_=6_4 , snake_case_=1_6_3_8_4 , snake_case_=1 , snake_case_="gelu_new" , snake_case_=0 , snake_case_=0 , snake_case_=5_1_2 , snake_case_=2 , snake_case_=0.02 , snake_case_=1E-12 , snake_case_=0.1 , snake_case_="absolute" , snake_case_=0 , snake_case_=2 , snake_case_=3 , **snake_case_ , ): '''simple docstring''' super().__init__(pad_token_id=snake_case_ , bos_token_id=snake_case_ , eos_token_id=snake_case_ , **snake_case_ ) UpperCAmelCase_ : List[Any] = vocab_size UpperCAmelCase_ : Dict = embedding_size UpperCAmelCase_ : str = hidden_size UpperCAmelCase_ : Any = num_hidden_layers UpperCAmelCase_ : Union[str, Any] = num_hidden_groups UpperCAmelCase_ : List[str] = num_attention_heads UpperCAmelCase_ : Any = inner_group_num UpperCAmelCase_ : Optional[int] = hidden_act UpperCAmelCase_ : Tuple = intermediate_size UpperCAmelCase_ : Any = hidden_dropout_prob UpperCAmelCase_ : List[str] = attention_probs_dropout_prob UpperCAmelCase_ : Union[str, Any] = max_position_embeddings UpperCAmelCase_ : Dict = type_vocab_size UpperCAmelCase_ : Union[str, Any] = initializer_range UpperCAmelCase_ : Optional[Any] = layer_norm_eps UpperCAmelCase_ : Dict = classifier_dropout_prob UpperCAmelCase_ : Tuple = position_embedding_type class __SCREAMING_SNAKE_CASE ( lowerCamelCase_ ): '''simple docstring''' @property def _UpperCamelCase ( self ): '''simple docstring''' if self.task == "multiple-choice": UpperCAmelCase_ : Optional[Any] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: UpperCAmelCase_ : List[Any] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
274
1
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) __lowerCamelCase : List[Any] = logging.get_logger(__name__) __lowerCamelCase : Tuple = OrderedDict( [ ("""audio-spectrogram-transformer""", """ASTFeatureExtractor"""), ("""beit""", """BeitFeatureExtractor"""), ("""chinese_clip""", """ChineseCLIPFeatureExtractor"""), ("""clap""", """ClapFeatureExtractor"""), ("""clip""", """CLIPFeatureExtractor"""), ("""clipseg""", """ViTFeatureExtractor"""), ("""conditional_detr""", """ConditionalDetrFeatureExtractor"""), ("""convnext""", """ConvNextFeatureExtractor"""), ("""cvt""", """ConvNextFeatureExtractor"""), ("""data2vec-audio""", """Wav2Vec2FeatureExtractor"""), ("""data2vec-vision""", """BeitFeatureExtractor"""), ("""deformable_detr""", """DeformableDetrFeatureExtractor"""), ("""deit""", """DeiTFeatureExtractor"""), ("""detr""", """DetrFeatureExtractor"""), ("""dinat""", """ViTFeatureExtractor"""), ("""donut-swin""", """DonutFeatureExtractor"""), ("""dpt""", """DPTFeatureExtractor"""), ("""encodec""", """EncodecFeatureExtractor"""), ("""flava""", """FlavaFeatureExtractor"""), ("""glpn""", """GLPNFeatureExtractor"""), ("""groupvit""", """CLIPFeatureExtractor"""), ("""hubert""", """Wav2Vec2FeatureExtractor"""), ("""imagegpt""", """ImageGPTFeatureExtractor"""), ("""layoutlmv2""", """LayoutLMv2FeatureExtractor"""), ("""layoutlmv3""", """LayoutLMv3FeatureExtractor"""), ("""levit""", """LevitFeatureExtractor"""), ("""maskformer""", """MaskFormerFeatureExtractor"""), ("""mctct""", """MCTCTFeatureExtractor"""), ("""mobilenet_v1""", """MobileNetV1FeatureExtractor"""), ("""mobilenet_v2""", """MobileNetV2FeatureExtractor"""), ("""mobilevit""", """MobileViTFeatureExtractor"""), ("""nat""", """ViTFeatureExtractor"""), ("""owlvit""", """OwlViTFeatureExtractor"""), ("""perceiver""", """PerceiverFeatureExtractor"""), ("""poolformer""", """PoolFormerFeatureExtractor"""), ("""regnet""", """ConvNextFeatureExtractor"""), ("""resnet""", """ConvNextFeatureExtractor"""), ("""segformer""", """SegformerFeatureExtractor"""), ("""sew""", """Wav2Vec2FeatureExtractor"""), ("""sew-d""", """Wav2Vec2FeatureExtractor"""), ("""speech_to_text""", """Speech2TextFeatureExtractor"""), ("""speecht5""", """SpeechT5FeatureExtractor"""), ("""swiftformer""", """ViTFeatureExtractor"""), ("""swin""", """ViTFeatureExtractor"""), ("""swinv2""", """ViTFeatureExtractor"""), ("""table-transformer""", """DetrFeatureExtractor"""), ("""timesformer""", """VideoMAEFeatureExtractor"""), ("""tvlt""", """TvltFeatureExtractor"""), ("""unispeech""", """Wav2Vec2FeatureExtractor"""), ("""unispeech-sat""", """Wav2Vec2FeatureExtractor"""), ("""van""", """ConvNextFeatureExtractor"""), ("""videomae""", """VideoMAEFeatureExtractor"""), ("""vilt""", """ViltFeatureExtractor"""), ("""vit""", """ViTFeatureExtractor"""), ("""vit_mae""", """ViTFeatureExtractor"""), ("""vit_msn""", """ViTFeatureExtractor"""), ("""wav2vec2""", """Wav2Vec2FeatureExtractor"""), ("""wav2vec2-conformer""", """Wav2Vec2FeatureExtractor"""), ("""wavlm""", """Wav2Vec2FeatureExtractor"""), ("""whisper""", """WhisperFeatureExtractor"""), ("""xclip""", """CLIPFeatureExtractor"""), ("""yolos""", """YolosFeatureExtractor"""), ] ) __lowerCamelCase : Optional[Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def A_ ( _lowerCAmelCase ) -> Any: for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: UpperCamelCase : Optional[Any] = model_type_to_module_name(__snake_case ) UpperCamelCase : Optional[int] = importlib.import_module(F""".{module_name}""" , "transformers.models" ) try: return getattr(__snake_case , __snake_case ) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items(): if getattr(__snake_case , "__name__" , __snake_case ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. UpperCamelCase : Tuple = importlib.import_module("transformers" ) if hasattr(__snake_case , __snake_case ): return getattr(__snake_case , __snake_case ) return None def A_ ( _lowerCAmelCase , _lowerCAmelCase = None , _lowerCAmelCase = False , _lowerCAmelCase = False , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = False , **_lowerCAmelCase , ) -> List[str]: UpperCamelCase : Dict = get_file_from_repo( __snake_case , __snake_case , cache_dir=__snake_case , force_download=__snake_case , resume_download=__snake_case , proxies=__snake_case , use_auth_token=__snake_case , revision=__snake_case , local_files_only=__snake_case , ) if resolved_config_file is None: logger.info( "Could not locate the feature extractor configuration file, will try to use the model config instead." ) return {} with open(__snake_case , encoding="utf-8" ) as reader: return json.load(__snake_case ) class A__ : def __init__( self ): '''simple docstring''' raise EnvironmentError( "AutoFeatureExtractor is designed to be instantiated " "using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method." ) @classmethod @replace_list_option_in_docstrings(A_ ) def __UpperCamelCase( cls , A_ , **A_ ): '''simple docstring''' UpperCamelCase : Tuple = kwargs.pop("config" , A_ ) UpperCamelCase : str = kwargs.pop("trust_remote_code" , A_ ) UpperCamelCase : str = True UpperCamelCase , UpperCamelCase : Optional[Any] = FeatureExtractionMixin.get_feature_extractor_dict(A_ , **A_ ) UpperCamelCase : List[Any] = config_dict.get("feature_extractor_type" , A_ ) UpperCamelCase : Any = None if "AutoFeatureExtractor" in config_dict.get("auto_map" , {} ): UpperCamelCase : List[Any] = config_dict["auto_map"]["AutoFeatureExtractor"] # If we don't find the feature extractor class in the feature extractor config, let's try the model config. if feature_extractor_class is None and feature_extractor_auto_map is None: if not isinstance(A_ , A_ ): UpperCamelCase : Any = AutoConfig.from_pretrained(A_ , **A_ ) # It could be in `config.feature_extractor_type`` UpperCamelCase : Tuple = getattr(A_ , "feature_extractor_type" , A_ ) if hasattr(A_ , "auto_map" ) and "AutoFeatureExtractor" in config.auto_map: UpperCamelCase : List[str] = config.auto_map["AutoFeatureExtractor"] if feature_extractor_class is not None: UpperCamelCase : int = feature_extractor_class_from_name(A_ ) UpperCamelCase : Any = feature_extractor_auto_map is not None UpperCamelCase : Optional[Any] = feature_extractor_class is not None or type(A_ ) in FEATURE_EXTRACTOR_MAPPING UpperCamelCase : Dict = resolve_trust_remote_code( A_ , A_ , A_ , A_ ) if has_remote_code and trust_remote_code: UpperCamelCase : str = get_class_from_dynamic_module( A_ , A_ , **A_ ) UpperCamelCase : Tuple = kwargs.pop("code_revision" , A_ ) if os.path.isdir(A_ ): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(A_ , **A_ ) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(A_ , **A_ ) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(A_ ) in FEATURE_EXTRACTOR_MAPPING: UpperCamelCase : Union[str, Any] = FEATURE_EXTRACTOR_MAPPING[type(A_ )] return feature_extractor_class.from_dict(A_ , **A_ ) raise ValueError( F"""Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a """ F"""`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following """ F"""`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys() )}""" ) @staticmethod def __UpperCamelCase( A_ , A_ ): '''simple docstring''' FEATURE_EXTRACTOR_MAPPING.register(A_ , A_ )
52
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging a_ : Union[str, Any] = logging.get_logger(__name__) if is_vision_available(): import PIL class __UpperCamelCase ( lowerCamelCase__ ): lowercase : Tuple =['pixel_values'] def __init__( self, lowerCAmelCase = True, lowerCAmelCase = None, lowerCAmelCase = PILImageResampling.BICUBIC, lowerCAmelCase = True, lowerCAmelCase = None, lowerCAmelCase = True, lowerCAmelCase = 1 / 255, lowerCAmelCase = True, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = True, **lowerCAmelCase, ): """simple docstring""" super().__init__(**lowerCAmelCase ) lowerCamelCase_ =size if size is not None else {'''shortest_edge''': 224} lowerCamelCase_ =get_size_dict(lowerCAmelCase, default_to_square=lowerCAmelCase ) lowerCamelCase_ =crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} lowerCamelCase_ =get_size_dict(lowerCAmelCase, default_to_square=lowerCAmelCase, param_name='''crop_size''' ) lowerCamelCase_ =do_resize lowerCamelCase_ =size lowerCamelCase_ =resample lowerCamelCase_ =do_center_crop lowerCamelCase_ =crop_size lowerCamelCase_ =do_rescale lowerCamelCase_ =rescale_factor lowerCamelCase_ =do_normalize lowerCamelCase_ =image_mean if image_mean is not None else OPENAI_CLIP_MEAN lowerCamelCase_ =image_std if image_std is not None else OPENAI_CLIP_STD lowerCamelCase_ =do_convert_rgb def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase = PILImageResampling.BICUBIC, lowerCAmelCase = None, **lowerCAmelCase, ): """simple docstring""" lowerCamelCase_ =get_size_dict(lowerCAmelCase, default_to_square=lowerCAmelCase ) if "shortest_edge" not in size: raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) lowerCamelCase_ =get_resize_output_image_size(lowerCAmelCase, size=size['''shortest_edge'''], default_to_square=lowerCAmelCase ) return resize(lowerCAmelCase, size=lowerCAmelCase, resample=lowerCAmelCase, data_format=lowerCAmelCase, **lowerCAmelCase ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase = None, **lowerCAmelCase, ): """simple docstring""" lowerCamelCase_ =get_size_dict(lowerCAmelCase ) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(lowerCAmelCase, size=(size['''height'''], size['''width''']), data_format=lowerCAmelCase, **lowerCAmelCase ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase = None, **lowerCAmelCase, ): """simple docstring""" return rescale(lowerCAmelCase, scale=lowerCAmelCase, data_format=lowerCAmelCase, **lowerCAmelCase ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase = None, **lowerCAmelCase, ): """simple docstring""" return normalize(lowerCAmelCase, mean=lowerCAmelCase, std=lowerCAmelCase, data_format=lowerCAmelCase, **lowerCAmelCase ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = ChannelDimension.FIRST, **lowerCAmelCase, ): """simple docstring""" lowerCamelCase_ =do_resize if do_resize is not None else self.do_resize lowerCamelCase_ =size if size is not None else self.size lowerCamelCase_ =get_size_dict(lowerCAmelCase, param_name='''size''', default_to_square=lowerCAmelCase ) lowerCamelCase_ =resample if resample is not None else self.resample lowerCamelCase_ =do_center_crop if do_center_crop is not None else self.do_center_crop lowerCamelCase_ =crop_size if crop_size is not None else self.crop_size lowerCamelCase_ =get_size_dict(lowerCAmelCase, param_name='''crop_size''', default_to_square=lowerCAmelCase ) lowerCamelCase_ =do_rescale if do_rescale is not None else self.do_rescale lowerCamelCase_ =rescale_factor if rescale_factor is not None else self.rescale_factor lowerCamelCase_ =do_normalize if do_normalize is not None else self.do_normalize lowerCamelCase_ =image_mean if image_mean is not None else self.image_mean lowerCamelCase_ =image_std if image_std is not None else self.image_std lowerCamelCase_ =do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb lowerCamelCase_ =make_list_of_images(lowerCAmelCase ) if not valid_images(lowerCAmelCase ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # PIL RGBA images are converted to RGB if do_convert_rgb: lowerCamelCase_ =[convert_to_rgb(lowerCAmelCase ) for image in images] # All transformations expect numpy arrays. lowerCamelCase_ =[to_numpy_array(lowerCAmelCase ) for image in images] if do_resize: lowerCamelCase_ =[self.resize(image=lowerCAmelCase, size=lowerCAmelCase, resample=lowerCAmelCase ) for image in images] if do_center_crop: lowerCamelCase_ =[self.center_crop(image=lowerCAmelCase, size=lowerCAmelCase ) for image in images] if do_rescale: lowerCamelCase_ =[self.rescale(image=lowerCAmelCase, scale=lowerCAmelCase ) for image in images] if do_normalize: lowerCamelCase_ =[self.normalize(image=lowerCAmelCase, mean=lowerCAmelCase, std=lowerCAmelCase ) for image in images] lowerCamelCase_ =[to_channel_dimension_format(lowerCAmelCase, lowerCAmelCase ) for image in images] lowerCamelCase_ ={'''pixel_values''': images} return BatchFeature(data=lowerCAmelCase, tensor_type=lowerCAmelCase )
75
0
import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class a : _lowercase = None _lowercase = False _lowercase = False _lowercase = False _lowercase = None _lowercase = None _lowercase = False _lowercase = False _lowercase = False _lowercase = True _lowercase = None _lowercase = 1 _lowercase = None _lowercase = False _lowercase = None _lowercase = None def _UpperCAmelCase ( self ): '''simple docstring''' return self.__class__(**{k: copy.deepcopy(A_ ) for k, v in self.__dict__.items()} )
189
import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class a ( UpperCAmelCase ): _lowercase = (PNDMScheduler,) _lowercase = (("num_inference_steps", 5_0),) def _UpperCAmelCase ( self , **A_ ): '''simple docstring''' _UpperCAmelCase : Tuple = { "num_train_timesteps": 1000, "beta_start": 0.00_01, "beta_end": 0.02, "beta_schedule": "linear", } config.update(**A_ ) return config def _UpperCAmelCase ( self , A_=0 , **A_ ): '''simple docstring''' _UpperCAmelCase : int = dict(self.forward_default_kwargs ) _UpperCAmelCase : Optional[Any] = kwargs.pop("num_inference_steps" , A_ ) _UpperCAmelCase : int = self.dummy_sample _UpperCAmelCase : Dict = 0.1 * sample _UpperCAmelCase : Optional[int] = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: _UpperCAmelCase : Dict = self.get_scheduler_config(**A_ ) _UpperCAmelCase : Any = scheduler_class(**A_ ) scheduler.set_timesteps(A_ ) # copy over dummy past residuals _UpperCAmelCase : Union[str, Any] = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(A_ ) _UpperCAmelCase : str = scheduler_class.from_pretrained(A_ ) new_scheduler.set_timesteps(A_ ) # copy over dummy past residuals _UpperCAmelCase : Union[str, Any] = dummy_past_residuals[:] _UpperCAmelCase : Tuple = scheduler.step_prk(A_ , A_ , A_ , **A_ ).prev_sample _UpperCAmelCase : Any = new_scheduler.step_prk(A_ , A_ , A_ , **A_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" _UpperCAmelCase : Union[str, Any] = scheduler.step_plms(A_ , A_ , A_ , **A_ ).prev_sample _UpperCAmelCase : Optional[Any] = new_scheduler.step_plms(A_ , A_ , A_ , **A_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def _UpperCAmelCase ( self ): '''simple docstring''' pass def _UpperCAmelCase ( self , A_=0 , **A_ ): '''simple docstring''' _UpperCAmelCase : Any = dict(self.forward_default_kwargs ) _UpperCAmelCase : int = kwargs.pop("num_inference_steps" , A_ ) _UpperCAmelCase : int = self.dummy_sample _UpperCAmelCase : Any = 0.1 * sample _UpperCAmelCase : Tuple = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: _UpperCAmelCase : Optional[Any] = self.get_scheduler_config() _UpperCAmelCase : Dict = scheduler_class(**A_ ) scheduler.set_timesteps(A_ ) # copy over dummy past residuals (must be after setting timesteps) _UpperCAmelCase : Any = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(A_ ) _UpperCAmelCase : str = scheduler_class.from_pretrained(A_ ) # copy over dummy past residuals new_scheduler.set_timesteps(A_ ) # copy over dummy past residual (must be after setting timesteps) _UpperCAmelCase : List[Any] = dummy_past_residuals[:] _UpperCAmelCase : Tuple = scheduler.step_prk(A_ , A_ , A_ , **A_ ).prev_sample _UpperCAmelCase : Union[str, Any] = new_scheduler.step_prk(A_ , A_ , A_ , **A_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" _UpperCAmelCase : Optional[Any] = scheduler.step_plms(A_ , A_ , A_ , **A_ ).prev_sample _UpperCAmelCase : List[str] = new_scheduler.step_plms(A_ , A_ , A_ , **A_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def _UpperCAmelCase ( self , **A_ ): '''simple docstring''' _UpperCAmelCase : Optional[Any] = self.scheduler_classes[0] _UpperCAmelCase : Union[str, Any] = self.get_scheduler_config(**A_ ) _UpperCAmelCase : List[str] = scheduler_class(**A_ ) _UpperCAmelCase : List[str] = 10 _UpperCAmelCase : Optional[int] = self.dummy_model() _UpperCAmelCase : List[Any] = self.dummy_sample_deter scheduler.set_timesteps(A_ ) for i, t in enumerate(scheduler.prk_timesteps ): _UpperCAmelCase : Dict = model(A_ , A_ ) _UpperCAmelCase : int = scheduler.step_prk(A_ , A_ , A_ ).prev_sample for i, t in enumerate(scheduler.plms_timesteps ): _UpperCAmelCase : Any = model(A_ , A_ ) _UpperCAmelCase : Any = scheduler.step_plms(A_ , A_ , A_ ).prev_sample return sample def _UpperCAmelCase ( self ): '''simple docstring''' _UpperCAmelCase : List[Any] = dict(self.forward_default_kwargs ) _UpperCAmelCase : str = kwargs.pop("num_inference_steps" , A_ ) for scheduler_class in self.scheduler_classes: _UpperCAmelCase : int = self.get_scheduler_config() _UpperCAmelCase : Optional[Any] = scheduler_class(**A_ ) _UpperCAmelCase : int = self.dummy_sample _UpperCAmelCase : str = 0.1 * sample if num_inference_steps is not None and hasattr(A_ , "set_timesteps" ): scheduler.set_timesteps(A_ ) elif num_inference_steps is not None and not hasattr(A_ , "set_timesteps" ): _UpperCAmelCase : Union[str, Any] = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) _UpperCAmelCase : Tuple = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] _UpperCAmelCase : Any = dummy_past_residuals[:] _UpperCAmelCase : Any = scheduler.step_prk(A_ , 0 , A_ , **A_ ).prev_sample _UpperCAmelCase : Optional[Any] = scheduler.step_prk(A_ , 1 , A_ , **A_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) _UpperCAmelCase : Optional[int] = scheduler.step_plms(A_ , 0 , A_ , **A_ ).prev_sample _UpperCAmelCase : Optional[Any] = scheduler.step_plms(A_ , 1 , A_ , **A_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _UpperCAmelCase ( self ): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=A_ ) def _UpperCAmelCase ( self ): '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=A_ ) _UpperCAmelCase : List[str] = self.scheduler_classes[0] _UpperCAmelCase : Optional[int] = self.get_scheduler_config(steps_offset=1 ) _UpperCAmelCase : str = scheduler_class(**A_ ) scheduler.set_timesteps(10 ) assert torch.equal( scheduler.timesteps , torch.LongTensor( [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1] ) , ) def _UpperCAmelCase ( self ): '''simple docstring''' for beta_start, beta_end in zip([0.00_01, 0.0_01] , [0.0_02, 0.02] ): self.check_over_configs(beta_start=A_ , beta_end=A_ ) def _UpperCAmelCase ( self ): '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=A_ ) def _UpperCAmelCase ( self ): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=A_ ) def _UpperCAmelCase ( self ): '''simple docstring''' for t in [1, 5, 10]: self.check_over_forward(time_step=A_ ) def _UpperCAmelCase ( self ): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ): self.check_over_forward(num_inference_steps=A_ ) def _UpperCAmelCase ( self ): '''simple docstring''' _UpperCAmelCase : int = 27 for scheduler_class in self.scheduler_classes: _UpperCAmelCase : str = self.dummy_sample _UpperCAmelCase : str = 0.1 * sample _UpperCAmelCase : str = self.get_scheduler_config() _UpperCAmelCase : Tuple = scheduler_class(**A_ ) scheduler.set_timesteps(A_ ) # before power of 3 fix, would error on first step, so we only need to do two for i, t in enumerate(scheduler.prk_timesteps[:2] ): _UpperCAmelCase : Dict = scheduler.step_prk(A_ , A_ , A_ ).prev_sample def _UpperCAmelCase ( self ): '''simple docstring''' with self.assertRaises(A_ ): _UpperCAmelCase : Union[str, Any] = self.scheduler_classes[0] _UpperCAmelCase : Dict = self.get_scheduler_config() _UpperCAmelCase : Union[str, Any] = scheduler_class(**A_ ) scheduler.step_plms(self.dummy_sample , 1 , self.dummy_sample ).prev_sample def _UpperCAmelCase ( self ): '''simple docstring''' _UpperCAmelCase : Dict = self.full_loop() _UpperCAmelCase : int = torch.sum(torch.abs(A_ ) ) _UpperCAmelCase : Optional[Any] = torch.mean(torch.abs(A_ ) ) assert abs(result_sum.item() - 1_98.13_18 ) < 1e-2 assert abs(result_mean.item() - 0.25_80 ) < 1e-3 def _UpperCAmelCase ( self ): '''simple docstring''' _UpperCAmelCase : Optional[Any] = self.full_loop(prediction_type="v_prediction" ) _UpperCAmelCase : Union[str, Any] = torch.sum(torch.abs(A_ ) ) _UpperCAmelCase : List[Any] = torch.mean(torch.abs(A_ ) ) assert abs(result_sum.item() - 67.39_86 ) < 1e-2 assert abs(result_mean.item() - 0.08_78 ) < 1e-3 def _UpperCAmelCase ( self ): '''simple docstring''' _UpperCAmelCase : Tuple = self.full_loop(set_alpha_to_one=A_ , beta_start=0.01 ) _UpperCAmelCase : Dict = torch.sum(torch.abs(A_ ) ) _UpperCAmelCase : Optional[int] = torch.mean(torch.abs(A_ ) ) assert abs(result_sum.item() - 2_30.03_99 ) < 1e-2 assert abs(result_mean.item() - 0.29_95 ) < 1e-3 def _UpperCAmelCase ( self ): '''simple docstring''' _UpperCAmelCase : List[Any] = self.full_loop(set_alpha_to_one=A_ , beta_start=0.01 ) _UpperCAmelCase : Optional[Any] = torch.sum(torch.abs(A_ ) ) _UpperCAmelCase : Dict = torch.mean(torch.abs(A_ ) ) assert abs(result_sum.item() - 1_86.94_82 ) < 1e-2 assert abs(result_mean.item() - 0.24_34 ) < 1e-3
189
1
from __future__ import absolute_import, division, print_function, unicode_literals from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers import RobertaConfig from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.roberta.modeling_roberta import ( ROBERTA_INPUTS_DOCSTRING, ROBERTA_START_DOCSTRING, RobertaEmbeddings, ) from .modeling_highway_bert import BertPreTrainedModel, DeeBertModel, HighwayException, entropy @add_start_docstrings( '''The RoBERTa Model transformer with early exiting (DeeRoBERTa). ''' , __magic_name__ , ) class _A ( __magic_name__): SCREAMING_SNAKE_CASE : int = RobertaConfig SCREAMING_SNAKE_CASE : List[str] = '''roberta''' def __init__( self , _SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ : int = RobertaEmbeddings(_SCREAMING_SNAKE_CASE ) self.init_weights() @add_start_docstrings( '''RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top, also takes care of multi-layer training. ''' , __magic_name__ , ) class _A ( __magic_name__): SCREAMING_SNAKE_CASE : Dict = RobertaConfig SCREAMING_SNAKE_CASE : Tuple = '''roberta''' def __init__( self , _SCREAMING_SNAKE_CASE ): """simple docstring""" super().__init__(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ : Optional[int] = config.num_labels SCREAMING_SNAKE_CASE_ : str = config.num_hidden_layers SCREAMING_SNAKE_CASE_ : int = DeeRobertaModel(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ : Optional[Any] = nn.Dropout(config.hidden_dropout_prob ) SCREAMING_SNAKE_CASE_ : Tuple = nn.Linear(config.hidden_size , self.config.num_labels ) @add_start_docstrings_to_model_forward(_SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=-1 , _SCREAMING_SNAKE_CASE=False , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.num_layers try: SCREAMING_SNAKE_CASE_ : Any = self.roberta( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , position_ids=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE , inputs_embeds=_SCREAMING_SNAKE_CASE , ) SCREAMING_SNAKE_CASE_ : List[Any] = outputs[1] SCREAMING_SNAKE_CASE_ : Optional[int] = self.dropout(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ : Dict = self.classifier(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ : List[Any] = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: SCREAMING_SNAKE_CASE_ : Any = e.message SCREAMING_SNAKE_CASE_ : str = e.exit_layer SCREAMING_SNAKE_CASE_ : str = outputs[0] if not self.training: SCREAMING_SNAKE_CASE_ : str = entropy(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ : Optional[Any] = [] SCREAMING_SNAKE_CASE_ : Dict = [] if labels is not None: if self.num_labels == 1: # We are doing regression SCREAMING_SNAKE_CASE_ : Any = MSELoss() SCREAMING_SNAKE_CASE_ : Tuple = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: SCREAMING_SNAKE_CASE_ : List[str] = CrossEntropyLoss() SCREAMING_SNAKE_CASE_ : Dict = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits SCREAMING_SNAKE_CASE_ : Tuple = [] for highway_exit in outputs[-1]: SCREAMING_SNAKE_CASE_ : Union[str, Any] = highway_exit[0] if not self.training: highway_logits_all.append(_SCREAMING_SNAKE_CASE ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression SCREAMING_SNAKE_CASE_ : Any = MSELoss() SCREAMING_SNAKE_CASE_ : Tuple = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: SCREAMING_SNAKE_CASE_ : Union[str, Any] = CrossEntropyLoss() SCREAMING_SNAKE_CASE_ : int = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(_SCREAMING_SNAKE_CASE ) if train_highway: SCREAMING_SNAKE_CASE_ : Optional[int] = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: SCREAMING_SNAKE_CASE_ : Optional[int] = (loss,) + outputs if not self.training: SCREAMING_SNAKE_CASE_ : str = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: SCREAMING_SNAKE_CASE_ : Tuple = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), entropy
253
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowerCAmelCase : List[str] = logging.get_logger(__name__) class _A ( __magic_name__ , __magic_name__): SCREAMING_SNAKE_CASE : Dict = '''maskformer-swin''' SCREAMING_SNAKE_CASE : Dict = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , _SCREAMING_SNAKE_CASE=224 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=96 , _SCREAMING_SNAKE_CASE=[2, 2, 6, 2] , _SCREAMING_SNAKE_CASE=[3, 6, 12, 24] , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=4.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1e-5 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ : Optional[Any] = image_size SCREAMING_SNAKE_CASE_ : List[str] = patch_size SCREAMING_SNAKE_CASE_ : Tuple = num_channels SCREAMING_SNAKE_CASE_ : List[Any] = embed_dim SCREAMING_SNAKE_CASE_ : Dict = depths SCREAMING_SNAKE_CASE_ : Dict = len(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ : Tuple = num_heads SCREAMING_SNAKE_CASE_ : List[Any] = window_size SCREAMING_SNAKE_CASE_ : List[Any] = mlp_ratio SCREAMING_SNAKE_CASE_ : Tuple = qkv_bias SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : Union[str, Any] = drop_path_rate SCREAMING_SNAKE_CASE_ : List[Any] = hidden_act SCREAMING_SNAKE_CASE_ : Dict = use_absolute_embeddings SCREAMING_SNAKE_CASE_ : int = layer_norm_eps SCREAMING_SNAKE_CASE_ : Optional[Any] = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE_ : str = int(embed_dim * 2 ** (len(_SCREAMING_SNAKE_CASE ) - 1) ) SCREAMING_SNAKE_CASE_ : List[str] = ['stem'] + [f"stage{idx}" for idx in range(1 , len(_SCREAMING_SNAKE_CASE ) + 1 )] SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = get_aligned_output_features_output_indices( out_features=_SCREAMING_SNAKE_CASE , out_indices=_SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
253
1
import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): __UpperCAmelCase = yaml.safe_load( '\\nname: ""\nallow_empty: false\nallow_empty_text: true\nsubsections:\n - name: "Dataset Card for X" # First-level markdown heading\n allow_empty: false\n allow_empty_text: true\n subsections:\n - name: "Table of Contents"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: "Dataset Description"\n allow_empty: false\n allow_empty_text: false\n subsections:\n - name: "Dataset Summary"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: "Supported Tasks and Leaderboards"\n allow_empty: true\n allow_empty_text: true\n subsections: null\n - name: Languages\n allow_empty: false\n allow_empty_text: true\n subsections: null\n' ) __UpperCAmelCase = { 'name': 'root', 'text': '', 'is_empty_text': True, 'subsections': [ { 'name': 'Dataset Card for My Dataset', 'text': '', 'is_empty_text': True, 'subsections': [ {'name': 'Table of Contents', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': []}, { 'name': 'Dataset Description', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [ { 'name': 'Dataset Summary', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [], }, { 'name': 'Supported Tasks and Leaderboards', 'text': '', 'is_empty_text': True, 'subsections': [], }, {'name': 'Languages', 'text': 'Language Text', 'is_empty_text': False, 'subsections': []}, ], }, ], } ], } __UpperCAmelCase = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __UpperCAmelCase = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n#### Extra Ignored Subsection\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __UpperCAmelCase = { 'name': 'root', 'text': '', 'is_empty_text': True, 'subsections': [ { 'name': 'Dataset Card for My Dataset', 'text': '', 'is_empty_text': True, 'subsections': [ {'name': 'Table of Contents', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': []}, { 'name': 'Dataset Description', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [ { 'name': 'Dataset Summary', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [ { 'name': 'Extra Ignored Subsection', 'text': '', 'is_empty_text': True, 'subsections': [], } ], }, { 'name': 'Supported Tasks and Leaderboards', 'text': '', 'is_empty_text': True, 'subsections': [], }, {'name': 'Languages', 'text': 'Language Text', 'is_empty_text': False, 'subsections': []}, ], }, ], } ], } __UpperCAmelCase = '\\n---\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __UpperCAmelCase = ( 'The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README.' ) __UpperCAmelCase = '\\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __UpperCAmelCase = ( 'The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README.' ) __UpperCAmelCase = '\\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __UpperCAmelCase = 'The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README.' __UpperCAmelCase = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __UpperCAmelCase = 'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored).' __UpperCAmelCase = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n' __UpperCAmelCase = 'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found \'None\'.' __UpperCAmelCase = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Languages\nLanguage Text\n' __UpperCAmelCase = 'The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`.' __UpperCAmelCase = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\n' __UpperCAmelCase = 'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty.' __UpperCAmelCase = '\\n---\nlanguage:\n- zh\n- en\n---\n\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __UpperCAmelCase = 'The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.' __UpperCAmelCase = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n# Dataset Card My Dataset\n' __UpperCAmelCase = 'The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README.' __UpperCAmelCase = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __UpperCAmelCase = 'The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README.' __UpperCAmelCase = '' __UpperCAmelCase = 'The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README.' __UpperCAmelCase = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __UpperCAmelCase = 'The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections.' @pytest.mark.parametrize( 'readme_md, expected_dict' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def lowercase__ ( __snake_case : int , __snake_case : Tuple ): '''simple docstring''' assert ReadMe.from_string(__snake_case , __snake_case ).to_dict() == expected_dict @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def lowercase__ ( __snake_case : Dict , __snake_case : Optional[int] ): '''simple docstring''' with pytest.raises(__snake_case , match=re.escape(expected_error.format(path='root' ) ) ): UpperCAmelCase_ : Optional[int] = ReadMe.from_string(__snake_case , __snake_case ) readme.validate() @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def lowercase__ ( __snake_case : Union[str, Any] , __snake_case : int ): '''simple docstring''' with pytest.raises(__snake_case , match=re.escape(expected_error.format(path='root' ) ) ): ReadMe.from_string(__snake_case , __snake_case ) @pytest.mark.parametrize( 'readme_md,' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def lowercase__ ( __snake_case : List[Any] ): '''simple docstring''' ReadMe.from_string(__snake_case , __snake_case , suppress_parsing_errors=__snake_case ) @pytest.mark.parametrize( 'readme_md, expected_dict' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def lowercase__ ( __snake_case : Any , __snake_case : str ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: UpperCAmelCase_ : Optional[Any] = Path(__snake_case ) / 'README.md' with open(__snake_case , 'w+' ) as readme_file: readme_file.write(__snake_case ) UpperCAmelCase_ : List[str] = ReadMe.from_readme(__snake_case , __snake_case ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def lowercase__ ( __snake_case : List[Any] , __snake_case : Dict ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: UpperCAmelCase_ : str = Path(__snake_case ) / 'README.md' with open(__snake_case , 'w+' ) as readme_file: readme_file.write(__snake_case ) UpperCAmelCase_ : Optional[int] = expected_error.format(path=__snake_case ) with pytest.raises(__snake_case , match=re.escape(__snake_case ) ): UpperCAmelCase_ : int = ReadMe.from_readme(__snake_case , __snake_case ) readme.validate() @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def lowercase__ ( __snake_case : Optional[Any] , __snake_case : str ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: UpperCAmelCase_ : Optional[int] = Path(__snake_case ) / 'README.md' with open(__snake_case , 'w+' ) as readme_file: readme_file.write(__snake_case ) UpperCAmelCase_ : List[str] = expected_error.format(path=__snake_case ) with pytest.raises(__snake_case , match=re.escape(__snake_case ) ): ReadMe.from_readme(__snake_case , __snake_case ) @pytest.mark.parametrize( 'readme_md,' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def lowercase__ ( __snake_case : Dict ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: UpperCAmelCase_ : Optional[Any] = Path(__snake_case ) / 'README.md' with open(__snake_case , 'w+' ) as readme_file: readme_file.write(__snake_case ) ReadMe.from_readme(__snake_case , __snake_case , suppress_parsing_errors=__snake_case )
355
from __future__ import annotations from collections.abc import Callable __UpperCAmelCase = list[list[float | int]] def lowercase__ ( __snake_case : Matrix , __snake_case : Matrix ): '''simple docstring''' UpperCAmelCase_ : int = len(__snake_case ) UpperCAmelCase_ : Matrix = [[0 for _ in range(size + 1 )] for _ in range(__snake_case )] UpperCAmelCase_ : int UpperCAmelCase_ : int UpperCAmelCase_ : int UpperCAmelCase_ : int UpperCAmelCase_ : int UpperCAmelCase_ : float for row in range(__snake_case ): for col in range(__snake_case ): UpperCAmelCase_ : Dict = matrix[row][col] UpperCAmelCase_ : Union[str, Any] = vector[row][0] UpperCAmelCase_ : Union[str, Any] = 0 UpperCAmelCase_ : Union[str, Any] = 0 while row < size and col < size: # pivoting UpperCAmelCase_ : Optional[Any] = max((abs(augmented[rowa][col] ), rowa) for rowa in range(__snake_case , __snake_case ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: UpperCAmelCase_ , UpperCAmelCase_ : Tuple = augmented[pivot_row], augmented[row] for rowa in range(row + 1 , __snake_case ): UpperCAmelCase_ : Optional[int] = augmented[rowa][col] / augmented[row][col] UpperCAmelCase_ : List[str] = 0 for cola in range(col + 1 , size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1 , __snake_case ): for row in range(__snake_case ): UpperCAmelCase_ : Union[str, Any] = augmented[row][col] / augmented[col][col] for cola in range(__snake_case , size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row] , 10 )] for row in range(__snake_case ) ] def lowercase__ ( __snake_case : list[int] ): '''simple docstring''' UpperCAmelCase_ : int = len(__snake_case ) UpperCAmelCase_ : Matrix = [[0 for _ in range(__snake_case )] for _ in range(__snake_case )] UpperCAmelCase_ : Matrix = [[0] for _ in range(__snake_case )] UpperCAmelCase_ : Matrix UpperCAmelCase_ : int UpperCAmelCase_ : int UpperCAmelCase_ : int for x_val, y_val in enumerate(__snake_case ): for col in range(__snake_case ): UpperCAmelCase_ : int = (x_val + 1) ** (size - col - 1) UpperCAmelCase_ : int = y_val UpperCAmelCase_ : List[str] = solve(__snake_case , __snake_case ) def interpolated_func(__snake_case : int ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(__snake_case ) ) return interpolated_func def lowercase__ ( __snake_case : int ): '''simple docstring''' return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def lowercase__ ( __snake_case : Callable[[int], int] = question_function , __snake_case : int = 10 ): '''simple docstring''' UpperCAmelCase_ : list[int] = [func(__snake_case ) for x_val in range(1 , order + 1 )] UpperCAmelCase_ : list[Callable[[int], int]] = [ interpolate(data_points[:max_coeff] ) for max_coeff in range(1 , order + 1 ) ] UpperCAmelCase_ : int = 0 UpperCAmelCase_ : Callable[[int], int] UpperCAmelCase_ : int for poly in polynomials: UpperCAmelCase_ : Optional[int] = 1 while func(__snake_case ) == poly(__snake_case ): x_val += 1 ret += poly(__snake_case ) return ret if __name__ == "__main__": print(F'{solution() = }')
145
0
"""simple docstring""" def lowercase ( a__ : List[Any] ) -> int: if divisor % 5 == 0 or divisor % 2 == 0: return 0 _UpperCamelCase = 1 _UpperCamelCase = 1 while repunit: _UpperCamelCase = (10 * repunit + 1) % divisor repunit_index += 1 return repunit_index def lowercase ( a__ : Optional[Any] = 1000000 ) -> int: _UpperCamelCase = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(_lowercase ) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(F'''{solution() = }''')
256
'''simple docstring''' from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask if is_tf_available(): import tensorflow as tf from transformers import TFBlipTextModel from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : def __init__( self , A , A=12 , A=7 , A=True , A=True , A=True , A=99 , A=32 , A=32 , A=2 , A=4 , A=37 , A=0.1 , A=0.1 , A=512 , A=0.0_2 , A=0 , A=None , ) -> Any: UpperCAmelCase : Optional[Any] = parent UpperCAmelCase : str = batch_size UpperCAmelCase : Union[str, Any] = seq_length UpperCAmelCase : Optional[Any] = is_training UpperCAmelCase : int = use_input_mask UpperCAmelCase : List[Any] = use_labels UpperCAmelCase : Dict = vocab_size UpperCAmelCase : str = hidden_size UpperCAmelCase : List[Any] = projection_dim UpperCAmelCase : Tuple = num_hidden_layers UpperCAmelCase : Dict = num_attention_heads UpperCAmelCase : Optional[Any] = intermediate_size UpperCAmelCase : Any = dropout UpperCAmelCase : List[Any] = attention_dropout UpperCAmelCase : Optional[Any] = max_position_embeddings UpperCAmelCase : Tuple = initializer_range UpperCAmelCase : Optional[Any] = scope UpperCAmelCase : Union[str, Any] = bos_token_id def _lowercase( self ) -> Tuple: UpperCAmelCase : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase : Union[str, Any] = None if self.use_input_mask: UpperCAmelCase : str = random_attention_mask([self.batch_size, self.seq_length] ) if input_mask is not None: UpperCAmelCase : Tuple = input_mask.numpy() UpperCAmelCase , UpperCAmelCase : int = input_mask.shape UpperCAmelCase : Optional[int] = np.random.randint(1 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(A ): UpperCAmelCase : Tuple = 1 UpperCAmelCase : Optional[Any] = 0 UpperCAmelCase : int = self.get_config() return config, input_ids, tf.convert_to_tensor(A ) def _lowercase( self ) -> int: return BlipTextConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , projection_dim=self.projection_dim , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , dropout=self.dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , bos_token_id=self.bos_token_id , ) def _lowercase( self , A , A , A ) -> Union[str, Any]: UpperCAmelCase : int = TFBlipTextModel(config=A ) UpperCAmelCase : Union[str, Any] = model(A , attention_mask=A , training=A ) UpperCAmelCase : int = model(A , training=A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def _lowercase( self ) -> Optional[int]: UpperCAmelCase : Dict = self.prepare_config_and_inputs() UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : Any = config_and_inputs UpperCAmelCase : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class UpperCamelCase_ ( __magic_name__ , unittest.TestCase ): lowercase = (TFBlipTextModel,) if is_tf_available() else () lowercase = False lowercase = False lowercase = False def _lowercase( self ) -> int: UpperCAmelCase : Union[str, Any] = BlipTextModelTester(self ) UpperCAmelCase : List[str] = ConfigTester(self , config_class=A , hidden_size=37 ) def _lowercase( self ) -> Tuple: self.config_tester.run_common_tests() def _lowercase( self ) -> List[Any]: UpperCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def _lowercase( self ) -> List[str]: pass def _lowercase( self ) -> Optional[int]: pass @unittest.skip(reason="""Blip does not use inputs_embeds""" ) def _lowercase( self ) -> Union[str, Any]: pass @unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING""" ) def _lowercase( self ) -> Optional[int]: pass @unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING""" ) def _lowercase( self ) -> Dict: pass @slow def _lowercase( self ) -> Dict: for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase : Any = TFBlipTextModel.from_pretrained(A ) self.assertIsNotNone(A ) def _lowercase( self , A=True ) -> str: super().test_pt_tf_model_equivalence(allow_missing_keys=A )
265
0
"""simple docstring""" from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class _a : def __init__( self : int, lowerCAmelCase__ : Collection[float] | None = None ) -> None: '''simple docstring''' if components is None: _UpperCamelCase : Tuple = [] _UpperCamelCase : Optional[int] = list(lowerCAmelCase__ ) def __len__( self : List[Any] ) -> int: '''simple docstring''' return len(self.__components ) def __str__( self : Dict ) -> str: '''simple docstring''' return "(" + ",".join(map(lowerCAmelCase__, self.__components ) ) + ")" def __add__( self : int, lowerCAmelCase__ : Vector ) -> Vector: '''simple docstring''' _UpperCamelCase : List[Any] = len(self ) if size == len(lowerCAmelCase__ ): _UpperCamelCase : str = [self.__components[i] + other.component(lowerCAmelCase__ ) for i in range(lowerCAmelCase__ )] return Vector(lowerCAmelCase__ ) else: raise Exception('''must have the same size''' ) def __sub__( self : Optional[Any], lowerCAmelCase__ : Vector ) -> Vector: '''simple docstring''' _UpperCamelCase : List[Any] = len(self ) if size == len(lowerCAmelCase__ ): _UpperCamelCase : List[Any] = [self.__components[i] - other.component(lowerCAmelCase__ ) for i in range(lowerCAmelCase__ )] return Vector(lowerCAmelCase__ ) else: # error case raise Exception('''must have the same size''' ) @overload def __mul__( self : Optional[int], lowerCAmelCase__ : float ) -> Vector: '''simple docstring''' ... @overload def __mul__( self : int, lowerCAmelCase__ : Vector ) -> float: '''simple docstring''' ... def __mul__( self : int, lowerCAmelCase__ : float | Vector ) -> float | Vector: '''simple docstring''' if isinstance(lowerCAmelCase__, (float, int) ): _UpperCamelCase : Tuple = [c * other for c in self.__components] return Vector(lowerCAmelCase__ ) elif isinstance(lowerCAmelCase__, lowerCAmelCase__ ) and len(self ) == len(lowerCAmelCase__ ): _UpperCamelCase : Tuple = len(self ) _UpperCamelCase : Any = [self.__components[i] * other.component(lowerCAmelCase__ ) for i in range(lowerCAmelCase__ )] return sum(lowerCAmelCase__ ) else: # error case raise Exception('''invalid operand!''' ) def snake_case ( self : List[str] ) -> Vector: '''simple docstring''' return Vector(self.__components ) def snake_case ( self : Any, lowerCAmelCase__ : int ) -> float: '''simple docstring''' if isinstance(lowerCAmelCase__, lowerCAmelCase__ ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('''index out of range''' ) def snake_case ( self : Optional[Any], lowerCAmelCase__ : int, lowerCAmelCase__ : float ) -> None: '''simple docstring''' assert -len(self.__components ) <= pos < len(self.__components ) _UpperCamelCase : List[str] = value def snake_case ( self : str ) -> float: '''simple docstring''' if len(self.__components ) == 0: raise Exception('''Vector is empty''' ) _UpperCamelCase : Optional[int] = [c**2 for c in self.__components] return math.sqrt(sum(lowerCAmelCase__ ) ) def snake_case ( self : Optional[Any], lowerCAmelCase__ : Vector, lowerCAmelCase__ : bool = False ) -> float: '''simple docstring''' _UpperCamelCase : Any = self * other _UpperCamelCase : Union[str, Any] = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def a_ ( _lowercase ): assert isinstance(_lowercase , _lowercase ) return Vector([0] * dimension ) def a_ ( _lowercase , _lowercase ): assert isinstance(_lowercase , _lowercase ) and (isinstance(_lowercase , _lowercase )) _UpperCamelCase : Tuple = [0] * dimension _UpperCamelCase : List[Any] = 1 return Vector(_lowercase ) def a_ ( _lowercase , _lowercase , _lowercase ): assert ( isinstance(_lowercase , _lowercase ) and isinstance(_lowercase , _lowercase ) and (isinstance(_lowercase , (int, float) )) ) return x * scalar + y def a_ ( _lowercase , _lowercase , _lowercase ): random.seed(_lowercase ) _UpperCamelCase : int = [random.randint(_lowercase , _lowercase ) for _ in range(_lowercase )] return Vector(_lowercase ) class _a : def __init__( self : Dict, lowerCAmelCase__ : list[list[float]], lowerCAmelCase__ : int, lowerCAmelCase__ : int ) -> None: '''simple docstring''' _UpperCamelCase : Union[str, Any] = matrix _UpperCamelCase : List[str] = w _UpperCamelCase : Dict = h def __str__( self : Optional[int] ) -> str: '''simple docstring''' _UpperCamelCase : Optional[Any] = '''''' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self : Any, lowerCAmelCase__ : Matrix ) -> Matrix: '''simple docstring''' if self.__width == other.width() and self.__height == other.height(): _UpperCamelCase : List[str] = [] for i in range(self.__height ): _UpperCamelCase : int = [ self.__matrix[i][j] + other.component(lowerCAmelCase__, lowerCAmelCase__ ) for j in range(self.__width ) ] matrix.append(lowerCAmelCase__ ) return Matrix(lowerCAmelCase__, self.__width, self.__height ) else: raise Exception('''matrix must have the same dimension!''' ) def __sub__( self : Union[str, Any], lowerCAmelCase__ : Matrix ) -> Matrix: '''simple docstring''' if self.__width == other.width() and self.__height == other.height(): _UpperCamelCase : int = [] for i in range(self.__height ): _UpperCamelCase : int = [ self.__matrix[i][j] - other.component(lowerCAmelCase__, lowerCAmelCase__ ) for j in range(self.__width ) ] matrix.append(lowerCAmelCase__ ) return Matrix(lowerCAmelCase__, self.__width, self.__height ) else: raise Exception('''matrices must have the same dimension!''' ) @overload def __mul__( self : Any, lowerCAmelCase__ : float ) -> Matrix: '''simple docstring''' ... @overload def __mul__( self : str, lowerCAmelCase__ : Vector ) -> Vector: '''simple docstring''' ... def __mul__( self : List[Any], lowerCAmelCase__ : float | Vector ) -> Vector | Matrix: '''simple docstring''' if isinstance(lowerCAmelCase__, lowerCAmelCase__ ): # matrix-vector if len(lowerCAmelCase__ ) == self.__width: _UpperCamelCase : List[Any] = zero_vector(self.__height ) for i in range(self.__height ): _UpperCamelCase : Dict = [ self.__matrix[i][j] * other.component(lowerCAmelCase__ ) for j in range(self.__width ) ] ans.change_component(lowerCAmelCase__, sum(lowerCAmelCase__ ) ) return ans else: raise Exception( '''vector must have the same size as the ''' '''number of columns of the matrix!''' ) elif isinstance(lowerCAmelCase__, (int, float) ): # matrix-scalar _UpperCamelCase : int = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(lowerCAmelCase__, self.__width, self.__height ) return None def snake_case ( self : Union[str, Any] ) -> int: '''simple docstring''' return self.__height def snake_case ( self : List[str] ) -> int: '''simple docstring''' return self.__width def snake_case ( self : Union[str, Any], lowerCAmelCase__ : int, lowerCAmelCase__ : int ) -> float: '''simple docstring''' if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('''change_component: indices out of bounds''' ) def snake_case ( self : Any, lowerCAmelCase__ : int, lowerCAmelCase__ : int, lowerCAmelCase__ : float ) -> None: '''simple docstring''' if 0 <= x < self.__height and 0 <= y < self.__width: _UpperCamelCase : str = value else: raise Exception('''change_component: indices out of bounds''' ) def snake_case ( self : List[Any], lowerCAmelCase__ : int, lowerCAmelCase__ : int ) -> float: '''simple docstring''' if self.__height != self.__width: raise Exception('''Matrix is not square''' ) _UpperCamelCase : Dict = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(lowerCAmelCase__ ) ): _UpperCamelCase : Optional[int] = minor[i][:y] + minor[i][y + 1 :] return Matrix(lowerCAmelCase__, self.__width - 1, self.__height - 1 ).determinant() def snake_case ( self : Union[str, Any], lowerCAmelCase__ : int, lowerCAmelCase__ : int ) -> float: '''simple docstring''' if self.__height != self.__width: raise Exception('''Matrix is not square''' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(lowerCAmelCase__, lowerCAmelCase__ ) else: raise Exception('''Indices out of bounds''' ) def snake_case ( self : Optional[Any] ) -> float: '''simple docstring''' if self.__height != self.__width: raise Exception('''Matrix is not square''' ) if self.__height < 1: raise Exception('''Matrix has no element''' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: _UpperCamelCase : Any = [ self.__matrix[0][y] * self.cofactor(0, lowerCAmelCase__ ) for y in range(self.__width ) ] return sum(lowerCAmelCase__ ) def a_ ( _lowercase ): _UpperCamelCase : list[list[float]] = [[0] * n for _ in range(_lowercase )] return Matrix(_lowercase , _lowercase , _lowercase ) def a_ ( _lowercase , _lowercase , _lowercase , _lowercase ): random.seed(_lowercase ) _UpperCamelCase : list[list[float]] = [ [random.randint(_lowercase , _lowercase ) for _ in range(_lowercase )] for _ in range(_lowercase ) ] return Matrix(_lowercase , _lowercase , _lowercase )
128
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class _a ( unittest.TestCase ): def snake_case ( self : Tuple ) -> Dict: '''simple docstring''' _UpperCamelCase : int = tempfile.mkdtemp() _UpperCamelCase : List[str] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''的''', '''价''', '''格''', '''是''', '''15''', '''便''', '''alex''', '''##andra''', ''',''', '''。''', '''-''', '''t''', '''shirt''', ] _UpperCamelCase : Optional[Any] = 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 : Dict = { '''do_resize''': True, '''size''': {'''height''': 2_2_4, '''width''': 2_2_4}, '''do_center_crop''': True, '''crop_size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.48_145_466, 0.4_578_275, 0.40_821_073], '''image_std''': [0.26_862_954, 0.26_130_258, 0.27_577_711], '''do_convert_rgb''': True, } _UpperCamelCase : Optional[Any] = os.path.join(self.tmpdirname, lowerCAmelCase__ ) with open(self.image_processor_file, '''w''', encoding='''utf-8''' ) as fp: json.dump(lowerCAmelCase__, lowerCAmelCase__ ) def snake_case ( self : str, **lowerCAmelCase__ : List[Any] ) -> Optional[int]: '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname, **lowerCAmelCase__ ) def snake_case ( self : Union[str, Any], **lowerCAmelCase__ : Tuple ) -> str: '''simple docstring''' return BertTokenizerFast.from_pretrained(self.tmpdirname, **lowerCAmelCase__ ) def snake_case ( self : Any, **lowerCAmelCase__ : Optional[int] ) -> Optional[Any]: '''simple docstring''' return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname, **lowerCAmelCase__ ) def snake_case ( self : str ) -> Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def snake_case ( self : Any ) -> int: '''simple docstring''' _UpperCamelCase : List[str] = [np.random.randint(2_5_5, size=(3, 3_0, 4_0_0), dtype=np.uinta )] _UpperCamelCase : List[Any] = [Image.fromarray(np.moveaxis(lowerCAmelCase__, 0, -1 ) ) for x in image_inputs] return image_inputs def snake_case ( self : str ) -> Any: '''simple docstring''' _UpperCamelCase : Any = self.get_tokenizer() _UpperCamelCase : int = self.get_rust_tokenizer() _UpperCamelCase : int = self.get_image_processor() _UpperCamelCase : Tuple = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__, image_processor=lowerCAmelCase__ ) processor_slow.save_pretrained(self.tmpdirname ) _UpperCamelCase : List[Any] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname, use_fast=lowerCAmelCase__ ) _UpperCamelCase : List[Any] = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__, image_processor=lowerCAmelCase__ ) processor_fast.save_pretrained(self.tmpdirname ) _UpperCamelCase : List[Any] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab(), tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab(), tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab(), tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer, lowerCAmelCase__ ) self.assertIsInstance(processor_fast.tokenizer, lowerCAmelCase__ ) self.assertEqual(processor_slow.image_processor.to_json_string(), image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string(), image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor, lowerCAmelCase__ ) self.assertIsInstance(processor_fast.image_processor, lowerCAmelCase__ ) def snake_case ( self : int ) -> Tuple: '''simple docstring''' _UpperCamelCase : List[Any] = ChineseCLIPProcessor(tokenizer=self.get_tokenizer(), image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _UpperCamelCase : Dict = self.get_tokenizer(cls_token='''(CLS)''', sep_token='''(SEP)''' ) _UpperCamelCase : List[str] = self.get_image_processor(do_normalize=lowerCAmelCase__ ) _UpperCamelCase : Optional[Any] = ChineseCLIPProcessor.from_pretrained( self.tmpdirname, cls_token='''(CLS)''', sep_token='''(SEP)''', do_normalize=lowerCAmelCase__ ) self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer, lowerCAmelCase__ ) self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor, lowerCAmelCase__ ) def snake_case ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' _UpperCamelCase : List[str] = self.get_image_processor() _UpperCamelCase : str = self.get_tokenizer() _UpperCamelCase : Optional[Any] = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__, image_processor=lowerCAmelCase__ ) _UpperCamelCase : List[str] = self.prepare_image_inputs() _UpperCamelCase : Any = image_processor(lowerCAmelCase__, return_tensors='''np''' ) _UpperCamelCase : Any = processor(images=lowerCAmelCase__, return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2 ) def snake_case ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' _UpperCamelCase : Tuple = self.get_image_processor() _UpperCamelCase : Optional[Any] = self.get_tokenizer() _UpperCamelCase : Any = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__, image_processor=lowerCAmelCase__ ) _UpperCamelCase : Tuple = '''Alexandra,T-shirt的价格是15便士。''' _UpperCamelCase : List[str] = processor(text=lowerCAmelCase__ ) _UpperCamelCase : Any = tokenizer(lowerCAmelCase__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key], encoded_processor[key] ) def snake_case ( self : Dict ) -> Tuple: '''simple docstring''' _UpperCamelCase : Tuple = self.get_image_processor() _UpperCamelCase : Optional[Any] = self.get_tokenizer() _UpperCamelCase : Dict = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__, image_processor=lowerCAmelCase__ ) _UpperCamelCase : Any = '''Alexandra,T-shirt的价格是15便士。''' _UpperCamelCase : Union[str, Any] = self.prepare_image_inputs() _UpperCamelCase : str = processor(text=lowerCAmelCase__, images=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ), ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(lowerCAmelCase__ ): processor() def snake_case ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' _UpperCamelCase : int = self.get_image_processor() _UpperCamelCase : int = self.get_tokenizer() _UpperCamelCase : Optional[Any] = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__, image_processor=lowerCAmelCase__ ) _UpperCamelCase : List[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _UpperCamelCase : List[Any] = processor.batch_decode(lowerCAmelCase__ ) _UpperCamelCase : Dict = tokenizer.batch_decode(lowerCAmelCase__ ) self.assertListEqual(lowerCAmelCase__, lowerCAmelCase__ ) def snake_case ( self : Union[str, Any] ) -> Dict: '''simple docstring''' _UpperCamelCase : Any = self.get_image_processor() _UpperCamelCase : Optional[int] = self.get_tokenizer() _UpperCamelCase : Optional[Any] = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__, image_processor=lowerCAmelCase__ ) _UpperCamelCase : Any = '''Alexandra,T-shirt的价格是15便士。''' _UpperCamelCase : int = self.prepare_image_inputs() _UpperCamelCase : Dict = processor(text=lowerCAmelCase__, images=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ), processor.model_input_names )
128
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) A : Union[str, Any] = {'''configuration_beit''': ['''BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BeitConfig''', '''BeitOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Tuple = ['''BeitFeatureExtractor'''] A : Tuple = ['''BeitImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Any = [ '''BEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BeitForImageClassification''', '''BeitForMaskedImageModeling''', '''BeitForSemanticSegmentation''', '''BeitModel''', '''BeitPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : str = [ '''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 A : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
274
import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class A (unittest.TestCase ): '''simple docstring''' def a_ ( self : Any ) -> Union[str, Any]: """simple docstring""" A__ = ["""a""", """b""", """c"""] # Defaults to last layer if both are None A__ , A__ = get_aligned_output_features_output_indices(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , ["""c"""] ) self.assertEqual(__lowerCAmelCase , [2] ) # Out indices set to match out features A__ , A__ = get_aligned_output_features_output_indices(["""a""", """c"""] , __lowerCAmelCase , __lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , ["""a""", """c"""] ) self.assertEqual(__lowerCAmelCase , [0, 2] ) # Out features set to match out indices A__ , A__ = get_aligned_output_features_output_indices(__lowerCAmelCase , [0, 2] , __lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , ["""a""", """c"""] ) self.assertEqual(__lowerCAmelCase , [0, 2] ) # Out features selected from negative indices A__ , A__ = get_aligned_output_features_output_indices(__lowerCAmelCase , [-3, -1] , __lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , ["""a""", """c"""] ) self.assertEqual(__lowerCAmelCase , [-3, -1] ) def a_ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" with self.assertRaises(__lowerCAmelCase ): verify_out_features_out_indices(["""a""", """b"""] , (0, 1) , __lowerCAmelCase ) # Out features must be a list with self.assertRaises(__lowerCAmelCase ): verify_out_features_out_indices(("""a""", """b""") , (0, 1) , ["""a""", """b"""] ) # Out features must be a subset of stage names with self.assertRaises(__lowerCAmelCase ): verify_out_features_out_indices(["""a""", """b"""] , (0, 1) , ["""a"""] ) # Out indices must be a list or tuple with self.assertRaises(__lowerCAmelCase ): verify_out_features_out_indices(__lowerCAmelCase , 0 , ["""a""", """b"""] ) # Out indices must be a subset of stage names with self.assertRaises(__lowerCAmelCase ): verify_out_features_out_indices(__lowerCAmelCase , (0, 1) , ["""a"""] ) # Out features and out indices must be the same length with self.assertRaises(__lowerCAmelCase ): verify_out_features_out_indices(["""a""", """b"""] , (0,) , ["""a""", """b""", """c"""] ) # Out features should match out indices with self.assertRaises(__lowerCAmelCase ): verify_out_features_out_indices(["""a""", """b"""] , (0, 2) , ["""a""", """b""", """c"""] ) # Out features and out indices should be in order with self.assertRaises(__lowerCAmelCase ): verify_out_features_out_indices(["""b""", """a"""] , (0, 1) , ["""a""", """b"""] ) # Check passes with valid inputs verify_out_features_out_indices(["""a""", """b""", """d"""] , (0, 1, -1) , ["""a""", """b""", """c""", """d"""] ) def a_ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" A__ = BackboneMixin() A__ = ["""a""", """b""", """c"""] A__ = ["""a""", """c"""] A__ = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ["""a""", """c"""] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly A__ = ["""a""", """b"""] self.assertEqual(backbone.out_features , ["""a""", """b"""] ) self.assertEqual(backbone.out_indices , [0, 1] ) A__ = [-3, -1] self.assertEqual(backbone.out_features , ["""a""", """c"""] ) self.assertEqual(backbone.out_indices , [-3, -1] )
274
1
import inspect import unittest from transformers import YolosConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import YolosForObjectDetection, YolosModel from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __A : """simple docstring""" def __init__( self , lowerCamelCase__ , lowerCamelCase__=13 , lowerCamelCase__=[30, 30] , lowerCamelCase__=2 , lowerCamelCase__=3 , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=32 , lowerCamelCase__=5 , lowerCamelCase__=4 , lowerCamelCase__=37 , lowerCamelCase__="gelu" , lowerCamelCase__=0.1 , lowerCamelCase__=0.1 , lowerCamelCase__=10 , lowerCamelCase__=0.02 , lowerCamelCase__=3 , lowerCamelCase__=None , lowerCamelCase__=8 , lowerCamelCase__=10 , ): """simple docstring""" __UpperCamelCase : Optional[Any] =parent __UpperCamelCase : Union[str, Any] =batch_size __UpperCamelCase : Dict =image_size __UpperCamelCase : Tuple =patch_size __UpperCamelCase : int =num_channels __UpperCamelCase : Union[str, Any] =is_training __UpperCamelCase : Optional[Any] =use_labels __UpperCamelCase : int =hidden_size __UpperCamelCase : Optional[Any] =num_hidden_layers __UpperCamelCase : Tuple =num_attention_heads __UpperCamelCase : List[str] =intermediate_size __UpperCamelCase : List[Any] =hidden_act __UpperCamelCase : List[str] =hidden_dropout_prob __UpperCamelCase : str =attention_probs_dropout_prob __UpperCamelCase : Union[str, Any] =type_sequence_label_size __UpperCamelCase : int =initializer_range __UpperCamelCase : Any =num_labels __UpperCamelCase : str =scope __UpperCamelCase : Optional[Any] =n_targets __UpperCamelCase : str =num_detection_tokens # we set the expected sequence length (which is used in several tests) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens __UpperCamelCase : List[str] =(image_size[1] // patch_size) * (image_size[0] // patch_size) __UpperCamelCase : List[str] =num_patches + 1 + self.num_detection_tokens def __lowercase ( self ): """simple docstring""" __UpperCamelCase : str =floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]] ) __UpperCamelCase : List[str] =None if self.use_labels: # labels is a list of Dict (each Dict being the labels for a given example in the batch) __UpperCamelCase : str =[] for i in range(self.batch_size ): __UpperCamelCase : str ={} __UpperCamelCase : Union[str, Any] =torch.randint( high=self.num_labels , size=(self.n_targets,) , device=lowerCamelCase__ ) __UpperCamelCase : List[Any] =torch.rand(self.n_targets , 4 , device=lowerCamelCase__ ) labels.append(lowerCamelCase__ ) __UpperCamelCase : int =self.get_config() return config, pixel_values, labels def __lowercase ( self ): """simple docstring""" return YolosConfig( 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 , num_detection_tokens=self.num_detection_tokens , num_labels=self.num_labels , ) def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" __UpperCamelCase : int =YolosModel(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __UpperCamelCase : Dict =model(lowerCamelCase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.expected_seq_len, self.hidden_size) ) def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" __UpperCamelCase : int =YolosForObjectDetection(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __UpperCamelCase : Any =model(pixel_values=lowerCamelCase__ ) __UpperCamelCase : Optional[int] =model(lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_detection_tokens, self.num_labels + 1) ) self.parent.assertEqual(result.pred_boxes.shape , (self.batch_size, self.num_detection_tokens, 4) ) __UpperCamelCase : Optional[Any] =model(pixel_values=lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_detection_tokens, self.num_labels + 1) ) self.parent.assertEqual(result.pred_boxes.shape , (self.batch_size, self.num_detection_tokens, 4) ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Optional[int] =self.prepare_config_and_inputs() __UpperCamelCase , __UpperCamelCase , __UpperCamelCase : Optional[int] =config_and_inputs __UpperCamelCase : Tuple ={'pixel_values': pixel_values} return config, inputs_dict @require_torch class __A ( a , a , unittest.TestCase ): """simple docstring""" UpperCamelCase__ : Optional[Any] =(YolosModel, YolosForObjectDetection) if is_torch_available() else () UpperCamelCase__ : Tuple =( {"""feature-extraction""": YolosModel, """object-detection""": YolosForObjectDetection} if is_torch_available() else {} ) UpperCamelCase__ : Optional[int] =False UpperCamelCase__ : Union[str, Any] =False UpperCamelCase__ : Optional[int] =False UpperCamelCase__ : Tuple =False def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=False ): """simple docstring""" __UpperCamelCase : Any =super()._prepare_for_class(lowerCamelCase__ , lowerCamelCase__ , return_labels=lowerCamelCase__ ) if return_labels: if model_class.__name__ == "YolosForObjectDetection": __UpperCamelCase : int =[] for i in range(self.model_tester.batch_size ): __UpperCamelCase : Optional[Any] ={} __UpperCamelCase : List[str] =torch.ones( size=(self.model_tester.n_targets,) , device=lowerCamelCase__ , dtype=torch.long ) __UpperCamelCase : List[str] =torch.ones( self.model_tester.n_targets , 4 , device=lowerCamelCase__ , dtype=torch.float ) labels.append(lowerCamelCase__ ) __UpperCamelCase : Any =labels return inputs_dict def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Union[str, Any] =YolosModelTester(self ) __UpperCamelCase : Tuple =ConfigTester(self , config_class=lowerCamelCase__ , has_text_modality=lowerCamelCase__ , hidden_size=37 ) def __lowercase ( self ): """simple docstring""" self.config_tester.run_common_tests() def __lowercase ( self ): """simple docstring""" pass def __lowercase ( self ): """simple docstring""" __UpperCamelCase , __UpperCamelCase : Optional[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase : int =model_class(lowerCamelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __UpperCamelCase : List[Any] =model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCamelCase__ , nn.Linear ) ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase , __UpperCamelCase : Tuple =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase : Optional[Any] =model_class(lowerCamelCase__ ) __UpperCamelCase : int =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCamelCase : Dict =[*signature.parameters.keys()] __UpperCamelCase : Any =['pixel_values'] self.assertListEqual(arg_names[:1] , lowerCamelCase__ ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Any =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase__ ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase , __UpperCamelCase : Optional[int] =self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase : Any =True # in YOLOS, the seq_len is different __UpperCamelCase : int =self.model_tester.expected_seq_len for model_class in self.all_model_classes: __UpperCamelCase : int =True __UpperCamelCase : List[str] =False __UpperCamelCase : Dict =True __UpperCamelCase : int =model_class(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() with torch.no_grad(): __UpperCamelCase : Any =model(**self._prepare_for_class(lowerCamelCase__ , lowerCamelCase__ ) ) __UpperCamelCase : Any =outputs.attentions self.assertEqual(len(lowerCamelCase__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __UpperCamelCase : str =True __UpperCamelCase : int =model_class(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() with torch.no_grad(): __UpperCamelCase : int =model(**self._prepare_for_class(lowerCamelCase__ , lowerCamelCase__ ) ) __UpperCamelCase : Any =outputs.attentions self.assertEqual(len(lowerCamelCase__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) __UpperCamelCase : Tuple =len(lowerCamelCase__ ) # Check attention is always last and order is fine __UpperCamelCase : int =True __UpperCamelCase : Optional[Any] =True __UpperCamelCase : Dict =model_class(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() with torch.no_grad(): __UpperCamelCase : Dict =model(**self._prepare_for_class(lowerCamelCase__ , lowerCamelCase__ ) ) __UpperCamelCase : List[str] =1 self.assertEqual(out_len + added_hidden_states , len(lowerCamelCase__ ) ) __UpperCamelCase : Union[str, Any] =outputs.attentions self.assertEqual(len(lowerCamelCase__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) def __lowercase ( self ): """simple docstring""" def check_hidden_states_output(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): __UpperCamelCase : int =model_class(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() with torch.no_grad(): __UpperCamelCase : Union[str, Any] =model(**self._prepare_for_class(lowerCamelCase__ , lowerCamelCase__ ) ) __UpperCamelCase : Tuple =outputs.hidden_states __UpperCamelCase : str =getattr( self.model_tester , 'expected_num_hidden_layers' , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(lowerCamelCase__ ) , lowerCamelCase__ ) # YOLOS has a different seq_length __UpperCamelCase : Union[str, Any] =self.model_tester.expected_seq_len self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) __UpperCamelCase , __UpperCamelCase : Optional[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase : Dict =True check_hidden_states_output(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCamelCase : str =True check_hidden_states_output(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Any =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_object_detection(*lowerCamelCase__ ) @slow def __lowercase ( self ): """simple docstring""" for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase : List[Any] =YolosModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) def A ( ) -> Union[str, Any]: __UpperCamelCase : Optional[Any] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class __A ( unittest.TestCase ): """simple docstring""" @cached_property def __lowercase ( self ): """simple docstring""" return AutoImageProcessor.from_pretrained('hustvl/yolos-small' ) if is_vision_available() else None @slow def __lowercase ( self ): """simple docstring""" __UpperCamelCase : List[str] =YolosForObjectDetection.from_pretrained('hustvl/yolos-small' ).to(lowerCamelCase__ ) __UpperCamelCase : Any =self.default_image_processor __UpperCamelCase : Optional[Any] =prepare_img() __UpperCamelCase : List[Any] =image_processor(images=lowerCamelCase__ , return_tensors='pt' ).to(lowerCamelCase__ ) # forward pass with torch.no_grad(): __UpperCamelCase : Dict =model(inputs.pixel_values ) # verify outputs __UpperCamelCase : str =torch.Size((1, 100, 92) ) self.assertEqual(outputs.logits.shape , lowerCamelCase__ ) __UpperCamelCase : Optional[Any] =torch.tensor( [[-24.0_248, -10.3_024, -14.8_290], [-42.0_392, -16.8_200, -27.4_334], [-27.2_743, -11.8_154, -18.7_148]] , device=lowerCamelCase__ , ) __UpperCamelCase : Dict =torch.tensor( [[0.2_559, 0.5_455, 0.4_706], [0.2_989, 0.7_279, 0.1_875], [0.7_732, 0.4_017, 0.4_462]] , device=lowerCamelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , lowerCamelCase__ , atol=1E-4 ) ) self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3] , lowerCamelCase__ , atol=1E-4 ) ) # verify postprocessing __UpperCamelCase : Any =image_processor.post_process_object_detection( lowerCamelCase__ , threshold=0.3 , target_sizes=[image.size[::-1]] )[0] __UpperCamelCase : Union[str, Any] =torch.tensor([0.9_994, 0.9_790, 0.9_964, 0.9_972, 0.9_861] ).to(lowerCamelCase__ ) __UpperCamelCase : List[Any] =[75, 75, 17, 63, 17] __UpperCamelCase : Any =torch.tensor([335.0_609, 79.3_848, 375.4_216, 187.2_495] ).to(lowerCamelCase__ ) self.assertEqual(len(results['scores'] ) , 5 ) self.assertTrue(torch.allclose(results['scores'] , lowerCamelCase__ , atol=1E-4 ) ) self.assertSequenceEqual(results['labels'].tolist() , lowerCamelCase__ ) self.assertTrue(torch.allclose(results['boxes'][0, :] , lowerCamelCase__ ) )
245
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def A ( a_ ) -> int: __UpperCamelCase : List[Any] =botoa.client('iam' ) __UpperCamelCase : List[str] ={ 'Version': '2012-10-17', 'Statement': [ {'Effect': 'Allow', 'Principal': {'Service': 'sagemaker.amazonaws.com'}, 'Action': 'sts:AssumeRole'} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=a_ ,AssumeRolePolicyDocument=json.dumps(a_ ,indent=2 ) ) __UpperCamelCase : List[str] ={ 'Version': '2012-10-17', 'Statement': [ { 'Effect': 'Allow', 'Action': [ 'sagemaker:*', 'ecr:GetDownloadUrlForLayer', 'ecr:BatchGetImage', 'ecr:BatchCheckLayerAvailability', 'ecr:GetAuthorizationToken', 'cloudwatch:PutMetricData', 'cloudwatch:GetMetricData', 'cloudwatch:GetMetricStatistics', 'cloudwatch:ListMetrics', 'logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:DescribeLogStreams', 'logs:PutLogEvents', 'logs:GetLogEvents', 's3:CreateBucket', 's3:ListBucket', 's3:GetBucketLocation', 's3:GetObject', 's3:PutObject', ], 'Resource': '*', } ], } # attach policy to role iam_client.put_role_policy( RoleName=a_ ,PolicyName=F'{role_name}_policy_permission' ,PolicyDocument=json.dumps(a_ ,indent=2 ) ,) except iam_client.exceptions.EntityAlreadyExistsException: print(F'role {role_name} already exists. Using existing one' ) def A ( a_ ) -> Optional[Any]: __UpperCamelCase : List[Any] =botoa.client('iam' ) return iam_client.get_role(RoleName=a_ )["Role"]["Arn"] def A ( ) -> Tuple: __UpperCamelCase : Any =_ask_options( 'How do you want to authorize?' ,['AWS Profile', 'Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) '] ,a_ ,) __UpperCamelCase : str =None if credentials_configuration == 0: __UpperCamelCase : str =_ask_field('Enter your AWS Profile name: [default] ' ,default='default' ) __UpperCamelCase : Optional[Any] =aws_profile else: print( 'Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,' '`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`' ) __UpperCamelCase : int =_ask_field('AWS Access Key ID: ' ) __UpperCamelCase : Dict =aws_access_key_id __UpperCamelCase : Any =_ask_field('AWS Secret Access Key: ' ) __UpperCamelCase : Optional[Any] =aws_secret_access_key __UpperCamelCase : Tuple =_ask_field('Enter your AWS Region: [us-east-1]' ,default='us-east-1' ) __UpperCamelCase : List[str] =aws_region __UpperCamelCase : Any =_ask_options( 'Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?' ,['Provide IAM Role name', 'Create new IAM role using credentials'] ,a_ ,) if role_management == 0: __UpperCamelCase : Optional[Any] =_ask_field('Enter your IAM role name: ' ) else: __UpperCamelCase : Dict ='accelerate_sagemaker_execution_role' print(F'Accelerate will create an iam role "{iam_role_name}" using the provided credentials' ) _create_iam_role_for_sagemaker(a_ ) __UpperCamelCase : List[Any] =_ask_field( 'Do you want to use custom Docker image? [yes/NO]: ' ,_convert_yes_no_to_bool ,default=a_ ,error_message='Please enter yes or no.' ,) __UpperCamelCase : int =None if is_custom_docker_image: __UpperCamelCase : List[Any] =_ask_field('Enter your Docker image: ' ,lambda a_ : str(a_ ).lower() ) __UpperCamelCase : Union[str, Any] =_ask_field( 'Do you want to provide SageMaker input channels with data locations? [yes/NO]: ' ,_convert_yes_no_to_bool ,default=a_ ,error_message='Please enter yes or no.' ,) __UpperCamelCase : Optional[Any] =None if is_sagemaker_inputs_enabled: __UpperCamelCase : Optional[Any] =_ask_field( 'Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): ' ,lambda a_ : str(a_ ).lower() ,) __UpperCamelCase : str =_ask_field( 'Do you want to enable SageMaker metrics? [yes/NO]: ' ,_convert_yes_no_to_bool ,default=a_ ,error_message='Please enter yes or no.' ,) __UpperCamelCase : Dict =None if is_sagemaker_metrics_enabled: __UpperCamelCase : Optional[Any] =_ask_field( 'Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): ' ,lambda a_ : str(a_ ).lower() ,) __UpperCamelCase : int =_ask_options( 'What is the distributed mode?' ,['No distributed training', 'Data parallelism'] ,_convert_sagemaker_distributed_mode ,) __UpperCamelCase : int ={} __UpperCamelCase : str =_ask_field( 'Do you wish to optimize your script with torch dynamo?[yes/NO]:' ,_convert_yes_no_to_bool ,default=a_ ,error_message='Please enter yes or no.' ,) if use_dynamo: __UpperCamelCase : Dict ='dynamo_' __UpperCamelCase : Optional[int] =_ask_options( 'Which dynamo backend would you like to use?' ,[x.lower() for x in DYNAMO_BACKENDS] ,_convert_dynamo_backend ,default=2 ,) __UpperCamelCase : Tuple =_ask_field( 'Do you want to customize the defaults sent to torch.compile? [yes/NO]: ' ,_convert_yes_no_to_bool ,default=a_ ,error_message='Please enter yes or no.' ,) if use_custom_options: __UpperCamelCase : List[str] =_ask_options( 'Which mode do you want to use?' ,a_ ,lambda a_ : TORCH_DYNAMO_MODES[int(a_ )] ,default='default' ,) __UpperCamelCase : Union[str, Any] =_ask_field( 'Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ' ,_convert_yes_no_to_bool ,default=a_ ,error_message='Please enter yes or no.' ,) __UpperCamelCase : Tuple =_ask_field( 'Do you want to enable dynamic shape tracing? [yes/NO]: ' ,_convert_yes_no_to_bool ,default=a_ ,error_message='Please enter yes or no.' ,) __UpperCamelCase : Tuple ='Which EC2 instance type you want to use for your training?' if distributed_type != SageMakerDistributedType.NO: __UpperCamelCase : int =_ask_options( a_ ,a_ ,lambda a_ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(a_ )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" __UpperCamelCase : List[str] =_ask_field(a_ ,lambda a_ : str(a_ ).lower() ,default='ml.p3.2xlarge' ) __UpperCamelCase : Union[str, Any] =1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): __UpperCamelCase : List[str] =_ask_field( 'How many machines do you want use? [1]: ' ,a_ ,default=1 ,) __UpperCamelCase : Optional[Any] =_ask_options( 'Do you wish to use FP16 or BF16 (mixed precision)?' ,['no', 'fp16', 'bf16', 'fp8'] ,_convert_mixed_precision ,) if use_dynamo and mixed_precision == "no": print( 'Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.' ) return SageMakerConfig( image_uri=a_ ,compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER ,distributed_type=a_ ,use_cpu=a_ ,dynamo_config=a_ ,eca_instance_type=a_ ,profile=a_ ,region=a_ ,iam_role_name=a_ ,mixed_precision=a_ ,num_machines=a_ ,sagemaker_inputs_file=a_ ,sagemaker_metrics_file=a_ ,)
245
1
import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class __a ( unittest.TestCase ): def __lowercase ( self : Any ): '''simple docstring''' UpperCamelCase__ : Tuple = "ZinengTang/tvlt-base" UpperCamelCase__ : Optional[int] = tempfile.mkdtemp() def __lowercase ( self : List[str] , **SCREAMING_SNAKE_CASE : int ): '''simple docstring''' return TvltImageProcessor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE ) def __lowercase ( self : List[str] , **SCREAMING_SNAKE_CASE : Optional[int] ): '''simple docstring''' return TvltFeatureExtractor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE ) def __lowercase ( self : int ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def __lowercase ( self : List[str] ): '''simple docstring''' UpperCamelCase__ : List[str] = self.get_image_processor() UpperCamelCase__ : Optional[Any] = self.get_feature_extractor() UpperCamelCase__ : Dict = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE , feature_extractor=SCREAMING_SNAKE_CASE ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase__ : List[Any] = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE ) def __lowercase ( self : Any ): '''simple docstring''' UpperCamelCase__ : int = self.get_image_processor() UpperCamelCase__ : List[str] = self.get_feature_extractor() UpperCamelCase__ : Optional[int] = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE , feature_extractor=SCREAMING_SNAKE_CASE ) UpperCamelCase__ : Optional[int] = np.ones([1_20_00] ) UpperCamelCase__ : Dict = feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="np" ) UpperCamelCase__ : Optional[int] = processor(audio=SCREAMING_SNAKE_CASE , return_tensors="np" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowercase ( self : List[str] ): '''simple docstring''' UpperCamelCase__ : Any = self.get_image_processor() UpperCamelCase__ : Any = self.get_feature_extractor() UpperCamelCase__ : Union[str, Any] = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE , feature_extractor=SCREAMING_SNAKE_CASE ) UpperCamelCase__ : Optional[Any] = np.ones([3, 2_24, 2_24] ) UpperCamelCase__ : List[Any] = image_processor(SCREAMING_SNAKE_CASE , return_tensors="np" ) UpperCamelCase__ : List[Any] = processor(images=SCREAMING_SNAKE_CASE , return_tensors="np" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowercase ( self : Union[str, Any] ): '''simple docstring''' UpperCamelCase__ : Optional[int] = self.get_image_processor() UpperCamelCase__ : Any = self.get_feature_extractor() UpperCamelCase__ : int = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE , feature_extractor=SCREAMING_SNAKE_CASE ) UpperCamelCase__ : List[Any] = np.ones([1_20_00] ) UpperCamelCase__ : str = np.ones([3, 2_24, 2_24] ) UpperCamelCase__ : Any = processor(audio=SCREAMING_SNAKE_CASE , images=SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ["audio_values", "audio_mask", "pixel_values", "pixel_mask"] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE ): processor() def __lowercase ( self : Optional[Any] ): '''simple docstring''' UpperCamelCase__ : Dict = self.get_image_processor() UpperCamelCase__ : Tuple = self.get_feature_extractor() UpperCamelCase__ : Any = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE , feature_extractor=SCREAMING_SNAKE_CASE ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg="`processor` and `image_processor`+`feature_extractor` model input names do not match" , )
189
from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder # @@protoc_insertion_point(imports) lowerCamelCase : Tuple =_symbol_database.Default() lowerCamelCase : List[str] =_descriptor_pool.Default().AddSerializedFile( b'''\n\x19sentencepiece_model.proto\x12\rsentencepiece"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18. \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03''' ) lowerCamelCase : str =globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, '''sentencepiece_model_pb2''', _globals) if _descriptor._USE_C_DESCRIPTORS is False: lowerCamelCase : Optional[int] =None lowerCamelCase : Tuple =b'''H\003''' # (generated by protobuf compiler, but `_TRAINERSPEC` is not defined) # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001" # _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001" lowerCamelCase : List[str] =45 lowerCamelCase : List[Any] =1581 lowerCamelCase : Optional[int] =1517 lowerCamelCase : Tuple =1570 lowerCamelCase : Dict =1584 lowerCamelCase : Optional[Any] =1793 lowerCamelCase : Dict =1795 lowerCamelCase : Any =1916 lowerCamelCase : Dict =1864 lowerCamelCase : Dict =1905 lowerCamelCase : Dict =1919 lowerCamelCase : Union[str, Any] =2429 lowerCamelCase : List[Any] =2208 lowerCamelCase : List[Any] =2418 lowerCamelCase : List[str] =2323 lowerCamelCase : Dict =2407 # @@protoc_insertion_point(module_scope)
189
1
"""simple docstring""" from typing import Callable, Dict, Optional, Tuple import torch from torch import nn from torch.distributions import ( AffineTransform, Distribution, Independent, NegativeBinomial, Normal, StudentT, TransformedDistribution, ) class __snake_case ( _lowercase): def __init__( self : Any , __lowerCAmelCase : Distribution , __lowerCAmelCase : List[Any]=None , __lowerCAmelCase : Union[str, Any]=None , __lowerCAmelCase : Dict=0 ): """simple docstring""" _lowerCamelCase : List[Any] = 1.0 if scale is None else scale _lowerCamelCase : Union[str, Any] = 0.0 if loc is None else loc super().__init__(__lowerCAmelCase , [AffineTransform(loc=self.loc , scale=self.scale , event_dim=__lowerCAmelCase )] ) @property def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return self.base_dist.mean * self.scale + self.loc @property def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return self.base_dist.variance * self.scale**2 @property def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return self.variance.sqrt() class __snake_case ( nn.Module): def __init__( self : Any , __lowerCAmelCase : int , __lowerCAmelCase : Dict[str, int] , __lowerCAmelCase : Callable[..., Tuple[torch.Tensor]] , **__lowerCAmelCase : Any ): """simple docstring""" super().__init__(**__lowerCAmelCase ) _lowerCamelCase : str = args_dim _lowerCamelCase : Dict = nn.ModuleList([nn.Linear(__lowerCAmelCase , __lowerCAmelCase ) for dim in args_dim.values()] ) _lowerCamelCase : List[Any] = domain_map def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : torch.Tensor ): """simple docstring""" _lowerCamelCase : Optional[Any] = [proj(__lowerCAmelCase ) for proj in self.proj] return self.domain_map(*__lowerCAmelCase ) class __snake_case ( nn.Module): def __init__( self : List[Any] , __lowerCAmelCase : str ): """simple docstring""" super().__init__() _lowerCamelCase : str = function def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : Optional[int] , *__lowerCAmelCase : int ): """simple docstring""" return self.function(__lowerCAmelCase , *__lowerCAmelCase ) class __snake_case : snake_case__ : type snake_case__ : int snake_case__ : Dict[str, int] def __init__( self : int , __lowerCAmelCase : int = 1 ): """simple docstring""" _lowerCamelCase : str = dim _lowerCamelCase : Optional[int] = {k: dim * self.args_dim[k] for k in self.args_dim} def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : Any ): """simple docstring""" if self.dim == 1: return self.distribution_class(*__lowerCAmelCase ) else: return Independent(self.distribution_class(*__lowerCAmelCase ) , 1 ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[torch.Tensor] = None , __lowerCAmelCase : Optional[torch.Tensor] = None , ): """simple docstring""" _lowerCamelCase : int = self._base_distribution(__lowerCAmelCase ) if loc is None and scale is None: return distr else: return AffineTransformed(__lowerCAmelCase , loc=__lowerCAmelCase , scale=__lowerCAmelCase , event_dim=self.event_dim ) @property def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return () if self.dim == 1 else (self.dim,) @property def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return len(self.event_shape ) @property def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" return 0.0 def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : int ): """simple docstring""" return ParameterProjection( in_features=__lowerCAmelCase , args_dim=self.args_dim , domain_map=LambdaLayer(self.domain_map ) , ) def SCREAMING_SNAKE_CASE ( self : str , *__lowerCAmelCase : torch.Tensor ): """simple docstring""" raise NotImplementedError() @staticmethod def SCREAMING_SNAKE_CASE ( __lowerCAmelCase : torch.Tensor ): """simple docstring""" return (x + torch.sqrt(torch.square(__lowerCAmelCase ) + 4.0 )) / 2.0 class __snake_case ( _lowercase): snake_case__ : Dict[str, int] = {"df": 1, "loc": 1, "scale": 1} snake_case__ : type = StudentT @classmethod def SCREAMING_SNAKE_CASE ( cls : Optional[int] , __lowerCAmelCase : torch.Tensor , __lowerCAmelCase : torch.Tensor , __lowerCAmelCase : torch.Tensor ): """simple docstring""" _lowerCamelCase : List[str] = cls.squareplus(__lowerCAmelCase ).clamp_min(torch.finfo(scale.dtype ).eps ) _lowerCamelCase : Dict = 2.0 + cls.squareplus(__lowerCAmelCase ) return df.squeeze(-1 ), loc.squeeze(-1 ), scale.squeeze(-1 ) class __snake_case ( _lowercase): snake_case__ : Dict[str, int] = {"loc": 1, "scale": 1} snake_case__ : type = Normal @classmethod def SCREAMING_SNAKE_CASE ( cls : Optional[int] , __lowerCAmelCase : torch.Tensor , __lowerCAmelCase : torch.Tensor ): """simple docstring""" _lowerCamelCase : Union[str, Any] = cls.squareplus(__lowerCAmelCase ).clamp_min(torch.finfo(scale.dtype ).eps ) return loc.squeeze(-1 ), scale.squeeze(-1 ) class __snake_case ( _lowercase): snake_case__ : Dict[str, int] = {"total_count": 1, "logits": 1} snake_case__ : type = NegativeBinomial @classmethod def SCREAMING_SNAKE_CASE ( cls : Optional[int] , __lowerCAmelCase : torch.Tensor , __lowerCAmelCase : torch.Tensor ): """simple docstring""" _lowerCamelCase : Optional[int] = cls.squareplus(__lowerCAmelCase ) return total_count.squeeze(-1 ), logits.squeeze(-1 ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , __lowerCAmelCase : List[str] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = distr_args if self.dim == 1: return self.distribution_class(total_count=__lowerCAmelCase , logits=__lowerCAmelCase ) else: return Independent(self.distribution_class(total_count=__lowerCAmelCase , logits=__lowerCAmelCase ) , 1 ) def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[torch.Tensor] = None , __lowerCAmelCase : Optional[torch.Tensor] = None ): """simple docstring""" _lowerCamelCase : Any = distr_args if scale is not None: # See scaling property of Gamma. logits += scale.log() return self._base_distribution((total_count, logits) )
366
"""simple docstring""" import argparse from torch import nn # transformers_old should correspond to branch `save_old_prophetnet_model_structure` here # original prophetnet_checkpoints are saved under `patrickvonplaten/..._old` respectively from transformers_old.modeling_prophetnet import ( ProphetNetForConditionalGeneration as ProphetNetForConditionalGenerationOld, ) from transformers_old.modeling_xlm_prophetnet import ( XLMProphetNetForConditionalGeneration as XLMProphetNetForConditionalGenerationOld, ) from transformers import ProphetNetForConditionalGeneration, XLMProphetNetForConditionalGeneration, logging lowerCAmelCase__ = logging.get_logger(__name__) logging.set_verbosity_info() def snake_case_ ( A_ : str, A_ : str ): '''simple docstring''' if "xprophetnet" in prophetnet_checkpoint_path: _lowerCamelCase : Any = XLMProphetNetForConditionalGenerationOld.from_pretrained(A_ ) _lowerCamelCase , _lowerCamelCase : List[str] = XLMProphetNetForConditionalGeneration.from_pretrained( A_, output_loading_info=A_ ) else: _lowerCamelCase : str = ProphetNetForConditionalGenerationOld.from_pretrained(A_ ) _lowerCamelCase , _lowerCamelCase : Any = ProphetNetForConditionalGeneration.from_pretrained( A_, output_loading_info=A_ ) _lowerCamelCase : Optional[Any] = ['''key_proj''', '''value_proj''', '''query_proj'''] _lowerCamelCase : List[Any] = { '''self_attn''': '''ngram_self_attn''', '''cross_attn''': '''encoder_attn''', '''cross_attn_layer_norm''': '''encoder_attn_layer_norm''', '''feed_forward_layer_norm''': '''final_layer_norm''', '''feed_forward''': '''''', '''intermediate''': '''fc1''', '''output''': '''fc2''', '''key_proj''': '''k_proj''', '''query_proj''': '''q_proj''', '''value_proj''': '''v_proj''', '''word_embeddings''': '''embed_tokens''', '''embeddings_layer_norm''': '''emb_layer_norm''', '''relative_pos_embeddings''': '''relative_linear''', '''ngram_embeddings''': '''ngram_input_embed''', '''position_embeddings''': '''embed_positions''', } for key in loading_info["missing_keys"]: _lowerCamelCase : Union[str, Any] = key.split('''.''' ) if attributes[0] == "lm_head": _lowerCamelCase : str = prophet _lowerCamelCase : List[Any] = prophet_old else: _lowerCamelCase : Optional[int] = prophet.prophetnet _lowerCamelCase : Optional[Any] = prophet_old.model _lowerCamelCase : Any = False for attribute in attributes: if attribute in mapping: _lowerCamelCase : Optional[int] = mapping[attribute] if not hasattr(A_, A_ ) and len(A_ ) > 0: _lowerCamelCase : int = attribute elif hasattr(A_, A_ ): _lowerCamelCase : int = attribute if attribute == "weight": assert old_model.weight.shape == model.weight.shape, "Shapes have to match!" _lowerCamelCase : Optional[int] = old_model.weight logger.info(F'''{attribute} is initialized.''' ) _lowerCamelCase : List[str] = True break elif attribute == "bias": assert old_model.bias.shape == model.bias.shape, "Shapes have to match!" _lowerCamelCase : int = old_model.bias logger.info(F'''{attribute} is initialized''' ) _lowerCamelCase : Union[str, Any] = True break elif attribute in special_keys and hasattr(A_, '''in_proj_weight''' ): _lowerCamelCase : Tuple = old_model.in_proj_weight.shape[0] // 3 _lowerCamelCase : List[Any] = getattr(A_, A_ ) param.weight.shape == old_model.in_proj_weight[:embed_dim, :].shape, "Shapes have to match" param.bias.shape == old_model.in_proj_bias[:embed_dim].shape, "Shapes have to match" if attribute == "query_proj": _lowerCamelCase : Optional[Any] = nn.Parameter(old_model.in_proj_weight[:embed_dim, :] ) _lowerCamelCase : int = nn.Parameter(old_model.in_proj_bias[:embed_dim] ) elif attribute == "key_proj": _lowerCamelCase : int = nn.Parameter(old_model.in_proj_weight[embed_dim : 2 * embed_dim, :] ) _lowerCamelCase : str = nn.Parameter(old_model.in_proj_bias[embed_dim : 2 * embed_dim] ) elif attribute == "value_proj": _lowerCamelCase : Tuple = nn.Parameter(old_model.in_proj_weight[2 * embed_dim :, :] ) _lowerCamelCase : str = nn.Parameter(old_model.in_proj_bias[2 * embed_dim :] ) _lowerCamelCase : Dict = True break elif attribute == "position_embeddings": assert ( model.position_embeddings.weight.shape[-1] == old_model.embed_positions.weight.shape[-1] ), "Hidden size has to match" assert model.position_embeddings.weight.shape[0] == 5_12, "We want 512 position_embeddings." _lowerCamelCase : List[str] = nn.Parameter(old_model.embed_positions.weight[:5_12, :] ) _lowerCamelCase : Optional[Any] = True break if attribute.isdigit(): _lowerCamelCase : Optional[int] = model[int(A_ )] _lowerCamelCase : List[Any] = old_model[int(A_ )] else: _lowerCamelCase : List[str] = getattr(A_, A_ ) if old_attribute == "": _lowerCamelCase : str = old_model else: if not hasattr(A_, A_ ): raise ValueError(F'''{old_model} does not have {old_attribute}''' ) _lowerCamelCase : Optional[int] = getattr(A_, A_ ) if not is_key_init: raise ValueError(F'''{key} was not correctly initialized!''' ) print(F'''Saving model to {pytorch_dump_folder_path}''' ) prophet.save_pretrained(A_ ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--prophetnet_checkpoint_path''', default=None, type=str, required=True, help='''Path the official PyTorch dump.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) lowerCAmelCase__ = parser.parse_args() convert_prophetnet_checkpoint_to_pytorch(args.prophetnet_checkpoint_path, args.pytorch_dump_folder_path)
175
0
import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap UpperCAmelCase_ = 'Usage of script: script_name <size_of_canvas:int>' UpperCAmelCase_ = [0] * 100 + [1] * 10 random.shuffle(choice) def lowerCamelCase__ ( A__ : int ): '''simple docstring''' __lowerCamelCase = [[False for i in range(a_ )] for j in range(a_ )] return canvas def lowerCamelCase__ ( A__ : list[list[bool]] ): '''simple docstring''' for i, row in enumerate(a_ ): for j, _ in enumerate(a_ ): __lowerCamelCase = bool(random.getrandbits(1 ) ) def lowerCamelCase__ ( A__ : list[list[bool]] ): '''simple docstring''' __lowerCamelCase = np.array(a_ ) __lowerCamelCase = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(a_ ): for c, pt in enumerate(a_ ): __lowerCamelCase = __judge_point( a_ , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) __lowerCamelCase = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. __lowerCamelCase = current_canvas.tolist() return return_canvas def lowerCamelCase__ ( A__ : bool , A__ : list[list[bool]] ): '''simple docstring''' __lowerCamelCase = 0 __lowerCamelCase = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. __lowerCamelCase = pt if pt: if alive < 2: __lowerCamelCase = False elif alive == 2 or alive == 3: __lowerCamelCase = True elif alive > 3: __lowerCamelCase = False else: if alive == 3: __lowerCamelCase = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) UpperCAmelCase_ = int(sys.argv[1]) # main working structure of this module. UpperCAmelCase_ = create_canvas(canvas_size) seed(c) UpperCAmelCase_ , UpperCAmelCase_ = plt.subplots() fig.show() UpperCAmelCase_ = ListedColormap(['w', 'k']) try: while True: UpperCAmelCase_ = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
12
'''simple docstring''' from __future__ import annotations __a = list[tuple[int, int]] __a = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] __a = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class A__ : """simple docstring""" def __init__( self : List[Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : float , lowerCAmelCase__ : Node | None , ) -> List[str]: """simple docstring""" _UpperCAmelCase : List[str] = pos_x _UpperCAmelCase : List[Any] = pos_y _UpperCAmelCase : Optional[int] = (pos_y, pos_x) _UpperCAmelCase : Tuple = goal_x _UpperCAmelCase : List[str] = goal_y _UpperCAmelCase : str = g_cost _UpperCAmelCase : List[Any] = parent _UpperCAmelCase : str = self.calculate_heuristic() def _lowerCAmelCase ( self : str ) -> float: """simple docstring""" _UpperCAmelCase : Optional[Any] = abs(self.pos_x - self.goal_x ) _UpperCAmelCase : Optional[Any] = abs(self.pos_y - self.goal_y ) return dx + dy def __lt__( self : Any , lowerCAmelCase__ : Optional[int] ) -> bool: """simple docstring""" return self.f_cost < other.f_cost class A__ : """simple docstring""" def __init__( self : Union[str, Any] , lowerCAmelCase__ : tuple[int, int] , lowerCAmelCase__ : tuple[int, int] ) -> List[str]: """simple docstring""" _UpperCAmelCase : List[Any] = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , lowerCAmelCase__ ) _UpperCAmelCase : Dict = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_9_9_9_9 , lowerCAmelCase__ ) _UpperCAmelCase : Optional[int] = [self.start] _UpperCAmelCase : list[Node] = [] _UpperCAmelCase : List[Any] = False def _lowerCAmelCase ( self : Tuple ) -> Path | None: """simple docstring""" while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() _UpperCAmelCase : Dict = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: _UpperCAmelCase : List[str] = True return self.retrace_path(lowerCAmelCase__ ) self.closed_nodes.append(lowerCAmelCase__ ) _UpperCAmelCase : Union[str, Any] = self.get_successors(lowerCAmelCase__ ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(lowerCAmelCase__ ) else: # retrieve the best current path _UpperCAmelCase : List[Any] = self.open_nodes.pop(self.open_nodes.index(lowerCAmelCase__ ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(lowerCAmelCase__ ) else: self.open_nodes.append(lowerCAmelCase__ ) if not self.reached: return [self.start.pos] return None def _lowerCAmelCase ( self : List[str] , lowerCAmelCase__ : Node ) -> list[Node]: """simple docstring""" _UpperCAmelCase : Union[str, Any] = [] for action in delta: _UpperCAmelCase : Tuple = parent.pos_x + action[1] _UpperCAmelCase : Any = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(lowerCAmelCase__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( lowerCAmelCase__ , lowerCAmelCase__ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , lowerCAmelCase__ , ) ) return successors def _lowerCAmelCase ( self : Any , lowerCAmelCase__ : Node | None ) -> Path: """simple docstring""" _UpperCAmelCase : Optional[int] = node _UpperCAmelCase : Any = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) _UpperCAmelCase : Any = current_node.parent path.reverse() return path if __name__ == "__main__": __a = (0, 0) __a = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print('------') __a = GreedyBestFirst(init, goal) __a = greedy_bf.search() if path: for pos_x, pos_y in path: __a = 2 for elem in grid: print(elem)
145
0
'''simple docstring''' from math import sqrt def __UpperCamelCase ( _UpperCAmelCase ): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(sqrt(_UpperCAmelCase ) + 1 ), 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def __UpperCamelCase ( _UpperCAmelCase = 10001 ): __UpperCAmelCase : Tuple = 0 __UpperCAmelCase : Union[str, Any] = 1 while count != nth and number < 3: number += 1 if is_prime(_UpperCAmelCase ): count += 1 while count != nth: number += 2 if is_prime(_UpperCAmelCase ): count += 1 return number if __name__ == "__main__": print(f"{solution() = }")
37
'''simple docstring''' from datetime import datetime as dt import os from github import Github lowerCAmelCase__ : Union[str, Any] = [ "good first issue", "good second issue", "good difficult issue", "feature request", "new model", "wip", ] def __UpperCamelCase ( ): __UpperCAmelCase : Optional[int] = Github(os.environ["GITHUB_TOKEN"] ) __UpperCAmelCase : Union[str, Any] = g.get_repo("huggingface/transformers" ) __UpperCAmelCase : Union[str, Any] = repo.get_issues(state="open" ) for issue in open_issues: __UpperCAmelCase : int = sorted([comment for comment in issue.get_comments()], key=lambda _UpperCAmelCase : i.created_at, reverse=_UpperCAmelCase ) __UpperCAmelCase : Any = comments[0] if len(_UpperCAmelCase ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") issue.edit(state="closed" ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would add stale comment to {issue.number}") issue.create_comment( "This issue has been automatically marked as stale because it has not had " "recent activity. If you think this still needs to be addressed " "please comment on this thread.\n\nPlease note that issues that do not follow the " "[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) " "are likely to be ignored." ) if __name__ == "__main__": main()
37
1
from __future__ import annotations from random import choice def _lowerCAmelCase (_lowerCAmelCase): return choice(_lowerCAmelCase) def _lowerCAmelCase (_lowerCAmelCase , _lowerCAmelCase): UpperCamelCase_ = random_pivot(_lowerCAmelCase) # partition based on pivot # linear time UpperCamelCase_ = [e for e in lst if e < pivot] UpperCamelCase_ = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(_lowerCAmelCase) == k - 1: return pivot # pivot is in elements bigger than k elif len(_lowerCAmelCase) < k - 1: return kth_number(_lowerCAmelCase , k - len(_lowerCAmelCase) - 1) # pivot is in elements smaller than k else: return kth_number(_lowerCAmelCase , _lowerCAmelCase) if __name__ == "__main__": import doctest doctest.testmod()
128
import unittest from transformers import BertGenerationConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import BertGenerationDecoder, BertGenerationEncoder class _lowercase : '''simple docstring''' def __init__( self , snake_case__ , snake_case__=13 , snake_case__=7 , snake_case__=True , snake_case__=True , snake_case__=99 , snake_case__=32 , snake_case__=5 , snake_case__=4 , snake_case__=37 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=50 , snake_case__=0.02 , snake_case__=True , snake_case__=None , ): '''simple docstring''' UpperCamelCase_ = parent UpperCamelCase_ = batch_size UpperCamelCase_ = seq_length UpperCamelCase_ = is_training UpperCamelCase_ = use_input_mask UpperCamelCase_ = vocab_size UpperCamelCase_ = hidden_size UpperCamelCase_ = num_hidden_layers UpperCamelCase_ = num_attention_heads UpperCamelCase_ = intermediate_size UpperCamelCase_ = hidden_act UpperCamelCase_ = hidden_dropout_prob UpperCamelCase_ = attention_probs_dropout_prob UpperCamelCase_ = max_position_embeddings UpperCamelCase_ = initializer_range UpperCamelCase_ = use_labels UpperCamelCase_ = scope def _lowerCamelCase ( self ): '''simple docstring''' UpperCamelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase_ = None if self.use_input_mask: UpperCamelCase_ = random_attention_mask([self.batch_size, self.seq_length] ) if self.use_labels: UpperCamelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase_ = self.get_config() return config, input_ids, input_mask, token_labels def _lowerCamelCase ( self ): '''simple docstring''' return BertGenerationConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , is_decoder=snake_case__ , initializer_range=self.initializer_range , ) def _lowerCamelCase ( self ): '''simple docstring''' ( ( UpperCamelCase_ ) , ( UpperCamelCase_ ) , ( UpperCamelCase_ ) , ( UpperCamelCase_ ) , ) = self.prepare_config_and_inputs() UpperCamelCase_ = True UpperCamelCase_ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) UpperCamelCase_ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def _lowerCamelCase ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , **snake_case__ , ): '''simple docstring''' UpperCamelCase_ = BertGenerationEncoder(config=snake_case__ ) model.to(snake_case__ ) model.eval() UpperCamelCase_ = model(snake_case__ , attention_mask=snake_case__ ) UpperCamelCase_ = model(snake_case__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCamelCase ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , **snake_case__ , ): '''simple docstring''' UpperCamelCase_ = True UpperCamelCase_ = BertGenerationEncoder(config=snake_case__ ) model.to(snake_case__ ) model.eval() UpperCamelCase_ = model( snake_case__ , attention_mask=snake_case__ , encoder_hidden_states=snake_case__ , encoder_attention_mask=snake_case__ , ) UpperCamelCase_ = model( snake_case__ , attention_mask=snake_case__ , encoder_hidden_states=snake_case__ , ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCamelCase ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , **snake_case__ , ): '''simple docstring''' UpperCamelCase_ = True UpperCamelCase_ = True UpperCamelCase_ = BertGenerationDecoder(config=snake_case__ ).to(snake_case__ ).eval() # first forward pass UpperCamelCase_ = model( snake_case__ , attention_mask=snake_case__ , encoder_hidden_states=snake_case__ , encoder_attention_mask=snake_case__ , use_cache=snake_case__ , ) UpperCamelCase_ = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids UpperCamelCase_ = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCamelCase_ = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and UpperCamelCase_ = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase_ = torch.cat([input_mask, next_mask] , dim=-1 ) UpperCamelCase_ = model( snake_case__ , attention_mask=snake_case__ , encoder_hidden_states=snake_case__ , encoder_attention_mask=snake_case__ , output_hidden_states=snake_case__ , )["hidden_states"][0] UpperCamelCase_ = model( snake_case__ , attention_mask=snake_case__ , encoder_hidden_states=snake_case__ , encoder_attention_mask=snake_case__ , past_key_values=snake_case__ , output_hidden_states=snake_case__ , )["hidden_states"][0] # select random slice UpperCamelCase_ = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase_ = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCamelCase_ = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(snake_case__ , snake_case__ , atol=1e-3 ) ) def _lowerCamelCase ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , *snake_case__ , ): '''simple docstring''' UpperCamelCase_ = BertGenerationDecoder(snake_case__ ) model.to(snake_case__ ) model.eval() UpperCamelCase_ = model(snake_case__ , attention_mask=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _lowerCamelCase ( self ): '''simple docstring''' UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = self.prepare_config_and_inputs() UpperCamelCase_ = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class _lowercase (a_ , a_ , a_ , unittest.TestCase ): '''simple docstring''' lowercase__ = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () lowercase__ = (BertGenerationDecoder,) if is_torch_available() else () lowercase__ = ( {"""feature-extraction""": BertGenerationEncoder, """text-generation""": BertGenerationDecoder} if is_torch_available() else {} ) def _lowerCamelCase ( self ): '''simple docstring''' UpperCamelCase_ = BertGenerationEncoderTester(self ) UpperCamelCase_ = ConfigTester(self , config_class=snake_case__ , hidden_size=37 ) def _lowerCamelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def _lowerCamelCase ( self ): '''simple docstring''' UpperCamelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__ ) def _lowerCamelCase ( self ): '''simple docstring''' UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = self.model_tester.prepare_config_and_inputs() UpperCamelCase_ = "bert" self.model_tester.create_and_check_model(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) def _lowerCamelCase ( self ): '''simple docstring''' UpperCamelCase_ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*snake_case__ ) def _lowerCamelCase ( self ): '''simple docstring''' UpperCamelCase_ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*snake_case__ ) def _lowerCamelCase ( self ): '''simple docstring''' ( ( UpperCamelCase_ ) , ( UpperCamelCase_ ) , ( UpperCamelCase_ ) , ( UpperCamelCase_ ) , ( UpperCamelCase_ ) , ( UpperCamelCase_ ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() UpperCamelCase_ = None self.model_tester.create_and_check_model_as_decoder( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ) def _lowerCamelCase ( self ): '''simple docstring''' UpperCamelCase_ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*snake_case__ ) @slow def _lowerCamelCase ( self ): '''simple docstring''' UpperCamelCase_ = BertGenerationEncoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) self.assertIsNotNone(snake_case__ ) @require_torch class _lowercase (unittest.TestCase ): '''simple docstring''' @slow def _lowerCamelCase ( self ): '''simple docstring''' UpperCamelCase_ = BertGenerationEncoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) UpperCamelCase_ = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 1_0140, 102]] ) with torch.no_grad(): UpperCamelCase_ = model(snake_case__ )[0] UpperCamelCase_ = torch.Size([1, 8, 1024] ) self.assertEqual(output.shape , snake_case__ ) UpperCamelCase_ = torch.tensor( [[[0.1_775, 0.0_083, -0.0_321], [1.6_002, 0.1_287, 0.3_912], [2.1_473, 0.5_791, 0.6_066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case__ , atol=1e-4 ) ) @require_torch class _lowercase (unittest.TestCase ): '''simple docstring''' @slow def _lowerCamelCase ( self ): '''simple docstring''' UpperCamelCase_ = BertGenerationDecoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) UpperCamelCase_ = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 1_0140, 102]] ) with torch.no_grad(): UpperCamelCase_ = model(snake_case__ )[0] UpperCamelCase_ = torch.Size([1, 8, 5_0358] ) self.assertEqual(output.shape , snake_case__ ) UpperCamelCase_ = torch.tensor( [[[-0.5_788, -2.5_994, -3.7_054], [0.0_438, 4.7_997, 1.8_795], [1.5_862, 6.6_409, 4.4_638]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case__ , atol=1e-4 ) )
128
1
"""simple docstring""" import os from typing import BinaryIO, Optional, Union import numpy as np import pyarrow.parquet as pq from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config from ..features.features import FeatureType, _visit from ..formatting import query_table from ..packaged_modules import _PACKAGED_DATASETS_MODULES from ..packaged_modules.parquet.parquet import Parquet from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader def __UpperCAmelCase ( UpperCAmelCase_ : List[str] ) -> Optional[int]: '''simple docstring''' __snake_case : List[Any] = np.inf def set_batch_size(UpperCAmelCase_ : List[Any] ) -> None: nonlocal batch_size if isinstance(_UpperCAmelCase , _UpperCAmelCase ): __snake_case : Any = min(_UpperCAmelCase , config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS ) elif isinstance(_UpperCAmelCase , _UpperCAmelCase ): __snake_case : Dict = min(_UpperCAmelCase , config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS ) elif isinstance(_UpperCAmelCase , _UpperCAmelCase ) and feature.dtype == "binary": __snake_case : int = min(_UpperCAmelCase , config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS ) _visit(_UpperCAmelCase , _UpperCAmelCase ) return None if batch_size is np.inf else batch_size class UpperCamelCase ( SCREAMING_SNAKE_CASE__ ): def __init__(self : Union[str, Any] , _A : NestedDataStructureLike[PathLike] , _A : Optional[NamedSplit] = None , _A : Optional[Features] = None , _A : str = None , _A : bool = False , _A : bool = False , _A : Optional[int] = None , **_A : int , ) -> List[Any]: super().__init__( _A , split=_A , features=_A , cache_dir=_A , keep_in_memory=_A , streaming=_A , num_proc=_A , **_A , ) __snake_case : str = path_or_paths if isinstance(_A , _A) else {self.split: path_or_paths} __snake_case : Tuple = _PACKAGED_DATASETS_MODULES['parquet'][1] __snake_case : Optional[int] = Parquet( cache_dir=_A , data_files=_A , features=_A , hash=_A , **_A , ) def _lowercase (self : Optional[int]) -> Union[str, Any]: # Build iterable dataset if self.streaming: __snake_case : Union[str, Any] = self.builder.as_streaming_dataset(split=self.split) # Build regular (map-style) dataset else: __snake_case : Tuple = None __snake_case : Union[str, Any] = None __snake_case : List[Any] = None __snake_case : int = None self.builder.download_and_prepare( download_config=_A , download_mode=_A , verification_mode=_A , base_path=_A , num_proc=self.num_proc , ) __snake_case : Any = self.builder.as_dataset( split=self.split , verification_mode=_A , in_memory=self.keep_in_memory) return dataset class UpperCamelCase : def __init__(self : Dict , _A : Dataset , _A : Union[PathLike, BinaryIO] , _A : Optional[int] = None , **_A : Optional[Any] , ) -> Optional[Any]: __snake_case : List[Any] = dataset __snake_case : int = path_or_buf __snake_case : Optional[Any] = batch_size or get_writer_batch_size(dataset.features) __snake_case : Optional[Any] = parquet_writer_kwargs def _lowercase (self : Union[str, Any]) -> int: __snake_case : Union[str, Any] = self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE if isinstance(self.path_or_buf , (str, bytes, os.PathLike)): with open(self.path_or_buf , 'wb+') as buffer: __snake_case : int = self._write(file_obj=_A , batch_size=_A , **self.parquet_writer_kwargs) else: __snake_case : List[Any] = self._write(file_obj=self.path_or_buf , batch_size=_A , **self.parquet_writer_kwargs) return written def _lowercase (self : int , _A : BinaryIO , _A : int , **_A : Union[str, Any]) -> int: __snake_case : Optional[Any] = 0 __snake_case : int = parquet_writer_kwargs.pop('path_or_buf' , _A) __snake_case : List[str] = self.dataset.features.arrow_schema __snake_case : int = pq.ParquetWriter(_A , schema=_A , **_A) for offset in logging.tqdm( range(0 , len(self.dataset) , _A) , unit='ba' , disable=not logging.is_progress_bar_enabled() , desc='Creating parquet from Arrow format' , ): __snake_case : Tuple = query_table( table=self.dataset._data , key=slice(_A , offset + batch_size) , indices=self.dataset._indices if self.dataset._indices is not None else None , ) writer.write_table(_A) written += batch.nbytes writer.close() return written
359
"""simple docstring""" def __UpperCAmelCase ( UpperCAmelCase_ : int , UpperCAmelCase_ : int ) -> int: '''simple docstring''' while a != 0: __snake_case , __snake_case : Union[str, Any] = b % a, a return b def __UpperCAmelCase ( UpperCAmelCase_ : int , UpperCAmelCase_ : int ) -> int: '''simple docstring''' if gcd(UpperCAmelCase_ , UpperCAmelCase_ ) != 1: __snake_case : Union[str, Any] = F"mod inverse of {a!r} and {m!r} does not exist" raise ValueError(UpperCAmelCase_ ) __snake_case , __snake_case , __snake_case : List[str] = 1, 0, a __snake_case , __snake_case , __snake_case : Dict = 0, 1, m while va != 0: __snake_case : List[str] = ua // va __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case : List[str] = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va return ua % m
95
0
import numpy as np def __lowercase ( _A ) -> np.array: return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
245
import argparse import glob import logging import os from argparse import Namespace from importlib import import_module import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch.nn import CrossEntropyLoss from torch.utils.data import DataLoader, TensorDataset from utils_ner import TokenClassificationTask UpperCAmelCase__ : Tuple = logging.getLogger(__name__) class a__ ( UpperCAmelCase ): """simple docstring""" UpperCAmelCase__ : List[str] ="""token-classification""" def __init__( self : Tuple , UpperCAmelCase__ : Tuple ) ->Optional[Any]: """simple docstring""" if type(UpperCAmelCase__ ) == dict: SCREAMING_SNAKE_CASE : List[str] = Namespace(**UpperCAmelCase__ ) SCREAMING_SNAKE_CASE : List[str] = import_module("""tasks""" ) try: SCREAMING_SNAKE_CASE : str = getattr(UpperCAmelCase__ , hparams.task_type ) SCREAMING_SNAKE_CASE : TokenClassificationTask = token_classification_task_clazz() except AttributeError: raise ValueError( f"Task {hparams.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. " f"Available tasks classes are: {TokenClassificationTask.__subclasses__()}" ) SCREAMING_SNAKE_CASE : List[Any] = self.token_classification_task.get_labels(hparams.labels ) SCREAMING_SNAKE_CASE : List[Any] = CrossEntropyLoss().ignore_index super().__init__(UpperCAmelCase__ , len(self.labels ) , self.mode ) def _lowercase ( self : List[str] , **UpperCAmelCase__ : Optional[int] ) ->Any: """simple docstring""" return self.model(**UpperCAmelCase__ ) def _lowercase ( self : List[str] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str ) ->List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type != "distilbert": SCREAMING_SNAKE_CASE : List[str] = ( batch[2] if self.config.model_type in ["""bert""", """xlnet"""] else None ) # XLM and RoBERTa don"t use token_type_ids SCREAMING_SNAKE_CASE : Union[str, Any] = self(**UpperCAmelCase__ ) SCREAMING_SNAKE_CASE : int = outputs[0] # tensorboard_logs = {"loss": loss, "rate": self.lr_scheduler.get_last_lr()[-1]} return {"loss": loss} def _lowercase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = self.hparams for mode in ["train", "dev", "test"]: SCREAMING_SNAKE_CASE : Any = self._feature_file(UpperCAmelCase__ ) if os.path.exists(UpperCAmelCase__ ) and not args.overwrite_cache: logger.info("""Loading features from cached file %s""" , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE : Tuple = torch.load(UpperCAmelCase__ ) else: logger.info("""Creating features from dataset file at %s""" , args.data_dir ) SCREAMING_SNAKE_CASE : Optional[int] = self.token_classification_task.read_examples_from_file(args.data_dir , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE : List[str] = self.token_classification_task.convert_examples_to_features( UpperCAmelCase__ , self.labels , args.max_seq_length , self.tokenizer , cls_token_at_end=bool(self.config.model_type in ["""xlnet"""] ) , cls_token=self.tokenizer.cls_token , cls_token_segment_id=2 if self.config.model_type in ["""xlnet"""] else 0 , sep_token=self.tokenizer.sep_token , sep_token_extra=UpperCAmelCase__ , pad_on_left=bool(self.config.model_type in ["""xlnet"""] ) , pad_token=self.tokenizer.pad_token_id , pad_token_segment_id=self.tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info("""Saving features into cached file %s""" , UpperCAmelCase__ ) torch.save(UpperCAmelCase__ , UpperCAmelCase__ ) def _lowercase ( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : bool = False ) ->DataLoader: """simple docstring""" SCREAMING_SNAKE_CASE : Any = self._feature_file(UpperCAmelCase__ ) logger.info("""Loading features from cached file %s""" , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = torch.load(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([f.input_ids for f in features] , dtype=torch.long ) SCREAMING_SNAKE_CASE : int = torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) if features[0].token_type_ids is not None: SCREAMING_SNAKE_CASE : Any = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) else: SCREAMING_SNAKE_CASE : Tuple = torch.tensor([0 for f in features] , dtype=torch.long ) # HACK(we will not use this anymore soon) SCREAMING_SNAKE_CASE : Dict = torch.tensor([f.label_ids for f in features] , dtype=torch.long ) return DataLoader( TensorDataset(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) , batch_size=UpperCAmelCase__ ) def _lowercase ( self : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ) ->Tuple: """simple docstring""" """Compute validation""" "" SCREAMING_SNAKE_CASE : Tuple = {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type != "distilbert": SCREAMING_SNAKE_CASE : str = ( batch[2] if self.config.model_type in ["""bert""", """xlnet"""] else None ) # XLM and RoBERTa don"t use token_type_ids SCREAMING_SNAKE_CASE : Dict = self(**UpperCAmelCase__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = outputs[:2] SCREAMING_SNAKE_CASE : Optional[Any] = logits.detach().cpu().numpy() SCREAMING_SNAKE_CASE : Tuple = inputs["""labels"""].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def _lowercase ( self : int , UpperCAmelCase__ : List[str] ) ->Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = torch.stack([x["""val_loss"""] for x in outputs] ).mean() SCREAMING_SNAKE_CASE : str = np.concatenate([x["""pred"""] for x in outputs] , axis=0 ) SCREAMING_SNAKE_CASE : Tuple = np.argmax(UpperCAmelCase__ , axis=2 ) SCREAMING_SNAKE_CASE : Optional[Any] = np.concatenate([x["""target"""] for x in outputs] , axis=0 ) SCREAMING_SNAKE_CASE : Union[str, Any] = dict(enumerate(self.labels ) ) SCREAMING_SNAKE_CASE : int = [[] for _ in range(out_label_ids.shape[0] )] SCREAMING_SNAKE_CASE : Optional[int] = [[] for _ in range(out_label_ids.shape[0] )] for i in range(out_label_ids.shape[0] ): for j in range(out_label_ids.shape[1] ): if out_label_ids[i, j] != self.pad_token_label_id: out_label_list[i].append(label_map[out_label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) SCREAMING_SNAKE_CASE : Tuple = { """val_loss""": val_loss_mean, """accuracy_score""": accuracy_score(UpperCAmelCase__ , UpperCAmelCase__ ), """precision""": precision_score(UpperCAmelCase__ , UpperCAmelCase__ ), """recall""": recall_score(UpperCAmelCase__ , UpperCAmelCase__ ), """f1""": fa_score(UpperCAmelCase__ , UpperCAmelCase__ ), } SCREAMING_SNAKE_CASE : Optional[int] = dict(results.items() ) SCREAMING_SNAKE_CASE : Optional[Any] = results return ret, preds_list, out_label_list def _lowercase ( self : Dict , UpperCAmelCase__ : Union[str, Any] ) ->Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self._eval_end(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE : Optional[int] = ret["""log"""] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def _lowercase ( self : List[str] , UpperCAmelCase__ : Union[str, Any] ) ->Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = self._eval_end(UpperCAmelCase__ ) # Converting to the dict required by pl # https://github.com/PyTorchLightning/pytorch-lightning/blob/master/\ # pytorch_lightning/trainer/logging.py#L139 SCREAMING_SNAKE_CASE : Dict = ret["""log"""] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def _lowercase ( UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int ) ->List[Any]: """simple docstring""" BaseTransformer.add_model_specific_args(UpperCAmelCase__ , UpperCAmelCase__ ) parser.add_argument( """--task_type""" , default="""NER""" , type=UpperCAmelCase__ , help="""Task type to fine tune in training (e.g. NER, POS, etc)""" ) parser.add_argument( """--max_seq_length""" , default=1_2_8 , type=UpperCAmelCase__ , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--labels""" , default="""""" , type=UpperCAmelCase__ , help="""Path to a file containing all labels. If not specified, CoNLL-2003 labels are used.""" , ) parser.add_argument( """--gpus""" , default=0 , type=UpperCAmelCase__ , help="""The number of GPUs allocated for this, it is by default 0 meaning none""" , ) parser.add_argument( """--overwrite_cache""" , action="""store_true""" , help="""Overwrite the cached training and evaluation sets""" ) return parser if __name__ == "__main__": UpperCAmelCase__ : str = argparse.ArgumentParser() add_generic_args(parser, os.getcwd()) UpperCAmelCase__ : Tuple = NERTransformer.add_model_specific_args(parser, os.getcwd()) UpperCAmelCase__ : int = parser.parse_args() UpperCAmelCase__ : Union[str, Any] = NERTransformer(args) UpperCAmelCase__ : str = generic_train(model, args) if args.do_predict: # See https://github.com/huggingface/transformers/issues/3159 # pl use this default format to create a checkpoint: # https://github.com/PyTorchLightning/pytorch-lightning/blob/master\ # /pytorch_lightning/callbacks/model_checkpoint.py#L322 UpperCAmelCase__ : Union[str, Any] = sorted(glob.glob(os.path.join(args.output_dir, """checkpoint-epoch=*.ckpt"""), recursive=True)) UpperCAmelCase__ : Any = model.load_from_checkpoint(checkpoints[-1]) trainer.test(model)
245
1
from __future__ import annotations lowerCAmelCase__ : List[Any] =[-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] lowerCAmelCase__ : Dict =[-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def a__ ( A__ ): SCREAMING_SNAKE_CASE_ : str = [] SCREAMING_SNAKE_CASE_ : int = len(A__ ) for i in range(A__ ): SCREAMING_SNAKE_CASE_ : float = -1 for j in range(i + 1, A__ ): if arr[i] < arr[j]: SCREAMING_SNAKE_CASE_ : Optional[int] = arr[j] break result.append(A__ ) return result def a__ ( A__ ): SCREAMING_SNAKE_CASE_ : str = [] for i, outer in enumerate(A__ ): SCREAMING_SNAKE_CASE_ : float = -1 for inner in arr[i + 1 :]: if outer < inner: SCREAMING_SNAKE_CASE_ : List[Any] = inner break result.append(A__ ) return result def a__ ( A__ ): SCREAMING_SNAKE_CASE_ : Optional[int] = len(A__ ) SCREAMING_SNAKE_CASE_ : list[float] = [] SCREAMING_SNAKE_CASE_ : list[float] = [-1] * arr_size for index in reversed(range(A__ ) ): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: SCREAMING_SNAKE_CASE_ : Any = stack[-1] stack.append(arr[index] ) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) lowerCAmelCase__ : Optional[Any] =( 'from __main__ import arr, next_greatest_element_slow, ' 'next_greatest_element_fast, next_greatest_element' ) print( 'next_greatest_element_slow():', timeit('next_greatest_element_slow(arr)', setup=setup), ) print( 'next_greatest_element_fast():', timeit('next_greatest_element_fast(arr)', setup=setup), ) print( ' next_greatest_element():', timeit('next_greatest_element(arr)', setup=setup), )
370
import numpy # List of input, output pairs lowerCAmelCase__ : int =( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) lowerCAmelCase__ : Any =(((5_15, 22, 13), 5_55), ((61, 35, 49), 1_50)) lowerCAmelCase__ : List[str] =[2, 4, 1, 5] lowerCAmelCase__ : Dict =len(train_data) lowerCAmelCase__ : Union[str, Any] =0.0_0_9 def a__ ( A__, A__="train" ): return calculate_hypothesis_value(A__, A__ ) - output( A__, A__ ) def a__ ( A__ ): SCREAMING_SNAKE_CASE_ : Tuple = 0 for i in range(len(A__ ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def a__ ( A__, A__ ): if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def a__ ( A__, A__ ): if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def a__ ( A__, A__=m ): SCREAMING_SNAKE_CASE_ : Tuple = 0 for i in range(A__ ): if index == -1: summation_value += _error(A__ ) else: summation_value += _error(A__ ) * train_data[i][0][index] return summation_value def a__ ( A__ ): SCREAMING_SNAKE_CASE_ : Any = summation_of_cost_derivative(A__, A__ ) / m return cost_derivative_value def a__ ( ): global parameter_vector # Tune these values to set a tolerance value for predicted output SCREAMING_SNAKE_CASE_ : str = 0.00_00_02 SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ : Any = 0 while True: j += 1 SCREAMING_SNAKE_CASE_ : int = [0, 0, 0, 0] for i in range(0, len(A__ ) ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_cost_derivative(i - 1 ) SCREAMING_SNAKE_CASE_ : str = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( A__, A__, atol=A__, rtol=A__, ): break SCREAMING_SNAKE_CASE_ : Optional[Any] = temp_parameter_vector print(('Number of iterations:', j) ) def a__ ( ): for i in range(len(A__ ) ): print(('Actual output value:', output(A__, 'test' )) ) print(('Hypothesis output:', calculate_hypothesis_value(A__, 'test' )) ) if __name__ == "__main__": run_gradient_descent() print('\nTesting gradient descent for a linear hypothesis function.\n') test_gradient_descent()
162
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _SCREAMING_SNAKE_CASE = { """configuration_efficientformer""": [ """EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """EfficientFormerConfig""", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = ["""EfficientFormerImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = [ """EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """EfficientFormerForImageClassification""", """EfficientFormerForImageClassificationWithTeacher""", """EfficientFormerModel""", """EfficientFormerPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = [ """TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFEfficientFormerForImageClassification""", """TFEfficientFormerForImageClassificationWithTeacher""", """TFEfficientFormerModel""", """TFEfficientFormerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_efficientformer import EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientformer import EfficientFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientformer import ( EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientFormerForImageClassification, EfficientFormerForImageClassificationWithTeacher, EfficientFormerModel, EfficientFormerPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, TFEfficientFormerPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
343
import json import os import unittest from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES, XLMTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class _lowercase ( snake_case_ , unittest.TestCase ): lowercase = XLMTokenizer lowercase = False def SCREAMING_SNAKE_CASE__ ( self : Any ) -> List[Any]: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCamelCase_ : List[Any] = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'w</w>', 'r</w>', 't</w>', 'lo', 'low', 'er</w>', 'low</w>', 'lowest</w>', 'newer</w>', 'wider</w>', '<unk>', ] UpperCamelCase_ : str = dict(zip(snake_case , range(len(snake_case ) ) ) ) UpperCamelCase_ : Tuple = ['l o 123', 'lo w 1456', 'e r</w> 1789', ''] UpperCamelCase_ : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) UpperCamelCase_ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' ) as fp: fp.write(json.dumps(snake_case ) ) with open(self.merges_file , 'w' ) as fp: fp.write('\n'.join(snake_case ) ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , snake_case : Union[str, Any] ) -> int: """simple docstring""" UpperCamelCase_ : Tuple = 'lower newer' UpperCamelCase_ : Optional[int] = 'lower newer' return input_text, output_text def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Tuple: """simple docstring""" UpperCamelCase_ : int = XLMTokenizer(self.vocab_file , self.merges_file ) UpperCamelCase_ : List[str] = 'lower' UpperCamelCase_ : Optional[int] = ['low', 'er</w>'] UpperCamelCase_ : Optional[Any] = tokenizer.tokenize(snake_case ) self.assertListEqual(snake_case , snake_case ) UpperCamelCase_ : List[Any] = tokens + ['<unk>'] UpperCamelCase_ : int = [1_4, 1_5, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case ) , snake_case ) @slow def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ : int = XLMTokenizer.from_pretrained('xlm-mlm-en-2048' ) UpperCamelCase_ : int = tokenizer.encode('sequence builders' , add_special_tokens=snake_case ) UpperCamelCase_ : Optional[int] = tokenizer.encode('multi-sequence build' , add_special_tokens=snake_case ) UpperCamelCase_ : Tuple = tokenizer.build_inputs_with_special_tokens(snake_case ) UpperCamelCase_ : Any = tokenizer.build_inputs_with_special_tokens(snake_case , snake_case ) assert encoded_sentence == [0] + text + [1] assert encoded_pair == [0] + text + [1] + text_a + [1]
175
0
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. __A = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. __A = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. __A = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1000)) def __A ( _lowercase , _lowercase ): '''simple docstring''' _A = len([g for position, g in enumerate(_lowercase ) if g == main_target[position]] ) return (item, float(_lowercase )) def __A ( _lowercase , _lowercase ): '''simple docstring''' _A = random.randint(0 , len(_lowercase ) - 1 ) _A = parent_a[:random_slice] + parent_a[random_slice:] _A = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def __A ( _lowercase , _lowercase ): '''simple docstring''' _A = list(_lowercase ) if random.uniform(0 , 1 ) < MUTATION_PROBABILITY: _A = random.choice(_lowercase ) return "".join(_lowercase ) def __A ( _lowercase , _lowercase , _lowercase , ): '''simple docstring''' _A = [] # Generate more children proportionally to the fitness score. _A = int(parent_a[1] * 1_00 ) + 1 _A = 10 if child_n >= 10 else child_n for _ in range(_lowercase ): _A = population_score[random.randint(0 , _lowercase )][0] _A ,_A = crossover(parent_a[0] , _lowercase ) # Append new string to the population list. pop.append(mutate(_lowercase , _lowercase ) ) pop.append(mutate(_lowercase , _lowercase ) ) return pop def __A ( _lowercase , _lowercase , _lowercase = True ): '''simple docstring''' if N_POPULATION < N_SELECTED: _A = f"""{N_POPULATION} must be bigger than {N_SELECTED}""" raise ValueError(_lowercase ) # Verify that the target contains no genes besides the ones inside genes variable. _A = sorted({c for c in target if c not in genes} ) if not_in_genes_list: _A = f"""{not_in_genes_list} is not in genes list, evolution cannot converge""" raise ValueError(_lowercase ) # Generate random starting population. _A = [] for _ in range(_lowercase ): population.append(''''''.join([random.choice(_lowercase ) for i in range(len(_lowercase ) )] ) ) # Just some logs to know what the algorithms is doing. _A ,_A = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(_lowercase ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. _A = [evaluate(_lowercase , _lowercase ) for item in population] # Check if there is a matching evolution. _A = sorted(_lowercase , key=lambda _lowercase : x[1] , reverse=_lowercase ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( f"""\nGeneration: {generation}""" f"""\nTotal Population:{total_population}""" f"""\nBest score: {population_score[0][1]}""" f"""\nBest string: {population_score[0][0]}""" ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. _A = population[: int(N_POPULATION / 3 )] population.clear() population.extend(_lowercase ) # Normalize population score to be between 0 and 1. _A = [ (item, score / len(_lowercase )) for item, score in population_score ] # This is selection for i in range(_lowercase ): population.extend(select(population_score[int(_lowercase )] , _lowercase , _lowercase ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(_lowercase ) > N_POPULATION: break if __name__ == "__main__": __A = ( 'This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!' ) __A = list( ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm' 'nopqrstuvwxyz.,;!?+-*#@^\'èéòà€ù=)(&%$£/\\' ) __A , __A , __A = basic(target_str, genes_list) print( f'\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}' )
75
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def __A ( _lowercase ): '''simple docstring''' _A = [2, 2, 6, 2] if '''tiny''' in model_name else [2, 2, 18, 2] _A = True if '''large''' in model_name or '''huge''' in model_name else False _A = True if '''large''' in model_name or '''huge''' in model_name else False _A = True if '''large''' in model_name or '''huge''' in model_name else False if "large" in model_name or "xlarge" in model_name or "huge" in model_name: if "fl3" in model_name: _A = [3, 3, 3, 3] _A = [5, 5, 5, 5] elif "fl4" in model_name: _A = [4, 4, 4, 4] _A = [3, 3, 3, 3] if "tiny" in model_name or "small" in model_name or "base" in model_name: _A = [3, 3, 3, 3] if "lrf" in model_name: _A = [3, 3, 3, 3] else: _A = [2, 2, 2, 2] if "tiny" in model_name: _A = 96 elif "small" in model_name: _A = 96 elif "base" in model_name: _A = 1_28 elif "large" in model_name: _A = 1_92 elif "xlarge" in model_name: _A = 2_56 elif "huge" in model_name: _A = 3_52 # set label information _A = '''huggingface/label-files''' if "large" in model_name or "huge" in model_name: _A = '''imagenet-22k-id2label.json''' else: _A = '''imagenet-1k-id2label.json''' _A = json.load(open(hf_hub_download(_lowercase , _lowercase , repo_type='''dataset''' ) , '''r''' ) ) _A = {int(_lowercase ): v for k, v in idalabel.items()} _A = {v: k for k, v in idalabel.items()} _A = FocalNetConfig( embed_dim=_lowercase , depths=_lowercase , focal_levels=_lowercase , focal_windows=_lowercase , use_conv_embed=_lowercase , idalabel=_lowercase , labelaid=_lowercase , use_post_layernorm=_lowercase , use_layerscale=_lowercase , ) return config def __A ( _lowercase ): '''simple docstring''' if "patch_embed.proj" in name: _A = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: _A = name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: _A = '''encoder.''' + name if "encoder.layers" in name: _A = name.replace('''encoder.layers''' , '''encoder.stages''' ) if "downsample.proj" in name: _A = name.replace('''downsample.proj''' , '''downsample.projection''' ) if "blocks" in name: _A = name.replace('''blocks''' , '''layers''' ) if "modulation.f.weight" in name or "modulation.f.bias" in name: _A = name.replace('''modulation.f''' , '''modulation.projection_in''' ) if "modulation.h.weight" in name or "modulation.h.bias" in name: _A = name.replace('''modulation.h''' , '''modulation.projection_context''' ) if "modulation.proj.weight" in name or "modulation.proj.bias" in name: _A = name.replace('''modulation.proj''' , '''modulation.projection_out''' ) if name == "norm.weight": _A = '''layernorm.weight''' if name == "norm.bias": _A = '''layernorm.bias''' if "head" in name: _A = name.replace('''head''' , '''classifier''' ) else: _A = '''focalnet.''' + name return name def __A ( _lowercase , _lowercase , _lowercase=False ): '''simple docstring''' _A = { '''focalnet-tiny''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth''', '''focalnet-tiny-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth''', '''focalnet-small''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth''', '''focalnet-small-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth''', '''focalnet-base''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth''', '''focalnet-base-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth''', '''focalnet-large-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth''', '''focalnet-large-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth''', '''focalnet-xlarge-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth''', '''focalnet-xlarge-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth''', } # fmt: on _A = model_name_to_url[model_name] print('''Checkpoint URL: ''' , _lowercase ) _A = torch.hub.load_state_dict_from_url(_lowercase , map_location='''cpu''' )['''model'''] # rename keys for key in state_dict.copy().keys(): _A = state_dict.pop(_lowercase ) _A = val _A = get_focalnet_config(_lowercase ) _A = FocalNetForImageClassification(_lowercase ) model.eval() # load state dict model.load_state_dict(_lowercase ) # verify conversion _A = '''http://images.cocodataset.org/val2017/000000039769.jpg''' _A = BitImageProcessor( do_resize=_lowercase , size={'''shortest_edge''': 2_56} , resample=PILImageResampling.BILINEAR , do_center_crop=_lowercase , crop_size=2_24 , do_normalize=_lowercase , image_mean=_lowercase , image_std=_lowercase , ) _A = Image.open(requests.get(_lowercase , stream=_lowercase ).raw ) _A = processor(images=_lowercase , return_tensors='''pt''' ) _A = transforms.Compose( [ transforms.Resize(2_56 ), transforms.CenterCrop(2_24 ), transforms.ToTensor(), transforms.Normalize(mean=[0.4_85, 0.4_56, 0.4_06] , std=[0.2_29, 0.2_24, 0.2_25] ), ] ) _A = image_transforms(_lowercase ).unsqueeze(0 ) # verify pixel_values assert torch.allclose(inputs.pixel_values , _lowercase , atol=1e-4 ) _A = model(**_lowercase ) _A = outputs.logits.argmax(-1 ).item() print('''Predicted class:''' , model.config.idalabel[predicted_class_idx] ) print('''First values of logits:''' , outputs.logits[0, :3] ) if model_name == "focalnet-tiny": _A = torch.tensor([0.21_66, -0.43_68, 0.21_91] ) elif model_name == "focalnet-tiny-lrf": _A = torch.tensor([1.16_69, 0.01_25, -0.16_95] ) elif model_name == "focalnet-small": _A = torch.tensor([0.49_17, -0.04_30, 0.13_41] ) elif model_name == "focalnet-small-lrf": _A = torch.tensor([-0.25_88, -0.53_42, -0.23_31] ) elif model_name == "focalnet-base": _A = torch.tensor([-0.16_55, -0.40_90, -0.17_30] ) elif model_name == "focalnet-base-lrf": _A = torch.tensor([0.53_06, -0.04_83, -0.39_28] ) assert torch.allclose(outputs.logits[0, :3] , _lowercase , atol=1e-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(f"""Saving model and processor of {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_lowercase ) processor.save_pretrained(_lowercase ) if push_to_hub: print(f"""Pushing model and processor of {model_name} to the hub...""" ) model.push_to_hub(f"""{model_name}""" ) processor.push_to_hub(f"""{model_name}""" ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='focalnet-tiny', type=str, help='Name of the FocalNet 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 and processor to the hub.', ) __A = parser.parse_args() convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
75
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = { '''microsoft/focalnet-tiny''': '''https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json''', } class lowerCAmelCase_( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): '''simple docstring''' __lowercase : Optional[Any] = '''focalnet''' def __init__( self ,__UpperCAmelCase=224 ,__UpperCAmelCase=4 ,__UpperCAmelCase=3 ,__UpperCAmelCase=96 ,__UpperCAmelCase=False ,__UpperCAmelCase=[192, 384, 768, 768] ,__UpperCAmelCase=[2, 2, 6, 2] ,__UpperCAmelCase=[2, 2, 2, 2] ,__UpperCAmelCase=[3, 3, 3, 3] ,__UpperCAmelCase="gelu" ,__UpperCAmelCase=4.0 ,__UpperCAmelCase=0.0 ,__UpperCAmelCase=0.1 ,__UpperCAmelCase=False ,__UpperCAmelCase=1E-4 ,__UpperCAmelCase=False ,__UpperCAmelCase=False ,__UpperCAmelCase=False ,__UpperCAmelCase=0.0_2 ,__UpperCAmelCase=1E-5 ,__UpperCAmelCase=32 ,__UpperCAmelCase=None ,__UpperCAmelCase=None ,**__UpperCAmelCase ,) -> Optional[Any]: super().__init__(**__UpperCAmelCase ) lowerCAmelCase__ : Dict = image_size lowerCAmelCase__ : int = patch_size lowerCAmelCase__ : str = num_channels lowerCAmelCase__ : Dict = embed_dim lowerCAmelCase__ : List[str] = use_conv_embed lowerCAmelCase__ : List[Any] = hidden_sizes lowerCAmelCase__ : Dict = depths lowerCAmelCase__ : List[str] = focal_levels lowerCAmelCase__ : List[str] = focal_windows lowerCAmelCase__ : Dict = hidden_act lowerCAmelCase__ : Dict = mlp_ratio lowerCAmelCase__ : Tuple = hidden_dropout_prob lowerCAmelCase__ : Tuple = drop_path_rate lowerCAmelCase__ : Dict = use_layerscale lowerCAmelCase__ : Optional[Any] = layerscale_value lowerCAmelCase__ : str = use_post_layernorm lowerCAmelCase__ : Union[str, Any] = use_post_layernorm_in_modulation lowerCAmelCase__ : int = normalize_modulator lowerCAmelCase__ : Optional[Any] = initializer_range lowerCAmelCase__ : List[str] = layer_norm_eps lowerCAmelCase__ : List[Any] = encoder_stride lowerCAmelCase__ : Dict = ["""stem"""] + [F"""stage{idx}""" for idx in range(1 ,len(self.depths ) + 1 )] lowerCAmelCase__ , lowerCAmelCase__ : Any = get_aligned_output_features_output_indices( out_features=__UpperCAmelCase ,out_indices=__UpperCAmelCase ,stage_names=self.stage_names )
37
'''simple docstring''' from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record _lowerCAmelCase = '''\ @article{wang2019superglue, title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems}, author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R}, journal={arXiv preprint arXiv:1905.00537}, year={2019} } ''' _lowerCAmelCase = '''\ SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after GLUE with a new set of more difficult language understanding tasks, improved resources, and a new public leaderboard. ''' _lowerCAmelCase = ''' Compute SuperGLUE evaluation metric associated to each SuperGLUE dataset. Args: predictions: list of predictions to score. Depending on the SuperGlUE subset: - for \'record\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'prediction_text\': the predicted answer text - for \'multirc\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question-answer pair as specified by the dataset - \'prediction\': the predicted answer label - otherwise: list of predicted labels references: list of reference labels. Depending on the SuperGLUE subset: - for \'record\': list of question-answers dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'answers\': list of possible answers - otherwise: list of reference labels Returns: depending on the SuperGLUE subset: - for \'record\': - \'exact_match\': Exact match between answer and gold answer - \'f1\': F1 score - for \'multirc\': - \'exact_match\': Exact match between answer and gold answer - \'f1_m\': Per-question macro-F1 score - \'f1_a\': Average F1 score over all answers - for \'axb\': \'matthews_correlation\': Matthew Correlation - for \'cb\': - \'accuracy\': Accuracy - \'f1\': F1 score - for all others: - \'accuracy\': Accuracy Examples: >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"] >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\') >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\') >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}] >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\') >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'matthews_correlation\': 1.0} ''' def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase ): """simple docstring""" return float((preds == labels).mean() ) def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase="binary" ): """simple docstring""" lowerCAmelCase__ : Any = simple_accuracy(UpperCamelCase , UpperCamelCase ) lowerCAmelCase__ : Tuple = float(fa_score(y_true=UpperCamelCase , y_pred=UpperCamelCase , average=UpperCamelCase ) ) return { "accuracy": acc, "f1": fa, } def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : List[str] = {} for id_pred, label in zip(UpperCamelCase , UpperCamelCase ): lowerCAmelCase__ : str = f"""{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}""" lowerCAmelCase__ : Dict = id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: lowerCAmelCase__ : Optional[int] = [(pred, label)] lowerCAmelCase__ , lowerCAmelCase__ : int = [], [] for question, preds_labels in question_map.items(): lowerCAmelCase__ , lowerCAmelCase__ : Optional[int] = zip(*UpperCamelCase ) lowerCAmelCase__ : List[Any] = fa_score(y_true=UpperCamelCase , y_pred=UpperCamelCase , average="""macro""" ) fas.append(UpperCamelCase ) lowerCAmelCase__ : Union[str, Any] = int(sum(pred == label for pred, label in preds_labels ) == len(UpperCamelCase ) ) ems.append(UpperCamelCase ) lowerCAmelCase__ : Optional[Any] = float(sum(UpperCamelCase ) / len(UpperCamelCase ) ) lowerCAmelCase__ : List[Any] = sum(UpperCamelCase ) / len(UpperCamelCase ) lowerCAmelCase__ : Dict = float(fa_score(y_true=UpperCamelCase , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase_( datasets.Metric ): '''simple docstring''' def UpperCAmelCase_ ( self ) -> Optional[Any]: if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" ) return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features(self._get_feature_types() ) ,codebase_urls=[] ,reference_urls=[] ,format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None ,) def UpperCAmelCase_ ( self ) -> str: if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "prediction_text": datasets.Value("""string""" ), }, "references": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "answers": datasets.Sequence(datasets.Value("""string""" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64""" ), "paragraph": datasets.Value("""int64""" ), "question": datasets.Value("""int64""" ), }, "prediction": datasets.Value("""int64""" ), }, "references": datasets.Value("""int64""" ), } else: return { "predictions": datasets.Value("""int64""" ), "references": datasets.Value("""int64""" ), } def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ) -> Any: if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(__UpperCAmelCase ,__UpperCAmelCase )} elif self.config_name == "cb": return acc_and_fa(__UpperCAmelCase ,__UpperCAmelCase ,fa_avg="""macro""" ) elif self.config_name == "record": lowerCAmelCase__ : Optional[Any] = [ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] lowerCAmelCase__ : Union[str, Any] = {pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(__UpperCAmelCase ,__UpperCAmelCase )[0] elif self.config_name == "multirc": return evaluate_multirc(__UpperCAmelCase ,__UpperCAmelCase ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(__UpperCAmelCase ,__UpperCAmelCase )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" )
37
1
"""simple docstring""" import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests a = open # noqa: we just need to have a builtin inside this module to test it properly
352
"""simple docstring""" import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class lowercase_ ( unittest.TestCase ): '''simple docstring''' UpperCAmelCase : str = inspect.getfile(accelerate.test_utils ) UpperCAmelCase : Optional[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_cli.py'''] ) UpperCAmelCase : List[Any] = ['''accelerate''', '''launch'''] UpperCAmelCase : Dict = Path.home() / '''.cache/huggingface/accelerate''' UpperCAmelCase : Union[str, Any] = '''default_config.yaml''' UpperCAmelCase : Union[str, Any] = config_folder / config_file UpperCAmelCase : Union[str, Any] = config_folder / '''_default_config.yaml''' UpperCAmelCase : List[Any] = Path('''tests/test_configs''' ) @classmethod def lowerCAmelCase_ ( cls : List[Any] ): if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def lowerCAmelCase_ ( cls : Tuple ): if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def lowerCAmelCase_ ( self : List[Any] ): _A = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy() ) def lowerCAmelCase_ ( self : Optional[int] ): for config in sorted(self.test_config_path.glob('**/*.yaml' ) ): with self.subTest(config_file=_UpperCAmelCase ): execute_subprocess_async( self.base_cmd + ['--config_file', str(_UpperCAmelCase ), self.test_file_path] , env=os.environ.copy() ) def lowerCAmelCase_ ( self : Any ): execute_subprocess_async(['accelerate', 'test'] , env=os.environ.copy() ) class lowercase_ ( unittest.TestCase ): '''simple docstring''' UpperCAmelCase : Dict = '''test-tpu''' UpperCAmelCase : Optional[int] = '''us-central1-a''' UpperCAmelCase : List[str] = '''ls''' UpperCAmelCase : str = ['''accelerate''', '''tpu-config'''] UpperCAmelCase : Optional[Any] = '''cd /usr/share''' UpperCAmelCase : Optional[Any] = '''tests/test_samples/test_command_file.sh''' UpperCAmelCase : str = '''Running gcloud compute tpus tpu-vm ssh''' def lowerCAmelCase_ ( self : Any ): _A = run_command( self.cmd + ['--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug'] , return_stdout=_UpperCAmelCase , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , _UpperCAmelCase , ) def lowerCAmelCase_ ( self : Dict ): _A = run_command( self.cmd + [ '--config_file', 'tests/test_configs/0_12_0.yaml', '--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug', ] , return_stdout=_UpperCAmelCase , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , _UpperCAmelCase , ) def lowerCAmelCase_ ( self : Optional[int] ): _A = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--debug'] , return_stdout=_UpperCAmelCase ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , _UpperCAmelCase , ) def lowerCAmelCase_ ( self : str ): _A = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--debug'] , return_stdout=_UpperCAmelCase , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' , _UpperCAmelCase , ) def lowerCAmelCase_ ( self : List[str] ): _A = run_command( self.cmd + [ '--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--command', 'echo "Hello World"', '--debug', ] , return_stdout=_UpperCAmelCase , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo "Hello World" --worker all''' , _UpperCAmelCase , ) def lowerCAmelCase_ ( self : str ): _A = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command_file', self.command_file, '--debug'] , return_stdout=_UpperCAmelCase , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , _UpperCAmelCase , ) def lowerCAmelCase_ ( self : List[Any] ): _A = run_command( self.cmd + [ '--config_file', 'tests/test_configs/0_12_0.yaml', '--command_file', self.command_file, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug', ] , return_stdout=_UpperCAmelCase , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all''' , _UpperCAmelCase , ) def lowerCAmelCase_ ( self : int ): _A = run_command( self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--debug'] , return_stdout=_UpperCAmelCase , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo "hello world"; echo "this is a second command" --worker all''' , _UpperCAmelCase , ) def lowerCAmelCase_ ( self : Optional[int] ): _A = run_command( self.cmd + [ '--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--accelerate_version', '12.0.0', '--debug', ] , return_stdout=_UpperCAmelCase , ) self.assertIn( F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo "hello world"; echo "this is a second command" --worker all''' , _UpperCAmelCase , )
271
0
# 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 from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case_ : Union[str, Any] = {"configuration_timm_backbone": ["TimmBackboneConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : List[Any] = ["TimmBackbone"] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys snake_case_ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
51
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase : Any = { """configuration_convbert""": ["""CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ConvBertConfig""", """ConvBertOnnxConfig"""], """tokenization_convbert""": ["""ConvBertTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[Any] = ["""ConvBertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[str] = [ """CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """ConvBertForMaskedLM""", """ConvBertForMultipleChoice""", """ConvBertForQuestionAnswering""", """ConvBertForSequenceClassification""", """ConvBertForTokenClassification""", """ConvBertLayer""", """ConvBertModel""", """ConvBertPreTrainedModel""", """load_tf_weights_in_convbert""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ """TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFConvBertForMaskedLM""", """TFConvBertForMultipleChoice""", """TFConvBertForQuestionAnswering""", """TFConvBertForSequenceClassification""", """TFConvBertForTokenClassification""", """TFConvBertLayer""", """TFConvBertModel""", """TFConvBertPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys UpperCAmelCase : Union[str, Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
95
0
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): '''simple docstring''' def __init__( self : str , lowercase : List[str] , lowercase : Optional[Any]=7 , lowercase : Union[str, Any]=3 , lowercase : List[Any]=30 , lowercase : Dict=400 , lowercase : Any=True , lowercase : Tuple=None , lowercase : Optional[int]=True , lowercase : List[str]=[0.5, 0.5, 0.5] , lowercase : Optional[int]=[0.5, 0.5, 0.5] , lowercase : str=True , lowercase : Tuple=1 / 255 , lowercase : Dict=True , ): '''simple docstring''' _snake_case = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1_333} _snake_case = parent _snake_case = batch_size _snake_case = num_channels _snake_case = min_resolution _snake_case = max_resolution _snake_case = do_resize _snake_case = size _snake_case = do_normalize _snake_case = image_mean _snake_case = image_std _snake_case = do_rescale _snake_case = rescale_factor _snake_case = do_pad def A ( self : List[str] ): '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def A ( self : Dict , lowercase : Union[str, Any] , lowercase : Optional[int]=False ): '''simple docstring''' if not batched: _snake_case = image_inputs[0] if isinstance(lowercase , Image.Image ): _snake_case , _snake_case = image.size else: _snake_case , _snake_case = image.shape[1], image.shape[2] if w < h: _snake_case = int(self.size['shortest_edge'] * h / w ) _snake_case = self.size['shortest_edge'] elif w > h: _snake_case = self.size['shortest_edge'] _snake_case = int(self.size['shortest_edge'] * w / h ) else: _snake_case = self.size['shortest_edge'] _snake_case = self.size['shortest_edge'] else: _snake_case = [] for image in image_inputs: _snake_case , _snake_case = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) _snake_case = max(lowercase , key=lambda lowercase : item[0] )[0] _snake_case = max(lowercase , key=lambda lowercase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ,unittest.TestCase ): '''simple docstring''' _UpperCAmelCase : str = ConditionalDetrImageProcessor if is_vision_available() else None def A ( self : Optional[Any] ): '''simple docstring''' _snake_case = ConditionalDetrImageProcessingTester(self ) @property def A ( self : int ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def A ( self : int ): '''simple docstring''' _snake_case = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase , 'image_mean' ) ) self.assertTrue(hasattr(lowercase , 'image_std' ) ) self.assertTrue(hasattr(lowercase , 'do_normalize' ) ) self.assertTrue(hasattr(lowercase , 'do_resize' ) ) self.assertTrue(hasattr(lowercase , 'size' ) ) def A ( self : Optional[Any] ): '''simple docstring''' _snake_case = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 1_333} ) self.assertEqual(image_processor.do_pad , lowercase ) _snake_case = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=lowercase ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , lowercase ) def A ( self : Any ): '''simple docstring''' pass def A ( self : List[Any] ): '''simple docstring''' _snake_case = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _snake_case = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase ) for image in image_inputs: self.assertIsInstance(lowercase , Image.Image ) # Test not batched input _snake_case = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _snake_case , _snake_case = self.image_processor_tester.get_expected_values(lowercase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _snake_case , _snake_case = self.image_processor_tester.get_expected_values(lowercase , batched=lowercase ) _snake_case = image_processing(lowercase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def A ( self : Union[str, Any] ): '''simple docstring''' _snake_case = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _snake_case = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase , numpify=lowercase ) for image in image_inputs: self.assertIsInstance(lowercase , np.ndarray ) # Test not batched input _snake_case = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _snake_case , _snake_case = self.image_processor_tester.get_expected_values(lowercase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _snake_case = image_processing(lowercase , return_tensors='pt' ).pixel_values _snake_case , _snake_case = self.image_processor_tester.get_expected_values(lowercase , batched=lowercase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def A ( self : Optional[int] ): '''simple docstring''' _snake_case = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _snake_case = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase , torchify=lowercase ) for image in image_inputs: self.assertIsInstance(lowercase , torch.Tensor ) # Test not batched input _snake_case = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _snake_case , _snake_case = self.image_processor_tester.get_expected_values(lowercase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _snake_case = image_processing(lowercase , return_tensors='pt' ).pixel_values _snake_case , _snake_case = self.image_processor_tester.get_expected_values(lowercase , batched=lowercase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def A ( self : int ): '''simple docstring''' _snake_case = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: _snake_case = json.loads(f.read() ) _snake_case = {'image_id': 39_769, 'annotations': target} # encode them _snake_case = ConditionalDetrImageProcessor.from_pretrained('microsoft/conditional-detr-resnet-50' ) _snake_case = image_processing(images=lowercase , annotations=lowercase , return_tensors='pt' ) # verify pixel values _snake_case = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding['pixel_values'].shape , lowercase ) _snake_case = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , lowercase , atol=1E-4 ) ) # verify area _snake_case = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , lowercase ) ) # verify boxes _snake_case = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , lowercase ) _snake_case = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , lowercase , atol=1E-3 ) ) # verify image_id _snake_case = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , lowercase ) ) # verify is_crowd _snake_case = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , lowercase ) ) # verify class_labels _snake_case = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , lowercase ) ) # verify orig_size _snake_case = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , lowercase ) ) # verify size _snake_case = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , lowercase ) ) @slow def A ( self : List[str] ): '''simple docstring''' _snake_case = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: _snake_case = json.loads(f.read() ) _snake_case = {'file_name': '000000039769.png', 'image_id': 39_769, 'segments_info': target} _snake_case = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them _snake_case = ConditionalDetrImageProcessor(format='coco_panoptic' ) _snake_case = image_processing(images=lowercase , annotations=lowercase , masks_path=lowercase , return_tensors='pt' ) # verify pixel values _snake_case = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding['pixel_values'].shape , lowercase ) _snake_case = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , lowercase , atol=1E-4 ) ) # verify area _snake_case = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , lowercase ) ) # verify boxes _snake_case = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , lowercase ) _snake_case = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , lowercase , atol=1E-3 ) ) # verify image_id _snake_case = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , lowercase ) ) # verify is_crowd _snake_case = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , lowercase ) ) # verify class_labels _snake_case = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , lowercase ) ) # verify masks _snake_case = 822_873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , lowercase ) # verify orig_size _snake_case = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , lowercase ) ) # verify size _snake_case = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , lowercase ) )
130
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process _lowerCamelCase : int = logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE__ : '''simple docstring''' _UpperCAmelCase : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) _UpperCAmelCase : Optional[str] = field( default=UpperCAmelCase ,metadata={"help": "Pretrained config name or path if not the same as model_name"} ) _UpperCAmelCase : Optional[str] = field( default="NER" ,metadata={"help": "Task type to fine tune in training (e.g. NER, POS, etc)"} ) _UpperCAmelCase : Optional[str] = field( default=UpperCAmelCase ,metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) _UpperCAmelCase : bool = field(default=UpperCAmelCase ,metadata={"help": "Set this flag to use fast tokenization."} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. _UpperCAmelCase : Optional[str] = field( default=UpperCAmelCase ,metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} ,) @dataclass class SCREAMING_SNAKE_CASE__ : '''simple docstring''' _UpperCAmelCase : str = field( metadata={"help": "The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."} ) _UpperCAmelCase : Optional[str] = field( default=UpperCAmelCase ,metadata={"help": "Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."} ,) _UpperCAmelCase : int = field( default=1_2_8 ,metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } ,) _UpperCAmelCase : bool = field( default=UpperCAmelCase ,metadata={"help": "Overwrite the cached training and evaluation sets"} ) def a_ ( ) -> Optional[int]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. _snake_case = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _snake_case , _snake_case , _snake_case = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _snake_case , _snake_case , _snake_case = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. Use''' ' --overwrite_output_dir to overcome.' ) _snake_case = import_module('tasks' ) try: _snake_case = getattr(__lowercase , model_args.task_type ) _snake_case = token_classification_task_clazz() except AttributeError: raise ValueError( f'''Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ''' f'''Available tasks classes are: {TokenClassificationTask.__subclasses__()}''' ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( 'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('Training/evaluation parameters %s' , __lowercase ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task _snake_case = token_classification_task.get_labels(data_args.labels ) _snake_case = dict(enumerate(__lowercase ) ) _snake_case = len(__lowercase ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _snake_case = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__lowercase , idalabel=__lowercase , labelaid={label: i for i, label in enumerate(__lowercase )} , cache_dir=model_args.cache_dir , ) _snake_case = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) _snake_case = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=__lowercase , cache_dir=model_args.cache_dir , ) # Get datasets _snake_case = ( TokenClassificationDataset( token_classification_task=__lowercase , data_dir=data_args.data_dir , tokenizer=__lowercase , labels=__lowercase , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) _snake_case = ( TokenClassificationDataset( token_classification_task=__lowercase , data_dir=data_args.data_dir , tokenizer=__lowercase , labels=__lowercase , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(__lowercase : np.ndarray , __lowercase : np.ndarray ) -> Tuple[List[int], List[int]]: _snake_case = np.argmax(__lowercase , axis=2 ) _snake_case , _snake_case = preds.shape _snake_case = [[] for _ in range(__lowercase )] _snake_case = [[] for _ in range(__lowercase )] for i in range(__lowercase ): for j in range(__lowercase ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(__lowercase : EvalPrediction ) -> Dict: _snake_case , _snake_case = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(__lowercase , __lowercase ), "precision": precision_score(__lowercase , __lowercase ), "recall": recall_score(__lowercase , __lowercase ), "f1": fa_score(__lowercase , __lowercase ), } # Data collator _snake_case = DataCollatorWithPadding(__lowercase , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer _snake_case = Trainer( model=__lowercase , args=__lowercase , train_dataset=__lowercase , eval_dataset=__lowercase , compute_metrics=__lowercase , data_collator=__lowercase , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation _snake_case = {} if training_args.do_eval: logger.info('*** Evaluate ***' ) _snake_case = trainer.evaluate() _snake_case = os.path.join(training_args.output_dir , 'eval_results.txt' ) if trainer.is_world_process_zero(): with open(__lowercase , 'w' ) as writer: logger.info('***** Eval results *****' ) for key, value in result.items(): logger.info(' %s = %s' , __lowercase , __lowercase ) writer.write('%s = %s\n' % (key, value) ) results.update(__lowercase ) # Predict if training_args.do_predict: _snake_case = TokenClassificationDataset( token_classification_task=__lowercase , data_dir=data_args.data_dir , tokenizer=__lowercase , labels=__lowercase , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) _snake_case , _snake_case , _snake_case = trainer.predict(__lowercase ) _snake_case , _snake_case = align_predictions(__lowercase , __lowercase ) _snake_case = os.path.join(training_args.output_dir , 'test_results.txt' ) if trainer.is_world_process_zero(): with open(__lowercase , 'w' ) as writer: for key, value in metrics.items(): logger.info(' %s = %s' , __lowercase , __lowercase ) writer.write('%s = %s\n' % (key, value) ) # Save predictions _snake_case = os.path.join(training_args.output_dir , 'test_predictions.txt' ) if trainer.is_world_process_zero(): with open(__lowercase , 'w' ) as writer: with open(os.path.join(data_args.data_dir , 'test.txt' ) , 'r' ) as f: token_classification_task.write_predictions_to_file(__lowercase , __lowercase , __lowercase ) return results def a_ ( __lowercase : Optional[Any] ) -> Optional[int]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
130
1
from __future__ import annotations __a = list[tuple[int, int]] __a = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] __a = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class __SCREAMING_SNAKE_CASE : def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ): lowercase : Any = pos_x lowercase : str = pos_y lowercase : Optional[Any] = (pos_y, pos_x) lowercase : int = goal_x lowercase : Optional[Any] = goal_y lowercase : int = g_cost lowercase : Any = parent lowercase : Optional[int] = self.calculate_heuristic() def __lowerCamelCase ( self ): lowercase : Optional[Any] = abs(self.pos_x - self.goal_x ) lowercase : List[str] = abs(self.pos_y - self.goal_y ) return dx + dy def __lt__( self , SCREAMING_SNAKE_CASE__ ): return self.f_cost < other.f_cost class __SCREAMING_SNAKE_CASE : def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowercase : str = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , UpperCamelCase__ ) lowercase : int = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99999 , UpperCamelCase__ ) lowercase : int = [self.start] lowercase : int = [] lowercase : Any = False def __lowerCamelCase ( self ): while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() lowercase : Optional[int] = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: lowercase : List[Any] = True return self.retrace_path(UpperCamelCase__ ) self.closed_nodes.append(UpperCamelCase__ ) lowercase : Dict = self.get_successors(UpperCamelCase__ ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(UpperCamelCase__ ) else: # retrieve the best current path lowercase : Optional[Any] = self.open_nodes.pop(self.open_nodes.index(UpperCamelCase__ ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(UpperCamelCase__ ) else: self.open_nodes.append(UpperCamelCase__ ) if not self.reached: return [self.start.pos] return None def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ ): lowercase : int = [] for action in delta: lowercase : Tuple = parent.pos_x + action[1] lowercase : Any = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(UpperCamelCase__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( UpperCamelCase__ , UpperCamelCase__ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , UpperCamelCase__ , ) ) return successors def __lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ ): lowercase : str = node lowercase : str = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) lowercase : List[str] = current_node.parent path.reverse() return path if __name__ == "__main__": __a = (0, 0) __a = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print('''------''') __a = GreedyBestFirst(init, goal) __a = greedy_bf.search() if path: for pos_x, pos_y in path: __a = 2 for elem in grid: print(elem)
337
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCamelCase = logging.get_logger(__name__) __lowerCamelCase = { '''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 A__ ( _snake_case ): lowercase = "luke" def __init__( self , UpperCamelCase__=50267 , UpperCamelCase__=500000 , UpperCamelCase__=768 , UpperCamelCase__=256 , UpperCamelCase__=12 , UpperCamelCase__=12 , UpperCamelCase__=3072 , UpperCamelCase__="gelu" , UpperCamelCase__=0.1 , UpperCamelCase__=0.1 , UpperCamelCase__=512 , UpperCamelCase__=2 , UpperCamelCase__=0.02 , UpperCamelCase__=1e-1_2 , UpperCamelCase__=True , UpperCamelCase__=None , UpperCamelCase__=1 , UpperCamelCase__=0 , UpperCamelCase__=2 , **UpperCamelCase__ , ) -> Optional[int]: '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ ) A_ = vocab_size A_ = entity_vocab_size A_ = hidden_size A_ = entity_emb_size A_ = num_hidden_layers A_ = num_attention_heads A_ = hidden_act A_ = intermediate_size A_ = hidden_dropout_prob A_ = attention_probs_dropout_prob A_ = max_position_embeddings A_ = type_vocab_size A_ = initializer_range A_ = layer_norm_eps A_ = use_entity_aware_attention A_ = classifier_dropout
162
0
'''simple docstring''' from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize('''repo_id''', ['''canonical_dataset_name''', '''org-name/dataset-name'''] ) @pytest.mark.parametrize('''path''', ['''filename.csv''', '''filename with blanks.csv'''] ) @pytest.mark.parametrize('''revision''', [None, '''v2'''] ) def _a( UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : Tuple, UpperCamelCase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str =hf_hub_url(repo_id=UpperCamelCase__, path=UpperCamelCase__, revision=UpperCamelCase__ ) assert url == f"https://huggingface.co/datasets/{repo_id}/resolve/{revision or 'main'}/{quote(UpperCamelCase__ )}"
222
'''simple docstring''' import inspect import jax import jax.lax as lax import jax.numpy as jnp from ..utils import add_start_docstrings from ..utils.logging import get_logger a_ = get_logger(__name__) a_ = R'\n Args:\n input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):\n Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam\n search or log softmax for each vocabulary token when using beam search\n kwargs (`Dict[str, Any]`, *optional*):\n Additional logits processor specific kwargs.\n\n Return:\n `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.\n\n' class __SCREAMING_SNAKE_CASE : @add_start_docstrings(__lowercase ) def __call__( self : Any , __lowercase : jnp.ndarray , __lowercase : jnp.ndarray ) -> jnp.ndarray: raise NotImplementedError( F"{self.__class__} is an abstract class. Only classes inheriting this class can be called." ) class __SCREAMING_SNAKE_CASE : @add_start_docstrings(__lowercase ) def __call__( self : List[str] , __lowercase : jnp.ndarray , __lowercase : jnp.ndarray ) -> jnp.ndarray: raise NotImplementedError( F"{self.__class__} is an abstract class. Only classes inheriting this class can be called." ) class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): @add_start_docstrings(__lowercase ) def __call__( self : Any , __lowercase : jnp.ndarray , __lowercase : jnp.ndarray , __lowercase : int , **__lowercase : List[str] ) -> jnp.ndarray: for processor in self: SCREAMING_SNAKE_CASE__ : Optional[Any] =inspect.signature(processor.__call__ ).parameters if len(__lowercase ) > 3: if not all(arg in kwargs for arg in list(function_args.keys() )[2:] ): raise ValueError( F"Make sure that all the required parameters: {list(function_args.keys() )} for " F"{processor.__class__} are passed to the logits processor." ) SCREAMING_SNAKE_CASE__ : List[Any] =processor(__lowercase , __lowercase , __lowercase , **__lowercase ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] =processor(__lowercase , __lowercase , __lowercase ) return scores class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __init__( self : List[str] , __lowercase : float ) -> Tuple: if not isinstance(__lowercase , __lowercase ) or not (temperature > 0): raise ValueError(F"`temperature` has to be a strictly positive float, but is {temperature}" ) SCREAMING_SNAKE_CASE__ : Optional[int] =temperature def __call__( self : Optional[int] , __lowercase : jnp.ndarray , __lowercase : jnp.ndarray , __lowercase : int ) -> jnp.ndarray: SCREAMING_SNAKE_CASE__ : int =scores / self.temperature return scores class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __init__( self : Tuple , __lowercase : float , __lowercase : float = -float('''Inf''' ) , __lowercase : int = 1 ) -> List[str]: if not isinstance(__lowercase , __lowercase ) or (top_p < 0 or top_p > 1.0): raise ValueError(F"`top_p` has to be a float > 0 and < 1, but is {top_p}" ) if not isinstance(__lowercase , __lowercase ) or (min_tokens_to_keep < 1): raise ValueError(F"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}" ) SCREAMING_SNAKE_CASE__ : Tuple =top_p SCREAMING_SNAKE_CASE__ : List[str] =filter_value SCREAMING_SNAKE_CASE__ : Optional[Any] =min_tokens_to_keep def __call__( self : int , __lowercase : jnp.ndarray , __lowercase : jnp.ndarray , __lowercase : int ) -> jnp.ndarray: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] =lax.top_k(__lowercase , scores.shape[-1] ) SCREAMING_SNAKE_CASE__ : List[str] =jnp.full_like(__lowercase , self.filter_value ) SCREAMING_SNAKE_CASE__ : Tuple =jax.nn.softmax(__lowercase , axis=-1 ).cumsum(axis=-1 ) SCREAMING_SNAKE_CASE__ : Dict =cumulative_probs < self.top_p # include the token that is higher than top_p as well SCREAMING_SNAKE_CASE__ : Optional[Any] =jnp.roll(__lowercase , 1 ) score_mask |= score_mask.at[:, 0].set(__lowercase ) # min tokens to keep SCREAMING_SNAKE_CASE__ : Optional[Any] =score_mask.at[:, : self.min_tokens_to_keep].set(__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =jnp.where(__lowercase , __lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : int =jax.lax.sort_key_val(__lowercase , __lowercase )[-1] return next_scores class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __init__( self : List[str] , __lowercase : int , __lowercase : float = -float('''Inf''' ) , __lowercase : int = 1 ) -> List[Any]: if not isinstance(__lowercase , __lowercase ) or top_k <= 0: raise ValueError(F"`top_k` has to be a strictly positive integer, but is {top_k}" ) SCREAMING_SNAKE_CASE__ : str =max(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : List[Any] =filter_value def __call__( self : List[Any] , __lowercase : jnp.ndarray , __lowercase : jnp.ndarray , __lowercase : int ) -> jnp.ndarray: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict =scores.shape SCREAMING_SNAKE_CASE__ : str =jnp.full(batch_size * vocab_size , self.filter_value ) SCREAMING_SNAKE_CASE__ : List[Any] =min(self.top_k , scores.shape[-1] ) # Safety check SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] =lax.top_k(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : int =jnp.broadcast_to((jnp.arange(__lowercase ) * vocab_size)[:, None] , (batch_size, topk) ).flatten() SCREAMING_SNAKE_CASE__ : str =topk_scores.flatten() SCREAMING_SNAKE_CASE__ : int =topk_indices.flatten() + shift SCREAMING_SNAKE_CASE__ : str =next_scores_flat.at[topk_indices_flat].set(__lowercase ) SCREAMING_SNAKE_CASE__ : Any =next_scores_flat.reshape(__lowercase , __lowercase ) return next_scores class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __init__( self : Any , __lowercase : int ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : List[str] =bos_token_id def __call__( self : Tuple , __lowercase : jnp.ndarray , __lowercase : jnp.ndarray , __lowercase : int ) -> jnp.ndarray: SCREAMING_SNAKE_CASE__ : Tuple =jnp.full(scores.shape , -float('''inf''' ) ) SCREAMING_SNAKE_CASE__ : str =1 - jnp.bool_(cur_len - 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] =jnp.where(__lowercase , new_scores.at[:, self.bos_token_id].set(0 ) , __lowercase ) return scores class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __init__( self : Union[str, Any] , __lowercase : int , __lowercase : int ) -> List[str]: SCREAMING_SNAKE_CASE__ : Optional[int] =max_length SCREAMING_SNAKE_CASE__ : int =eos_token_id def __call__( self : Any , __lowercase : jnp.ndarray , __lowercase : jnp.ndarray , __lowercase : int ) -> jnp.ndarray: SCREAMING_SNAKE_CASE__ : Optional[int] =jnp.full(scores.shape , -float('''inf''' ) ) SCREAMING_SNAKE_CASE__ : str =1 - jnp.bool_(cur_len - self.max_length + 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] =jnp.where(__lowercase , new_scores.at[:, self.eos_token_id].set(0 ) , __lowercase ) return scores class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __init__( self : Union[str, Any] , __lowercase : int , __lowercase : int ) -> Tuple: if not isinstance(__lowercase , __lowercase ) or min_length < 0: raise ValueError(F"`min_length` has to be a positive integer, but is {min_length}" ) if not isinstance(__lowercase , __lowercase ) or eos_token_id < 0: raise ValueError(F"`eos_token_id` has to be a positive integer, but is {eos_token_id}" ) SCREAMING_SNAKE_CASE__ : str =min_length SCREAMING_SNAKE_CASE__ : Tuple =eos_token_id def __call__( self : Tuple , __lowercase : jnp.ndarray , __lowercase : jnp.ndarray , __lowercase : int ) -> jnp.ndarray: # create boolean flag to decide if min length penalty should be applied SCREAMING_SNAKE_CASE__ : List[str] =1 - jnp.clip(cur_len - self.min_length , 0 , 1 ) SCREAMING_SNAKE_CASE__ : Tuple =jnp.where(__lowercase , scores.at[:, self.eos_token_id].set(-float('''inf''' ) ) , __lowercase ) return scores class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __init__( self : int , __lowercase : Optional[Any] , __lowercase : Tuple ) -> List[str]: SCREAMING_SNAKE_CASE__ : Dict =list(__lowercase ) SCREAMING_SNAKE_CASE__ : Optional[int] =begin_index def __call__( self : Optional[Any] , __lowercase : Optional[Any] , __lowercase : Dict , __lowercase : int ) -> List[str]: SCREAMING_SNAKE_CASE__ : Any =1 - jnp.bool_(cur_len - self.begin_index ) SCREAMING_SNAKE_CASE__ : Optional[int] =jnp.where(__lowercase , scores.at[:, self.begin_suppress_tokens].set(-float('''inf''' ) ) , __lowercase ) return scores class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __init__( self : Optional[Any] , __lowercase : list ) -> Dict: SCREAMING_SNAKE_CASE__ : int =list(__lowercase ) def __call__( self : str , __lowercase : jnp.ndarray , __lowercase : jnp.ndarray , __lowercase : int ) -> jnp.ndarray: SCREAMING_SNAKE_CASE__ : Optional[int] =scores.at[..., self.suppress_tokens].set(-float('''inf''' ) ) return scores class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __init__( self : List[Any] , __lowercase : List[str] ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : List[str] =dict(__lowercase ) # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the # index of the array corresponds to the index of the token to be forced, for XLA compatibility. # Indexes without forced tokens will have a negative value. SCREAMING_SNAKE_CASE__ : Any =jnp.ones((max(force_token_map.keys() ) + 1) , dtype=jnp.intaa ) * -1 for index, token in force_token_map.items(): if token is not None: SCREAMING_SNAKE_CASE__ : Tuple =force_token_array.at[index].set(__lowercase ) SCREAMING_SNAKE_CASE__ : Dict =jnp.intaa(__lowercase ) def __call__( self : Optional[Any] , __lowercase : jnp.ndarray , __lowercase : jnp.ndarray , __lowercase : int ) -> jnp.ndarray: def _force_token(__lowercase : Union[str, Any] ): SCREAMING_SNAKE_CASE__ : Dict =scores.shape[0] SCREAMING_SNAKE_CASE__ : Optional[int] =self.force_token_array[generation_idx] SCREAMING_SNAKE_CASE__ : Optional[int] =jnp.ones_like(__lowercase , dtype=scores.dtype ) * -float('''inf''' ) SCREAMING_SNAKE_CASE__ : Tuple =jnp.zeros((batch_size, 1) , dtype=scores.dtype ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =lax.dynamic_update_slice(__lowercase , __lowercase , (0, current_token) ) return new_scores SCREAMING_SNAKE_CASE__ : Tuple =lax.cond( cur_len >= self.force_token_array.shape[0] , lambda: scores , lambda: lax.cond( self.force_token_array[cur_len] >= 0 , lambda: _force_token(__lowercase ) , lambda: scores , ) , ) return scores class __SCREAMING_SNAKE_CASE ( lowerCamelCase ): def __init__( self : List[str] , __lowercase : List[Any] , __lowercase : List[str] , __lowercase : Any ) -> Tuple: SCREAMING_SNAKE_CASE__ : Optional[int] =generate_config.eos_token_id SCREAMING_SNAKE_CASE__ : List[Any] =generate_config.no_timestamps_token_id SCREAMING_SNAKE_CASE__ : List[Any] =generate_config.no_timestamps_token_id + 1 SCREAMING_SNAKE_CASE__ : Dict =decoder_input_length + 1 if generate_config.is_multilingual: # room for language token and task token self.begin_index += 2 if hasattr(__lowercase , '''max_initial_timestamp_index''' ): SCREAMING_SNAKE_CASE__ : int =generate_config.max_initial_timestamp_index else: SCREAMING_SNAKE_CASE__ : Optional[int] =model_config.vocab_size if self.max_initial_timestamp_index is None: SCREAMING_SNAKE_CASE__ : Union[str, Any] =model_config.vocab_size def __call__( self : List[Any] , __lowercase : Union[str, Any] , __lowercase : Any , __lowercase : str ) -> Optional[Any]: # suppress <|notimestamps|> which is handled by without_timestamps SCREAMING_SNAKE_CASE__ : Any =scores.at[:, self.no_timestamps_token_id].set(-float('''inf''' ) ) def handle_pairs(__lowercase : Any , __lowercase : Optional[int] ): SCREAMING_SNAKE_CASE__ : Optional[int] =jnp.where((cur_len - self.begin_index) >= 1 , __lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =jnp.where( input_ids_k[cur_len - 1] >= self.timestamp_begin , True and last_was_timestamp , __lowercase , ) SCREAMING_SNAKE_CASE__ : List[str] =jnp.where((cur_len - self.begin_index) < 2 , __lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : Any =jnp.where( input_ids_k[cur_len - 2] >= self.timestamp_begin , __lowercase , __lowercase , ) return jnp.where( __lowercase , jnp.where( penultimate_was_timestamp > 0 , scores_k.at[self.timestamp_begin :].set(-float('''inf''' ) ) , scores_k.at[: self.eos_token_id].set(-float('''inf''' ) ) , ) , __lowercase , ) SCREAMING_SNAKE_CASE__ : List[str] =jax.vmap(__lowercase )(__lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : Optional[Any] =jnp.where(cur_len == self.begin_index , __lowercase , __lowercase ) SCREAMING_SNAKE_CASE__ : int =jnp.where( self.max_initial_timestamp_index is not None , True and apply_max_initial_timestamp , __lowercase , ) SCREAMING_SNAKE_CASE__ : Optional[int] =self.timestamp_begin + self.max_initial_timestamp_index SCREAMING_SNAKE_CASE__ : int =jnp.where( __lowercase , scores.at[:, last_allowed + 1 :].set(-float('''inf''' ) ) , __lowercase , ) # if sum of probability over timestamps is above any other token, sample timestamp SCREAMING_SNAKE_CASE__ : Any =jax.nn.log_softmax(__lowercase , axis=-1 ) def handle_cumulative_probs(__lowercase : Optional[int] , __lowercase : str ): SCREAMING_SNAKE_CASE__ : Union[str, Any] =jax.nn.logsumexp(logprobs_k[self.timestamp_begin :] , axis=-1 ) SCREAMING_SNAKE_CASE__ : List[Any] =jnp.max(logprobs_k[: self.timestamp_begin] ) return jnp.where( timestamp_logprob > max_text_token_logprob , scores_k.at[: self.timestamp_begin].set(-float('''inf''' ) ) , __lowercase , ) SCREAMING_SNAKE_CASE__ : Any =jax.vmap(__lowercase )(__lowercase , __lowercase ) return scores
222
1
'''simple docstring''' import string import numpy def a_ ( __snake_case : int , __snake_case : int ) -> int: """simple docstring""" return b if a == 0 else greatest_common_divisor(b % a , __snake_case ) class __UpperCamelCase : lowercase : Optional[int] =string.ascii_uppercase + string.digits # This cipher takes alphanumerics into account # i.e. a total of 36 characters # take x and return x % len(key_string) lowercase : Any =numpy.vectorize(lambda lowerCamelCase__ : x % 36 ) lowercase : List[str] =numpy.vectorize(lowerCamelCase__ ) def __init__( self, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =self.modulus(lowerCAmelCase ) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key lowerCamelCase_ =encrypt_key.shape[0] def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" return self.key_string.index(lowerCAmelCase ) def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" return self.key_string[round(lowerCAmelCase )] def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: lowerCamelCase_ =det % len(self.key_string ) lowerCamelCase_ =len(self.key_string ) if greatest_common_divisor(lowerCAmelCase, len(self.key_string ) ) != 1: lowerCamelCase_ =( f'''determinant modular {req_l} of encryption key({det}) ''' f'''is not co prime w.r.t {req_l}.\nTry another key.''' ) raise ValueError(lowerCAmelCase ) def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =[char for char in text.upper() if char in self.key_string] lowerCamelCase_ =chars[-1] while len(lowerCAmelCase ) % self.break_key != 0: chars.append(lowerCAmelCase ) return "".join(lowerCAmelCase ) def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =self.process_text(text.upper() ) lowerCamelCase_ ='''''' for i in range(0, len(lowerCAmelCase ) - self.break_key + 1, self.break_key ): lowerCamelCase_ =text[i : i + self.break_key] lowerCamelCase_ =[self.replace_letters(lowerCAmelCase ) for char in batch] lowerCamelCase_ =numpy.array([vec] ).T lowerCamelCase_ =self.modulus(self.encrypt_key.dot(lowerCAmelCase ) ).T.tolist()[ 0 ] lowerCamelCase_ =''''''.join( self.replace_digits(lowerCAmelCase ) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: lowerCamelCase_ =det % len(self.key_string ) lowerCamelCase_ =None for i in range(len(self.key_string ) ): if (det * i) % len(self.key_string ) == 1: lowerCamelCase_ =i break lowerCamelCase_ =( det_inv * numpy.linalg.det(self.encrypt_key ) * numpy.linalg.inv(self.encrypt_key ) ) return self.to_int(self.modulus(lowerCAmelCase ) ) def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =self.make_decrypt_key() lowerCamelCase_ =self.process_text(text.upper() ) lowerCamelCase_ ='''''' for i in range(0, len(lowerCAmelCase ) - self.break_key + 1, self.break_key ): lowerCamelCase_ =text[i : i + self.break_key] lowerCamelCase_ =[self.replace_letters(lowerCAmelCase ) for char in batch] lowerCamelCase_ =numpy.array([vec] ).T lowerCamelCase_ =self.modulus(decrypt_key.dot(lowerCAmelCase ) ).T.tolist()[0] lowerCamelCase_ =''''''.join( self.replace_digits(lowerCAmelCase ) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def a_ ( ) -> None: """simple docstring""" lowerCamelCase_ =int(input('''Enter the order of the encryption key: ''' ) ) lowerCamelCase_ =[] print('''Enter each row of the encryption key with space separated integers''' ) for _ in range(__snake_case ): lowerCamelCase_ =[int(__snake_case ) for x in input().split()] hill_matrix.append(__snake_case ) lowerCamelCase_ =HillCipher(numpy.array(__snake_case ) ) print('''Would you like to encrypt or decrypt some text? (1 or 2)''' ) lowerCamelCase_ =input('''\n1. Encrypt\n2. Decrypt\n''' ) if option == "1": lowerCamelCase_ =input('''What text would you like to encrypt?: ''' ) print('''Your encrypted text is:''' ) print(hc.encrypt(__snake_case ) ) elif option == "2": lowerCamelCase_ =input('''What text would you like to decrypt?: ''' ) print('''Your decrypted text is:''' ) print(hc.decrypt(__snake_case ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
75
'''simple docstring''' from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class __UpperCamelCase ( lowerCamelCase__ ): def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" return 0.0 def a_ ( __snake_case : np.ndarray , __snake_case : int ) -> tuple[int | float, int | float]: """simple docstring""" lowerCamelCase_ =min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) lowerCamelCase_ =max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def a_ ( __snake_case : FilterType , __snake_case : int ) -> None: """simple docstring""" lowerCamelCase_ =512 lowerCamelCase_ =[1] + [0] * (size - 1) lowerCamelCase_ =[filter_type.process(__snake_case ) for item in inputs] lowerCamelCase_ =[0] * (samplerate - size) # zero-padding outputs += filler lowerCamelCase_ =np.abs(np.fft.fft(__snake_case ) ) lowerCamelCase_ =20 * np.logaa(__snake_case ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel('''Frequency (Hz)''' ) plt.xscale('''log''' ) # Display within reasonable bounds lowerCamelCase_ =get_bounds(__snake_case , __snake_case ) plt.ylim(max([-80, bounds[0]] ) , min([80, bounds[1]] ) ) plt.ylabel('''Gain (dB)''' ) plt.plot(__snake_case ) plt.show() def a_ ( __snake_case : FilterType , __snake_case : int ) -> None: """simple docstring""" lowerCamelCase_ =512 lowerCamelCase_ =[1] + [0] * (size - 1) lowerCamelCase_ =[filter_type.process(__snake_case ) for item in inputs] lowerCamelCase_ =[0] * (samplerate - size) # zero-padding outputs += filler lowerCamelCase_ =np.angle(np.fft.fft(__snake_case ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel('''Frequency (Hz)''' ) plt.xscale('''log''' ) plt.ylim(-2 * pi , 2 * pi ) plt.ylabel('''Phase shift (Radians)''' ) plt.plot(np.unwrap(__snake_case , -2 * pi ) ) plt.show()
75
1
import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case__(_UpperCamelCase , unittest.TestCase ): """simple docstring""" lowercase_ = OpenAIGPTTokenizer lowercase_ = OpenAIGPTTokenizerFast lowercase_ = True lowercase_ = False def snake_case ( self : Dict ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt lowercase__ : Dict = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "w</w>", "r</w>", "t</w>", "lo", "low", "er</w>", "low</w>", "lowest</w>", "newer</w>", "wider</w>", "<unk>", ] lowercase__ : List[Any] = dict(zip(SCREAMING_SNAKE_CASE , range(len(SCREAMING_SNAKE_CASE ) ) ) ) lowercase__ : Dict = ["#version: 0.2", "l o", "lo w", "e r</w>", ""] lowercase__ : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) lowercase__ : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE ) ) with open(self.merges_file , "w" ) as fp: fp.write("\n".join(SCREAMING_SNAKE_CASE ) ) def snake_case ( self : Dict , SCREAMING_SNAKE_CASE : Tuple ): return "lower newer", "lower newer" def snake_case ( self : Optional[int] ): lowercase__ : List[str] = OpenAIGPTTokenizer(self.vocab_file , self.merges_file ) lowercase__ : int = "lower" lowercase__ : List[str] = ["low", "er</w>"] lowercase__ : int = tokenizer.tokenize(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) lowercase__ : Any = tokens + ["<unk>"] lowercase__ : List[str] = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) def snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE : Any=15 ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): lowercase__ : List[Any] = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # Simple input lowercase__ : Dict = "This is a simple input" lowercase__ : Tuple = ["This is a simple input 1", "This is a simple input 2"] lowercase__ : Optional[Any] = ("This is a simple input", "This is a pair") lowercase__ : Dict = [ ("This is a simple input 1", "This is a simple input 2"), ("This is a simple pair 1", "This is a simple pair 2"), ] # Simple input tests self.assertRaises(SCREAMING_SNAKE_CASE , tokenizer_r.encode , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="max_length" ) # Simple input self.assertRaises(SCREAMING_SNAKE_CASE , tokenizer_r.encode_plus , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="max_length" ) # Simple input self.assertRaises( SCREAMING_SNAKE_CASE , tokenizer_r.batch_encode_plus , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="max_length" , ) # Pair input self.assertRaises(SCREAMING_SNAKE_CASE , tokenizer_r.encode , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="max_length" ) # Pair input self.assertRaises(SCREAMING_SNAKE_CASE , tokenizer_r.encode_plus , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="max_length" ) # Pair input self.assertRaises( SCREAMING_SNAKE_CASE , tokenizer_r.batch_encode_plus , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="max_length" , ) def snake_case ( self : Union[str, Any] ): pass @require_ftfy @require_spacy @require_tokenizers class snake_case__(_UpperCamelCase ): """simple docstring""" pass
121
from __future__ import annotations lowerCAmelCase__ = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ): """simple docstring""" lowercase__ : Optional[int] = [ [0 for col in range(len(grid[0] ) )] for row in range(len(lowerCamelCase__ ) ) ] # the reference grid lowercase__ : List[Any] = 1 lowercase__ : Tuple = [ [0 for col in range(len(grid[0] ) )] for row in range(len(lowerCamelCase__ ) ) ] # the action grid lowercase__ : Union[str, Any] = init[0] lowercase__ : List[str] = init[1] lowercase__ : Optional[Any] = 0 lowercase__ : Optional[int] = g + heuristic[x][y] # cost from starting cell to destination cell lowercase__ : Tuple = [[f, g, x, y]] lowercase__ : Union[str, Any] = False # flag that is set when search is complete lowercase__ : Any = False # flag set if we can't find expand while not found and not resign: if len(lowerCamelCase__ ) == 0: raise ValueError("Algorithm is unable to find solution" ) else: # to choose the least costliest action so as to move closer to the goal cell.sort() cell.reverse() lowercase__ : Tuple = cell.pop() lowercase__ : Optional[Any] = next_cell[2] lowercase__ : int = next_cell[3] lowercase__ : Union[str, Any] = next_cell[1] if x == goal[0] and y == goal[1]: lowercase__ : Tuple = True else: for i in range(len(lowerCamelCase__ ) ): # to try out different valid actions lowercase__ : Tuple = x + DIRECTIONS[i][0] lowercase__ : str = y + DIRECTIONS[i][1] if xa >= 0 and xa < len(lowerCamelCase__ ) and ya >= 0 and ya < len(grid[0] ): if closed[xa][ya] == 0 and grid[xa][ya] == 0: lowercase__ : List[Any] = g + cost lowercase__ : Tuple = ga + heuristic[xa][ya] cell.append([fa, ga, xa, ya] ) lowercase__ : Dict = 1 lowercase__ : Union[str, Any] = i lowercase__ : Optional[int] = [] lowercase__ : List[Any] = goal[0] lowercase__ : Optional[int] = goal[1] invpath.append([x, y] ) # we get the reverse path from here while x != init[0] or y != init[1]: lowercase__ : int = x - DIRECTIONS[action[x][y]][0] lowercase__ : List[Any] = y - DIRECTIONS[action[x][y]][1] lowercase__ : Optional[Any] = xa lowercase__ : Dict = ya invpath.append([x, y] ) lowercase__ : List[str] = [] for i in range(len(lowerCamelCase__ ) ): path.append(invpath[len(lowerCamelCase__ ) - 1 - i] ) return path, action if __name__ == "__main__": lowerCAmelCase__ = [ [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0], ] lowerCAmelCase__ = [0, 0] # all coordinates are given in format [y,x] lowerCAmelCase__ = [len(grid) - 1, len(grid[0]) - 1] lowerCAmelCase__ = 1 # the cost map which pushes the path closer to the goal lowerCAmelCase__ = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): lowerCAmelCase__ = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: # added extra penalty in the heuristic map lowerCAmelCase__ = 9_9 lowerCAmelCase__ , lowerCAmelCase__ = search(grid, init, goal, cost, heuristic) print('''ACTION MAP''') for i in range(len(action)): print(action[i]) for i in range(len(path)): print(path[i])
121
1
import baseaa import io import json import os from copy import deepcopy from ..optimizer import AcceleratedOptimizer from ..scheduler import AcceleratedScheduler class __lowerCamelCase : """simple docstring""" def __init__( self , UpperCAmelCase ): """simple docstring""" if isinstance(UpperCAmelCase , UpperCAmelCase ): # Don't modify user's data should they want to reuse it (e.g. in tests), because once we # modified it, it will not be accepted here again, since `auto` values would have been overridden _UpperCAmelCase = deepcopy(UpperCAmelCase ) elif os.path.exists(UpperCAmelCase ): with io.open(UpperCAmelCase , 'r' , encoding='utf-8' ) as f: _UpperCAmelCase = json.load(UpperCAmelCase ) else: try: _UpperCAmelCase = baseaa.urlsafe_baadecode(UpperCAmelCase ).decode('utf-8' ) _UpperCAmelCase = json.loads(UpperCAmelCase ) except (UnicodeDecodeError, AttributeError, ValueError): raise ValueError( F"""Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}""" ) _UpperCAmelCase = config self.set_stage_and_offload() def UpperCamelCase ( self ): """simple docstring""" _UpperCAmelCase = self.get_value('zero_optimization.stage' , -1 ) # offload _UpperCAmelCase = False if self.is_zeroa() or self.is_zeroa(): _UpperCAmelCase = set(['cpu', 'nvme'] ) _UpperCAmelCase = set( [ self.get_value('zero_optimization.offload_optimizer.device' ), self.get_value('zero_optimization.offload_param.device' ), ] ) if len(offload_devices & offload_devices_valid ) > 0: _UpperCAmelCase = True def UpperCamelCase ( self , UpperCAmelCase ): """simple docstring""" _UpperCAmelCase = self.config # find the config node of interest if it exists _UpperCAmelCase = ds_key_long.split('.' ) _UpperCAmelCase = nodes.pop() for node in nodes: _UpperCAmelCase = config.get(UpperCAmelCase ) if config is None: return None, ds_key return config, ds_key def UpperCamelCase ( self , UpperCAmelCase , UpperCAmelCase=None ): """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.find_config_node(UpperCAmelCase ) if config is None: return default return config.get(UpperCAmelCase , UpperCAmelCase ) def UpperCamelCase ( self , UpperCAmelCase , UpperCAmelCase=False ): """simple docstring""" _UpperCAmelCase = self.config # find the config node of interest if it exists _UpperCAmelCase = ds_key_long.split('.' ) for node in nodes: _UpperCAmelCase = config _UpperCAmelCase = config.get(UpperCAmelCase ) if config is None: if must_exist: raise ValueError(F"""Can't find {ds_key_long} entry in the config: {self.config}""" ) else: return # if found remove it if parent_config is not None: parent_config.pop(UpperCAmelCase ) def UpperCamelCase ( self , UpperCAmelCase ): """simple docstring""" _UpperCAmelCase = self.get_value(UpperCAmelCase ) return False if value is None else bool(UpperCAmelCase ) def UpperCamelCase ( self , UpperCAmelCase ): """simple docstring""" _UpperCAmelCase = self.get_value(UpperCAmelCase ) return False if value is None else not bool(UpperCAmelCase ) def UpperCamelCase ( self ): """simple docstring""" return self._stage == 2 def UpperCamelCase ( self ): """simple docstring""" return self._stage == 3 def UpperCamelCase ( self ): """simple docstring""" return self._offload class __lowerCamelCase : """simple docstring""" def __init__( self , UpperCAmelCase ): """simple docstring""" _UpperCAmelCase = engine def UpperCamelCase ( self , UpperCAmelCase , **UpperCAmelCase ): """simple docstring""" self.engine.backward(UpperCAmelCase , **UpperCAmelCase ) # Deepspeed's `engine.step` performs the following operations: # - gradient accumulation check # - gradient clipping # - optimizer step # - zero grad # - checking overflow # - lr_scheduler step (only if engine.lr_scheduler is not None) self.engine.step() # and this plugin overrides the above calls with no-ops when Accelerate runs under # Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple # training loop that works transparently under many training regimes. class __lowerCamelCase ( snake_case__): """simple docstring""" def __init__( self , UpperCAmelCase ): """simple docstring""" super().__init__(UpperCAmelCase , device_placement=UpperCAmelCase , scaler=UpperCAmelCase ) _UpperCAmelCase = hasattr(self.optimizer , 'overflow' ) def UpperCamelCase ( self , UpperCAmelCase=None ): """simple docstring""" pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed def UpperCamelCase ( self ): """simple docstring""" pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed @property def UpperCamelCase ( self ): """simple docstring""" if self.__has_overflow__: return self.optimizer.overflow return False class __lowerCamelCase ( snake_case__): """simple docstring""" def __init__( self , UpperCAmelCase , UpperCAmelCase ): """simple docstring""" super().__init__(UpperCAmelCase , UpperCAmelCase ) def UpperCamelCase ( self ): """simple docstring""" pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed class __lowerCamelCase : """simple docstring""" def __init__( self , UpperCAmelCase , UpperCAmelCase=0.0_01 , UpperCAmelCase=0 , **UpperCAmelCase ): """simple docstring""" _UpperCAmelCase = params _UpperCAmelCase = lr _UpperCAmelCase = weight_decay _UpperCAmelCase = kwargs class __lowerCamelCase : """simple docstring""" def __init__( self , UpperCAmelCase , UpperCAmelCase=None , UpperCAmelCase=0 , **UpperCAmelCase ): """simple docstring""" _UpperCAmelCase = optimizer _UpperCAmelCase = total_num_steps _UpperCAmelCase = warmup_num_steps _UpperCAmelCase = kwargs
39
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import KarrasVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" __UpperCAmelCase : UNetaDModel __UpperCAmelCase : KarrasVeScheduler def __init__( self : Union[str, Any] ,_a : UNetaDModel ,_a : KarrasVeScheduler ): '''simple docstring''' super().__init__() self.register_modules(unet=_a ,scheduler=_a ) @torch.no_grad() def __call__( self : List[Any] ,_a : int = 1 ,_a : int = 50 ,_a : Optional[Union[torch.Generator, List[torch.Generator]]] = None ,_a : Optional[str] = "pil" ,_a : bool = True ,**_a : List[Any] ,): '''simple docstring''' _a : Any = self.unet.config.sample_size _a : Optional[int] = (batch_size, 3, img_size, img_size) _a : Dict = self.unet # sample x_0 ~ N(0, sigma_0^2 * I) _a : Dict = randn_tensor(_a ,generator=_a ,device=self.device ) * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(_a ) for t in self.progress_bar(self.scheduler.timesteps ): # here sigma_t == t_i from the paper _a : Optional[int] = self.scheduler.schedule[t] _a : List[str] = self.scheduler.schedule[t - 1] if t > 0 else 0 # 1. Select temporarily increased noise level sigma_hat # 2. Add new noise to move from sample_i to sample_hat _a, _a : List[Any] = self.scheduler.add_noise_to_input(_a ,_a ,generator=_a ) # 3. Predict the noise residual given the noise magnitude `sigma_hat` # The model inputs and output are adjusted by following eq. (213) in [1]. _a : Optional[int] = (sigma_hat / 2) * model((sample_hat + 1) / 2 ,sigma_hat / 2 ).sample # 4. Evaluate dx/dt at sigma_hat # 5. Take Euler step from sigma to sigma_prev _a : Tuple = self.scheduler.step(_a ,_a ,_a ,_a ) if sigma_prev != 0: # 6. Apply 2nd order correction # The model inputs and output are adjusted by following eq. (213) in [1]. _a : Optional[int] = (sigma_prev / 2) * model((step_output.prev_sample + 1) / 2 ,sigma_prev / 2 ).sample _a : Optional[Any] = self.scheduler.step_correct( _a ,_a ,_a ,_a ,step_output.prev_sample ,step_output['derivative'] ,) _a : Dict = step_output.prev_sample _a : Tuple = (sample / 2 + 0.5).clamp(0 ,1 ) _a : Optional[Any] = sample.cpu().permute(0 ,2 ,3 ,1 ).numpy() if output_type == "pil": _a : List[str] = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
271
0
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging __SCREAMING_SNAKE_CASE =logging.get_logger(__name__) __SCREAMING_SNAKE_CASE ={ "Visual-Attention-Network/van-base": ( "https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json" ), } class UpperCamelCase ( lowercase_ ): lowercase = 'van' def __init__( self ,__UpperCamelCase=224 ,__UpperCamelCase=3 ,__UpperCamelCase=[7, 3, 3, 3] ,__UpperCamelCase=[4, 2, 2, 2] ,__UpperCamelCase=[64, 128, 320, 512] ,__UpperCamelCase=[3, 3, 12, 3] ,__UpperCamelCase=[8, 8, 4, 4] ,__UpperCamelCase="gelu" ,__UpperCamelCase=0.02 ,__UpperCamelCase=1e-6 ,__UpperCamelCase=1e-2 ,__UpperCamelCase=0.0 ,__UpperCamelCase=0.0 ,**__UpperCamelCase ,) -> Union[str, Any]: '''simple docstring''' super().__init__(**__UpperCamelCase ) lowercase_ : List[str] = image_size lowercase_ : Any = num_channels lowercase_ : Dict = patch_sizes lowercase_ : Optional[int] = strides lowercase_ : Any = hidden_sizes lowercase_ : List[str] = depths lowercase_ : Any = mlp_ratios lowercase_ : List[str] = hidden_act lowercase_ : Tuple = initializer_range lowercase_ : Tuple = layer_norm_eps lowercase_ : int = layer_scale_init_value lowercase_ : List[Any] = drop_path_rate lowercase_ : Any = dropout_rate
321
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot import BlenderbotTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __SCREAMING_SNAKE_CASE =logging.get_logger(__name__) __SCREAMING_SNAKE_CASE ={ "vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_config_file": "tokenizer_config.json", } __SCREAMING_SNAKE_CASE ={ "vocab_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json"}, "merges_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt"}, "tokenizer_config_file": { "facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json" }, } __SCREAMING_SNAKE_CASE ={"facebook/blenderbot-3B": 128} class UpperCamelCase ( lowercase_ ): lowercase = VOCAB_FILES_NAMES lowercase = PRETRAINED_VOCAB_FILES_MAP lowercase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase = ['input_ids', 'attention_mask'] lowercase = BlenderbotTokenizer def __init__( self ,__UpperCamelCase=None ,__UpperCamelCase=None ,__UpperCamelCase=None ,__UpperCamelCase="replace" ,__UpperCamelCase="<s>" ,__UpperCamelCase="</s>" ,__UpperCamelCase="</s>" ,__UpperCamelCase="<s>" ,__UpperCamelCase="<unk>" ,__UpperCamelCase="<pad>" ,__UpperCamelCase="<mask>" ,__UpperCamelCase=False ,__UpperCamelCase=True ,**__UpperCamelCase ,) -> Optional[int]: '''simple docstring''' super().__init__( __UpperCamelCase ,__UpperCamelCase ,tokenizer_file=__UpperCamelCase ,errors=__UpperCamelCase ,bos_token=__UpperCamelCase ,eos_token=__UpperCamelCase ,sep_token=__UpperCamelCase ,cls_token=__UpperCamelCase ,unk_token=__UpperCamelCase ,pad_token=__UpperCamelCase ,mask_token=__UpperCamelCase ,add_prefix_space=__UpperCamelCase ,trim_offsets=__UpperCamelCase ,**__UpperCamelCase ,) lowercase_ : Optional[int] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space' ,__UpperCamelCase ) != add_prefix_space: lowercase_ : Union[str, Any] = getattr(__UpperCamelCase ,pre_tok_state.pop('type' ) ) lowercase_ : Any = add_prefix_space lowercase_ : Tuple = pre_tok_class(**__UpperCamelCase ) lowercase_ : int = add_prefix_space lowercase_ : Any = 'post_processor' lowercase_ : Optional[Any] = getattr(self.backend_tokenizer ,__UpperCamelCase ,__UpperCamelCase ) if tokenizer_component_instance: lowercase_ : Tuple = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: lowercase_ : str = tuple(state['sep'] ) if "cls" in state: lowercase_ : Union[str, Any] = tuple(state['cls'] ) lowercase_ : str = False if state.get('add_prefix_space' ,__UpperCamelCase ) != add_prefix_space: lowercase_ : Dict = add_prefix_space lowercase_ : int = True if state.get('trim_offsets' ,__UpperCamelCase ) != trim_offsets: lowercase_ : Optional[Any] = trim_offsets lowercase_ : Tuple = True if changes_to_apply: lowercase_ : Union[str, Any] = getattr(__UpperCamelCase ,state.pop('type' ) ) lowercase_ : Union[str, Any] = component_class(**__UpperCamelCase ) setattr(self.backend_tokenizer ,__UpperCamelCase ,__UpperCamelCase ) @property # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.mask_token with Roberta->Blenderbot, RoBERTa->Blenderbot def _UpperCAmelCase ( self ) -> str: '''simple docstring''' if self._mask_token is None: if self.verbose: logger.error('Using mask_token, but it is not set yet.' ) return None return str(self._mask_token ) @mask_token.setter def _UpperCAmelCase ( self ,__UpperCamelCase ) -> Tuple: '''simple docstring''' lowercase_ : Any = AddedToken(__UpperCamelCase ,lstrip=__UpperCamelCase ,rstrip=__UpperCamelCase ) if isinstance(__UpperCamelCase ,__UpperCamelCase ) else value lowercase_ : str = value def _UpperCAmelCase ( self ,*__UpperCamelCase ,**__UpperCamelCase ) -> BatchEncoding: '''simple docstring''' lowercase_ : Optional[int] = kwargs.get('is_split_into_words' ,__UpperCamelCase ) assert self.add_prefix_space or not is_split_into_words, ( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*__UpperCamelCase ,**__UpperCamelCase ) def _UpperCAmelCase ( self ,*__UpperCamelCase ,**__UpperCamelCase ) -> BatchEncoding: '''simple docstring''' lowercase_ : List[str] = kwargs.get('is_split_into_words' ,__UpperCamelCase ) assert self.add_prefix_space or not is_split_into_words, ( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._encode_plus(*__UpperCamelCase ,**__UpperCamelCase ) def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase = None ) -> Tuple[str]: '''simple docstring''' lowercase_ : Any = self._tokenizer.model.save(__UpperCamelCase ,name=__UpperCamelCase ) return tuple(__UpperCamelCase ) def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase = None ) -> List[int]: '''simple docstring''' lowercase_ : int = [self.sep_token_id] lowercase_ : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase = None ) -> Any: '''simple docstring''' return token_ids_a + [self.eos_token_id] def _UpperCAmelCase ( self ,__UpperCamelCase ) -> List[int]: '''simple docstring''' lowercase_ : Optional[Any] = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(' ' + text ) else: # Generated responses should contain them already. inputs.append(__UpperCamelCase ) lowercase_ : Dict = ' '.join(__UpperCamelCase ) lowercase_ : str = self.encode(__UpperCamelCase ) if len(__UpperCamelCase ) > self.model_max_length: lowercase_ : List[str] = input_ids[-self.model_max_length :] logger.warning(f'''Trimmed input from conversation as it was longer than {self.model_max_length} tokens.''' ) return input_ids
321
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCAmelCase__ = { '''configuration_bloom''': ['''BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BloomConfig''', '''BloomOnnxConfig'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''BloomTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BloomForCausalLM''', '''BloomModel''', '''BloomPreTrainedModel''', '''BloomForSequenceClassification''', '''BloomForTokenClassification''', '''BloomForQuestionAnswering''', ] if TYPE_CHECKING: from .configuration_bloom import BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP, BloomConfig, BloomOnnxConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bloom_fast import BloomTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bloom import ( BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST, BloomForCausalLM, BloomForQuestionAnswering, BloomForSequenceClassification, BloomForTokenClassification, BloomModel, BloomPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
130
import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = ['''model.decoder.embed_positions.weights'''] def __lowerCamelCase ( lowerCamelCase__ ): """simple docstring""" if "emb" in name: lowercase__ : int = name.replace("emb" , "model.decoder.embed_tokens" ) if "transformer" in name: lowercase__ : Any = name.replace("transformer" , "model.decoder" ) if "cross_attention" in name: lowercase__ : int = name.replace("cross_attention" , "encoder_attn" ) if "linear1" in name: lowercase__ : int = name.replace("linear1" , "fc1" ) if "linear2" in name: lowercase__ : int = name.replace("linear2" , "fc2" ) if "norm1" in name: lowercase__ : Union[str, Any] = name.replace("norm1" , "self_attn_layer_norm" ) if "norm_cross" in name: lowercase__ : Union[str, Any] = name.replace("norm_cross" , "encoder_attn_layer_norm" ) if "norm2" in name: lowercase__ : Dict = name.replace("norm2" , "final_layer_norm" ) if "out_norm" in name: lowercase__ : Dict = name.replace("out_norm" , "model.decoder.layer_norm" ) if "linears" in name: lowercase__ : Union[str, Any] = name.replace("linears" , "lm_heads" ) if "condition_provider.conditioners.description.output_proj" in name: lowercase__ : Union[str, Any] = name.replace("condition_provider.conditioners.description.output_proj" , "enc_to_dec_proj" ) return name def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" lowercase__ : Optional[Any] = list(state_dict.keys() ) lowercase__ : Dict = {} for key in keys: lowercase__ : Tuple = state_dict.pop(lowerCamelCase__ ) lowercase__ : Union[str, Any] = rename_keys(lowerCamelCase__ ) if "in_proj_weight" in key: # split fused qkv proj lowercase__ : Optional[int] = val[:hidden_size, :] lowercase__ : Optional[int] = val[hidden_size : 2 * hidden_size, :] lowercase__ : List[Any] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: lowercase__ : Union[str, Any] = val else: lowercase__ : List[Any] = val return state_dict, enc_dec_proj_state_dict def __lowerCamelCase ( lowerCamelCase__ ): """simple docstring""" if checkpoint == "small": # default config values lowercase__ : Optional[Any] = 1_024 lowercase__ : int = 24 lowercase__ : Optional[Any] = 16 elif checkpoint == "medium": lowercase__ : str = 1_536 lowercase__ : Union[str, Any] = 48 lowercase__ : Optional[int] = 24 elif checkpoint == "large": lowercase__ : Tuple = 2_048 lowercase__ : Union[str, Any] = 48 lowercase__ : Dict = 32 else: raise ValueError(F"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) lowercase__ : int = MusicgenDecoderConfig( hidden_size=lowerCamelCase__ , ffn_dim=hidden_size * 4 , num_hidden_layers=lowerCamelCase__ , num_attention_heads=lowerCamelCase__ , ) return config @torch.no_grad() def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__="cpu" ): """simple docstring""" lowercase__ : List[Any] = MusicGen.get_pretrained(lowerCamelCase__ , device=lowerCamelCase__ ) lowercase__ : str = decoder_config_from_checkpoint(lowerCamelCase__ ) lowercase__ : Optional[Any] = fairseq_model.lm.state_dict() lowercase__ , lowercase__ : Tuple = rename_state_dict( lowerCamelCase__ , hidden_size=decoder_config.hidden_size ) lowercase__ : str = TaEncoderModel.from_pretrained("t5-base" ) lowercase__ : Tuple = EncodecModel.from_pretrained("facebook/encodec_32khz" ) lowercase__ : List[str] = MusicgenForCausalLM(lowerCamelCase__ ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection lowercase__ , lowercase__ : List[str] = decoder.load_state_dict(lowerCamelCase__ , strict=lowerCamelCase__ ) for key in missing_keys.copy(): if key.startswith(("text_encoder", "audio_encoder") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(lowerCamelCase__ ) if len(lowerCamelCase__ ) > 0: raise ValueError(F"""Missing key(s) in state_dict: {missing_keys}""" ) if len(lowerCamelCase__ ) > 0: raise ValueError(F"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model lowercase__ : Any = MusicgenForConditionalGeneration(text_encoder=lowerCamelCase__ , audio_encoder=lowerCamelCase__ , decoder=lowerCamelCase__ ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(lowerCamelCase__ ) # check we can do a forward pass lowercase__ : List[str] = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) lowercase__ : Any = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): lowercase__ : List[str] = model(input_ids=lowerCamelCase__ , decoder_input_ids=lowerCamelCase__ ).logits if logits.shape != (8, 1, 2_048): raise ValueError("Incorrect shape for logits" ) # now construct the processor lowercase__ : List[Any] = AutoTokenizer.from_pretrained("t5-base" ) lowercase__ : Dict = AutoFeatureExtractor.from_pretrained("facebook/encodec_32khz" , padding_side="left" ) lowercase__ : Optional[Any] = MusicgenProcessor(feature_extractor=lowerCamelCase__ , tokenizer=lowerCamelCase__ ) # set the appropriate bos/pad token ids lowercase__ : List[Any] = 2_048 lowercase__ : List[Any] = 2_048 # set other default generation config params lowercase__ : str = int(30 * audio_encoder.config.frame_rate ) lowercase__ : List[Any] = True lowercase__ : Dict = 3.0 if pytorch_dump_folder is not None: Path(lowerCamelCase__ ).mkdir(exist_ok=lowerCamelCase__ ) logger.info(F"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(lowerCamelCase__ ) processor.save_pretrained(lowerCamelCase__ ) if repo_id: logger.info(F"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(lowerCamelCase__ ) processor.push_to_hub(lowerCamelCase__ ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint''', default='''small''', type=str, help='''Checkpoint size of the MusicGen model you\'d like to convert. Can be one of: `[\'small\', \'medium\', \'large\']`.''', ) parser.add_argument( '''--pytorch_dump_folder''', required=True, default=None, type=str, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) parser.add_argument( '''--device''', default='''cpu''', type=str, help='''Torch device to run the conversion, either cpu or cuda.''' ) lowerCAmelCase__ = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
130
1
class UpperCamelCase : '''simple docstring''' def __init__( self , UpperCamelCase_ = "" , UpperCamelCase_ = False ): # Mapping from the first character of the prefix of the node lowercase_ :dict[str, RadixNode] = {} # A node will be a leaf if the tree contains its word lowercase_ :str = is_leaf lowercase_ :Tuple = prefix def UpperCamelCase ( self , UpperCamelCase_ ): lowercase_ :Any = 0 for q, w in zip(self.prefix , UpperCamelCase_ ): if q != w: break x += 1 return self.prefix[:x], self.prefix[x:], word[x:] def UpperCamelCase ( self , UpperCamelCase_ ): for word in words: self.insert(UpperCamelCase_ ) def UpperCamelCase ( self , UpperCamelCase_ ): # Case 1: If the word is the prefix of the node # Solution: We set the current node as leaf if self.prefix == word: lowercase_ :Tuple = True # Case 2: The node has no edges that have a prefix to the word # Solution: We create an edge from the current node to a new one # containing the word elif word[0] not in self.nodes: lowercase_ :Optional[Any] = RadixNode(prefix=UpperCamelCase_ , is_leaf=UpperCamelCase_ ) else: lowercase_ :Tuple = self.nodes[word[0]] lowercase_ , lowercase_ , lowercase_ :List[str] = incoming_node.match( UpperCamelCase_ ) # Case 3: The node prefix is equal to the matching # Solution: We insert remaining word on the next node if remaining_prefix == "": self.nodes[matching_string[0]].insert(UpperCamelCase_ ) # Case 4: The word is greater equal to the matching # Solution: Create a node in between both nodes, change # prefixes and add the new node for the remaining word else: lowercase_ :Optional[int] = remaining_prefix lowercase_ :Optional[Any] = self.nodes[matching_string[0]] lowercase_ :Optional[Any] = RadixNode(UpperCamelCase_ , UpperCamelCase_ ) lowercase_ :List[str] = aux_node if remaining_word == "": lowercase_ :str = True else: self.nodes[matching_string[0]].insert(UpperCamelCase_ ) def UpperCamelCase ( self , UpperCamelCase_ ): lowercase_ :List[Any] = self.nodes.get(word[0] , UpperCamelCase_ ) if not incoming_node: return False else: lowercase_ , lowercase_ , lowercase_ :Union[str, Any] = incoming_node.match( UpperCamelCase_ ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # This applies when the word and the prefix are equal elif remaining_word == "": return incoming_node.is_leaf # We have word remaining so we check the next node else: return incoming_node.find(UpperCamelCase_ ) def UpperCamelCase ( self , UpperCamelCase_ ): lowercase_ :List[Any] = self.nodes.get(word[0] , UpperCamelCase_ ) if not incoming_node: return False else: lowercase_ , lowercase_ , lowercase_ :int = incoming_node.match( UpperCamelCase_ ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # We have word remaining so we check the next node elif remaining_word != "": return incoming_node.delete(UpperCamelCase_ ) else: # If it is not a leaf, we don't have to delete if not incoming_node.is_leaf: return False else: # We delete the nodes if no edges go from it if len(incoming_node.nodes ) == 0: del self.nodes[word[0]] # We merge the current node with its only child if len(self.nodes ) == 1 and not self.is_leaf: lowercase_ :Optional[int] = list(self.nodes.values() )[0] lowercase_ :Optional[int] = merging_node.is_leaf self.prefix += merging_node.prefix lowercase_ :Dict = merging_node.nodes # If there is more than 1 edge, we just mark it as non-leaf elif len(incoming_node.nodes ) > 1: lowercase_ :Optional[int] = False # If there is 1 edge, we merge it with its child else: lowercase_ :Optional[int] = list(incoming_node.nodes.values() )[0] lowercase_ :Dict = merging_node.is_leaf incoming_node.prefix += merging_node.prefix lowercase_ :Optional[Any] = merging_node.nodes return True def UpperCamelCase ( self , UpperCamelCase_ = 0 ): if self.prefix != "": print('''-''' * height , self.prefix , ''' (leaf)''' if self.is_leaf else '''''' ) for value in self.nodes.values(): value.print_tree(height + 1 ) def UpperCamelCase ( ) -> bool: '''simple docstring''' lowercase_ :Optional[int] = '''banana bananas bandana band apple all beast'''.split() lowercase_ :Optional[Any] = RadixNode() root.insert_many(_a ) assert all(root.find(_a ) for word in words ) assert not root.find('''bandanas''' ) assert not root.find('''apps''' ) root.delete('''all''' ) assert not root.find('''all''' ) root.delete('''banana''' ) assert not root.find('''banana''' ) assert root.find('''bananas''' ) return True def UpperCamelCase ( ) -> None: '''simple docstring''' assert test_trie() def UpperCamelCase ( ) -> None: '''simple docstring''' lowercase_ :List[Any] = RadixNode() lowercase_ :int = '''banana bananas bandanas bandana band apple all beast'''.split() root.insert_many(_a ) print('''Words:''' , _a ) print('''Tree:''' ) root.print_tree() if __name__ == "__main__": main()
252
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 UpperCamelCase : '''simple docstring''' lowercase : Dict =MBartConfig lowercase : Union[str, Any] ={} lowercase : Optional[int] ="""gelu""" def __init__( self , UpperCamelCase_ , UpperCamelCase_=13 , UpperCamelCase_=7 , UpperCamelCase_=True , UpperCamelCase_=False , UpperCamelCase_=99 , UpperCamelCase_=32 , UpperCamelCase_=2 , UpperCamelCase_=4 , UpperCamelCase_=37 , UpperCamelCase_=0.1 , UpperCamelCase_=0.1 , UpperCamelCase_=20 , UpperCamelCase_=2 , UpperCamelCase_=1 , UpperCamelCase_=0 , ): lowercase_ :int = parent lowercase_ :Any = batch_size lowercase_ :Any = seq_length lowercase_ :Union[str, Any] = is_training lowercase_ :Optional[Any] = use_labels lowercase_ :List[str] = vocab_size lowercase_ :Union[str, Any] = hidden_size lowercase_ :Optional[Any] = num_hidden_layers lowercase_ :Optional[int] = num_attention_heads lowercase_ :Any = intermediate_size lowercase_ :str = hidden_dropout_prob lowercase_ :List[Any] = attention_probs_dropout_prob lowercase_ :Union[str, Any] = max_position_embeddings lowercase_ :str = eos_token_id lowercase_ :List[Any] = pad_token_id lowercase_ :List[str] = bos_token_id def UpperCamelCase ( self ): lowercase_ :Optional[int] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) lowercase_ :Tuple = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) lowercase_ :Optional[Any] = tf.concat([input_ids, eos_tensor] , axis=1 ) lowercase_ :Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase_ :List[Any] = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) lowercase_ :Optional[Any] = prepare_mbart_inputs_dict(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) return config, inputs_dict def UpperCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ ): lowercase_ :Tuple = TFMBartModel(config=UpperCamelCase_ ).get_decoder() lowercase_ :Any = inputs_dict['''input_ids'''] lowercase_ :List[Any] = input_ids[:1, :] lowercase_ :List[Any] = inputs_dict['''attention_mask'''][:1, :] lowercase_ :str = inputs_dict['''head_mask'''] lowercase_ :List[str] = 1 # first forward pass lowercase_ :Any = model(UpperCamelCase_ , attention_mask=UpperCamelCase_ , head_mask=UpperCamelCase_ , use_cache=UpperCamelCase_ ) lowercase_ , lowercase_ :int = outputs.to_tuple() lowercase_ :List[Any] = past_key_values[1] def UpperCamelCase ( _a , _a , _a , _a=None , _a=None , _a=None , _a=None , _a=None , ) -> int: '''simple docstring''' if attention_mask is None: lowercase_ :Dict = tf.cast(tf.math.not_equal(_a , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: lowercase_ :Optional[int] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: lowercase_ :Any = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: lowercase_ :Optional[int] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: lowercase_ :Any = 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 UpperCamelCase ( lowercase__ , lowercase__ , unittest.TestCase ): '''simple docstring''' lowercase : Optional[Any] =(TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else () lowercase : Optional[Any] =(TFMBartForConditionalGeneration,) if is_tf_available() else () lowercase : Optional[Any] =( { """conversational""": TFMBartForConditionalGeneration, """feature-extraction""": TFMBartModel, """summarization""": TFMBartForConditionalGeneration, """text2text-generation""": TFMBartForConditionalGeneration, """translation""": TFMBartForConditionalGeneration, } if is_tf_available() else {} ) lowercase : Optional[Any] =True lowercase : Optional[Any] =False lowercase : List[str] =False def UpperCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): if pipeline_test_casse_name != "FeatureExtractionPipelineTests": # Exception encountered when calling layer '...' return True return False def UpperCamelCase ( self ): lowercase_ :Optional[int] = TFMBartModelTester(self ) lowercase_ :str = ConfigTester(self , config_class=UpperCamelCase_ ) def UpperCamelCase ( self ): self.config_tester.run_common_tests() def UpperCamelCase ( self ): lowercase_ :str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*UpperCamelCase_ ) @require_sentencepiece @require_tokenizers @require_tf class UpperCamelCase ( unittest.TestCase ): '''simple docstring''' lowercase : List[str] =[ """ UN Chief Says There Is No Military Solution in Syria""", ] lowercase : Optional[int] =[ """Şeful ONU declară că nu există o soluţie militară în Siria""", ] lowercase : Any ="""facebook/mbart-large-en-ro""" @cached_property def UpperCamelCase ( self ): return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def UpperCamelCase ( self ): lowercase_ :Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def UpperCamelCase ( self , **UpperCamelCase_ ): lowercase_ :Any = self.translate_src_text(**UpperCamelCase_ ) self.assertListEqual(self.expected_text , UpperCamelCase_ ) def UpperCamelCase ( self , **UpperCamelCase_ ): lowercase_ :Optional[Any] = self.tokenizer(self.src_text , **UpperCamelCase_ , return_tensors='''tf''' ) lowercase_ :Union[str, Any] = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 ) lowercase_ :Any = self.tokenizer.batch_decode(UpperCamelCase_ , skip_special_tokens=UpperCamelCase_ ) return generated_words @slow def UpperCamelCase ( self ): self._assert_generated_batch_equal_expected()
252
1
import os def A ( ) -> Any: '''simple docstring''' UpperCamelCase = os.path.dirname(os.path.realpath(lowercase ) ) UpperCamelCase = os.path.join(lowercase , 'triangle.txt' ) with open(lowercase ) as f: UpperCamelCase = f.readlines() UpperCamelCase = [] for line in triangle: UpperCamelCase = [] for number in line.strip().split(' ' ): numbers_from_line.append(int(lowercase ) ) a.append(lowercase ) for i in range(1 , len(lowercase ) ): for j in range(len(a[i] ) ): UpperCamelCase = a[i - 1][j] if j != len(a[i - 1] ) else 0 UpperCamelCase = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(lowercase , lowercase ) return max(a[-1] ) if __name__ == "__main__": print(solution())
222
def A ( lowercase , lowercase , lowercase , lowercase , lowercase ) -> int: '''simple docstring''' if index == number_of_items: return 0 UpperCamelCase = 0 UpperCamelCase = 0 UpperCamelCase = knapsack(lowercase , lowercase , lowercase , lowercase , index + 1 ) if weights[index] <= max_weight: UpperCamelCase = values[index] + knapsack( lowercase , lowercase , lowercase , max_weight - weights[index] , index + 1 ) return max(lowercase , lowercase ) if __name__ == "__main__": import doctest doctest.testmod()
222
1
def lowerCAmelCase_ ( __UpperCAmelCase: Dict = 100 ) -> int: UpperCamelCase__ : int = 0 UpperCamelCase__ : Tuple = 0 for i in range(1 , n + 1 ): sum_of_squares += i**2 sum_of_ints += i return sum_of_ints**2 - sum_of_squares if __name__ == "__main__": print(F'''{solution() = }''')
352
from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def lowerCAmelCase_ ( ) -> List[str]: UpperCamelCase__ : List[str] = { '''repo_name''': ['''test_repo1''', '''test_repo2''', '''test_repo3'''], '''path''': ['''test_1.py''', '''test_2.py''', '''unit_test.py'''], '''content''': ['''a ''' * 20, '''a ''' * 30, '''b ''' * 7], } UpperCamelCase__ : Dict = Dataset.from_dict(__UpperCAmelCase ) return dataset class lowercase__ ( __lowerCamelCase ): '''simple docstring''' def UpperCamelCase__ ( self ) -> Any: """simple docstring""" UpperCamelCase__ : List[Any] = get_dataset() UpperCamelCase__ : List[str] = make_duplicate_clusters(__magic_name__, 0.85 ) self.assertEqual(len(duplicate_clusters[0] ), 2 ) def UpperCamelCase__ ( self ) -> str: """simple docstring""" UpperCamelCase__ : List[Any] = get_dataset() UpperCamelCase__ ,UpperCamelCase__ : Dict = deduplicate_dataset(__magic_name__ ) self.assertEqual(len(__magic_name__ ), 2 ) print(__magic_name__ ) self.assertEqual(duplicate_clusters[0][0]['''copies'''], 2 ) self.assertEqual(duplicate_clusters[0][0]['''is_extreme'''], __magic_name__ )
247
0
import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger UpperCAmelCase__ : Any = get_logger(__name__) class UpperCAmelCase ( enum.Enum ): '''simple docstring''' __UpperCamelCase : List[str] = '''all_checks''' __UpperCamelCase : str = '''basic_checks''' __UpperCamelCase : int = '''no_checks''' class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def lowerCamelCase__ ( a , a , a=None ) -> Union[str, Any]: if expected_checksums is None: logger.info('''Unable to verify checksums.''' ) return if len(set(a ) - set(a ) ) > 0: raise ExpectedMoreDownloadedFiles(str(set(a ) - set(a ) ) ) if len(set(a ) - set(a ) ) > 0: raise UnexpectedDownloadedFile(str(set(a ) - set(a ) ) ) _A: Tuple = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] _A: Tuple = ''' for ''' + verification_name if verification_name is not None else '''''' if len(a ) > 0: raise NonMatchingChecksumError( f"""Checksums didn't match{for_verification_name}:\n""" f"""{bad_urls}\n""" '''Set `verification_mode=\'no_checks\'` to skip checksums verification and ignore this error''' ) logger.info('''All the checksums matched successfully''' + for_verification_name ) class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' def lowerCamelCase__ ( a , a ) -> Any: if expected_splits is None: logger.info('''Unable to verify splits sizes.''' ) return if len(set(a ) - set(a ) ) > 0: raise ExpectedMoreSplits(str(set(a ) - set(a ) ) ) if len(set(a ) - set(a ) ) > 0: raise UnexpectedSplits(str(set(a ) - set(a ) ) ) _A: Dict = [ {'''expected''': expected_splits[name], '''recorded''': recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(a ) > 0: raise NonMatchingSplitsSizesError(str(a ) ) logger.info('''All the splits matched successfully.''' ) def lowerCamelCase__ ( a , a = True ) -> dict: if record_checksum: _A: str = shaaaa() with open(a , '''rb''' ) as f: for chunk in iter(lambda: f.read(1 << 20 ) , B'''''' ): m.update(a ) _A: Any = m.hexdigest() else: _A: List[Any] = None return {"num_bytes": os.path.getsize(a ), "checksum": checksum} def lowerCamelCase__ ( a ) -> Optional[int]: if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
121
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from .config import config_command_parser from .config_args import default_config_file, load_config_from_file # noqa: F401 from .default import default_command_parser from .update import update_command_parser def lowerCamelCase__ ( a=None ) -> int: _A: Union[str, Any] = argparse.ArgumentParser(add_help=a , allow_abbrev=a ) # The main config parser _A: str = config_command_parser(a ) # The subparser to add commands to _A: str = config_parser.add_subparsers(title='''subcommands''' , dest='''subcommand''' ) # Then add other parsers with the parent parser default_command_parser(a , parents=[parent_parser] ) update_command_parser(a , parents=[parent_parser] ) return config_parser def lowerCamelCase__ ( ) -> Union[str, Any]: _A: Any = get_config_parser() _A: Tuple = config_parser.parse_args() if not hasattr(a , '''func''' ): config_parser.print_help() exit(1 ) # Run args.func(a ) if __name__ == "__main__": main()
121
1
"""simple docstring""" import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __a ( lowerCAmelCase__ , unittest.TestCase ): SCREAMING_SNAKE_CASE__ : List[str] = DDIMPipeline SCREAMING_SNAKE_CASE__ : Dict = UNCONDITIONAL_IMAGE_GENERATION_PARAMS SCREAMING_SNAKE_CASE__ : Union[str, Any] = PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "latents", "callback", "callback_steps", } SCREAMING_SNAKE_CASE__ : Tuple = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS SCREAMING_SNAKE_CASE__ : int = False def snake_case_ ( self ): torch.manual_seed(0 ) _lowerCamelCase = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) _lowerCamelCase = DDIMScheduler() _lowerCamelCase = {'unet': unet, 'scheduler': scheduler} return components def snake_case_ ( self , a__ , a__=0 ): if str(a__ ).startswith('mps' ): _lowerCamelCase = torch.manual_seed(a__ ) else: _lowerCamelCase = torch.Generator(device=a__ ).manual_seed(a__ ) _lowerCamelCase = { 'batch_size': 1, 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def snake_case_ ( self ): _lowerCamelCase = 'cpu' _lowerCamelCase = self.get_dummy_components() _lowerCamelCase = self.pipeline_class(**a__ ) pipe.to(a__ ) pipe.set_progress_bar_config(disable=a__ ) _lowerCamelCase = self.get_dummy_inputs(a__ ) _lowerCamelCase = pipe(**a__ ).images _lowerCamelCase = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) _lowerCamelCase = np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) _lowerCamelCase = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(a__ , 1e-3 ) def snake_case_ ( self ): super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def snake_case_ ( self ): super().test_save_load_local(expected_max_difference=3e-3 ) def snake_case_ ( self ): super().test_save_load_optional_components(expected_max_difference=3e-3 ) def snake_case_ ( self ): super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class __a ( unittest.TestCase ): def snake_case_ ( self ): _lowerCamelCase = 'google/ddpm-cifar10-32' _lowerCamelCase = UNetaDModel.from_pretrained(a__ ) _lowerCamelCase = DDIMScheduler() _lowerCamelCase = DDIMPipeline(unet=a__ , scheduler=a__ ) ddim.to(a__ ) ddim.set_progress_bar_config(disable=a__ ) _lowerCamelCase = torch.manual_seed(0 ) _lowerCamelCase = ddim(generator=a__ , eta=0.0 , output_type='numpy' ).images _lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) _lowerCamelCase = np.array([0.1723, 0.1617, 0.1600, 0.1626, 0.1497, 0.1513, 0.1505, 0.1442, 0.1453] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def snake_case_ ( self ): _lowerCamelCase = 'google/ddpm-ema-bedroom-256' _lowerCamelCase = UNetaDModel.from_pretrained(a__ ) _lowerCamelCase = DDIMScheduler.from_pretrained(a__ ) _lowerCamelCase = DDIMPipeline(unet=a__ , scheduler=a__ ) ddpm.to(a__ ) ddpm.set_progress_bar_config(disable=a__ ) _lowerCamelCase = torch.manual_seed(0 ) _lowerCamelCase = ddpm(generator=a__ , output_type='numpy' ).images _lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) _lowerCamelCase = np.array([0.0060, 0.0201, 0.0344, 0.0024, 0.0018, 0.0002, 0.0022, 0.0000, 0.0069] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
365
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING A_ : int =logging.get_logger(__name__) A_ : Tuple ={ """ut/deta""": """https://huggingface.co/ut/deta/resolve/main/config.json""", } class __a ( lowerCAmelCase__ ): SCREAMING_SNAKE_CASE__ : int = "deta" SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , a__=None , a__=9_00 , a__=20_48 , a__=6 , a__=20_48 , a__=8 , a__=6 , a__=10_24 , a__=8 , a__=0.0 , a__=True , a__="relu" , a__=2_56 , a__=0.1 , a__=0.0 , a__=0.0 , a__=0.02 , a__=1.0 , a__=True , a__=False , a__="sine" , a__=5 , a__=4 , a__=4 , a__=True , a__=3_00 , a__=True , a__=True , a__=1 , a__=5 , a__=2 , a__=1 , a__=1 , a__=5 , a__=2 , a__=0.1 , a__=0.25 , **a__ , ): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) _lowerCamelCase = CONFIG_MAPPING['resnet'](out_features=['stage2', 'stage3', 'stage4'] ) else: if isinstance(a__ , a__ ): _lowerCamelCase = backbone_config.pop('model_type' ) _lowerCamelCase = CONFIG_MAPPING[backbone_model_type] _lowerCamelCase = config_class.from_dict(a__ ) _lowerCamelCase = backbone_config _lowerCamelCase = num_queries _lowerCamelCase = max_position_embeddings _lowerCamelCase = d_model _lowerCamelCase = encoder_ffn_dim _lowerCamelCase = encoder_layers _lowerCamelCase = encoder_attention_heads _lowerCamelCase = decoder_ffn_dim _lowerCamelCase = decoder_layers _lowerCamelCase = decoder_attention_heads _lowerCamelCase = dropout _lowerCamelCase = attention_dropout _lowerCamelCase = activation_dropout _lowerCamelCase = activation_function _lowerCamelCase = init_std _lowerCamelCase = init_xavier_std _lowerCamelCase = encoder_layerdrop _lowerCamelCase = auxiliary_loss _lowerCamelCase = position_embedding_type # deformable attributes _lowerCamelCase = num_feature_levels _lowerCamelCase = encoder_n_points _lowerCamelCase = decoder_n_points _lowerCamelCase = two_stage _lowerCamelCase = two_stage_num_proposals _lowerCamelCase = with_box_refine _lowerCamelCase = assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError('If two_stage is True, with_box_refine must be True.' ) # Hungarian matcher _lowerCamelCase = class_cost _lowerCamelCase = bbox_cost _lowerCamelCase = giou_cost # Loss coefficients _lowerCamelCase = mask_loss_coefficient _lowerCamelCase = dice_loss_coefficient _lowerCamelCase = bbox_loss_coefficient _lowerCamelCase = giou_loss_coefficient _lowerCamelCase = eos_coefficient _lowerCamelCase = focal_alpha super().__init__(is_encoder_decoder=a__ , **a__ ) @property def snake_case_ ( self ): return self.encoder_attention_heads @property def snake_case_ ( self ): return self.d_model def snake_case_ ( self ): _lowerCamelCase = copy.deepcopy(self.__dict__ ) _lowerCamelCase = self.backbone_config.to_dict() _lowerCamelCase = self.__class__.model_type return output
80
0
'''simple docstring''' import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> List[Any]: UpperCamelCase = ("""dense.weight""", """attention.self.query""", """attention.self.key""", """attention.self.value""") UpperCamelCase = ( ("""layer.""", """layer_"""), ("""word_embeddings.weight""", """word_embeddings"""), ("""position_embeddings.weight""", """position_embeddings"""), ("""token_type_embeddings.weight""", """token_type_embeddings"""), (""".""", """/"""), ("""LayerNorm/weight""", """LayerNorm/gamma"""), ("""LayerNorm/bias""", """LayerNorm/beta"""), ("""weight""", """kernel"""), ) if not os.path.isdir(__UpperCamelCase ): os.makedirs(__UpperCamelCase ) UpperCamelCase = model.state_dict() def to_tf_var_name(__UpperCamelCase ): for patt, repl in iter(__UpperCamelCase ): UpperCamelCase = name.replace(__UpperCamelCase , __UpperCamelCase ) return F"bert/{name}" def create_tf_var(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): UpperCamelCase = tf.dtypes.as_dtype(tensor.dtype ) UpperCamelCase = tf.get_variable(dtype=__UpperCamelCase , shape=tensor.shape , name=__UpperCamelCase , initializer=tf.zeros_initializer() ) session.run(tf.variables_initializer([tf_var] ) ) session.run(__UpperCamelCase ) return tf_var tf.reset_default_graph() with tf.Session() as session: for var_name in state_dict: UpperCamelCase = to_tf_var_name(__UpperCamelCase ) UpperCamelCase = state_dict[var_name].numpy() if any(x in var_name for x in tensors_to_transpose ): UpperCamelCase = torch_tensor.T UpperCamelCase = create_tf_var(tensor=__UpperCamelCase , name=__UpperCamelCase , session=__UpperCamelCase ) tf.keras.backend.set_value(__UpperCamelCase , __UpperCamelCase ) UpperCamelCase = session.run(__UpperCamelCase ) print(F"Successfully created {tf_name}: {np.allclose(__UpperCamelCase , __UpperCamelCase )}" ) UpperCamelCase = tf.train.Saver(tf.trainable_variables() ) saver.save(__UpperCamelCase , os.path.join(__UpperCamelCase , model_name.replace("""-""" , """_""" ) + """.ckpt""" ) ) def lowercase__ ( __UpperCamelCase=None )-> Tuple: UpperCamelCase = argparse.ArgumentParser() parser.add_argument("""--model_name""" , type=__UpperCamelCase , required=__UpperCamelCase , help="""model name e.g. bert-base-uncased""" ) parser.add_argument( """--cache_dir""" , type=__UpperCamelCase , default=__UpperCamelCase , required=__UpperCamelCase , help="""Directory containing pytorch model""" ) parser.add_argument("""--pytorch_model_path""" , type=__UpperCamelCase , required=__UpperCamelCase , help="""/path/to/<pytorch-model-name>.bin""" ) parser.add_argument("""--tf_cache_dir""" , type=__UpperCamelCase , required=__UpperCamelCase , help="""Directory in which to save tensorflow model""" ) UpperCamelCase = parser.parse_args(__UpperCamelCase ) UpperCamelCase = BertModel.from_pretrained( pretrained_model_name_or_path=args.model_name , state_dict=torch.load(args.pytorch_model_path ) , cache_dir=args.cache_dir , ) convert_pytorch_checkpoint_to_tf(model=__UpperCamelCase , ckpt_dir=args.tf_cache_dir , model_name=args.model_name ) if __name__ == "__main__": main()
321
'''simple docstring''' def lowercase__ ( __UpperCamelCase = 4000000 )-> int: UpperCamelCase = [] UpperCamelCase ,UpperCamelCase = 0, 1 while b <= n: if b % 2 == 0: even_fibs.append(__UpperCamelCase ) UpperCamelCase ,UpperCamelCase = b, a + b return sum(__UpperCamelCase ) if __name__ == "__main__": print(f'{solution() = }')
321
1
"""simple docstring""" def _UpperCAmelCase ( __lowerCamelCase : str ) -> int: _snake_case = hex_num.strip() if not hex_num: raise ValueError('''No value was passed to the function''' ) _snake_case = hex_num[0] == '''-''' if is_negative: _snake_case = hex_num[1:] try: _snake_case = int(__lowerCamelCase , 16 ) except ValueError: raise ValueError('''Invalid value was passed to the function''' ) _snake_case = '''''' while int_num > 0: _snake_case = str(int_num % 2 ) + bin_str int_num >>= 1 return int(('''-''' + bin_str) if is_negative else bin_str ) if __name__ == "__main__": import doctest doctest.testmod()
40
"""simple docstring""" import requests from bsa import BeautifulSoup def _UpperCAmelCase ( __lowerCamelCase : str , __lowerCamelCase : dict ) -> str: _snake_case = BeautifulSoup(requests.get(__lowerCamelCase , params=__lowerCamelCase ).content , '''html.parser''' ) _snake_case = soup.find('''div''' , attrs={'''class''': '''gs_ri'''} ) _snake_case = div.find('''div''' , attrs={'''class''': '''gs_fl'''} ).find_all('''a''' ) return anchors[2].get_text() if __name__ == "__main__": UpperCAmelCase__ = { 'title': ( 'Precisely geometry controlled microsupercapacitors for ultrahigh areal ' 'capacitance, volumetric capacitance, and energy density' ), 'journal': 'Chem. Mater.', 'volume': 30, 'pages': '3979-3990', 'year': 2018, 'hl': 'en', } print(get_citation('https://scholar.google.com/scholar_lookup', params=params))
40
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_funnel import FunnelTokenizer UpperCAmelCase : str = logging.get_logger(__name__) UpperCAmelCase : Any = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} UpperCAmelCase : Tuple = [ "small", "small-base", "medium", "medium-base", "intermediate", "intermediate-base", "large", "large-base", "xlarge", "xlarge-base", ] UpperCAmelCase : Optional[int] = { "vocab_file": { "funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt", "funnel-transformer/small-base": "https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt", "funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt", "funnel-transformer/medium-base": ( "https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt" ), "funnel-transformer/intermediate": ( "https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt" ), "funnel-transformer/intermediate-base": ( "https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt" ), "funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt", "funnel-transformer/large-base": "https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt", "funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt", "funnel-transformer/xlarge-base": ( "https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json", "funnel-transformer/small-base": ( "https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json" ), "funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json", "funnel-transformer/medium-base": ( "https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json" ), "funnel-transformer/intermediate": ( "https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json" ), "funnel-transformer/intermediate-base": ( "https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json" ), "funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json", "funnel-transformer/large-base": ( "https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json" ), "funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json", "funnel-transformer/xlarge-base": ( "https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json" ), }, } UpperCAmelCase : Optional[Any] = {f"""funnel-transformer/{name}""": 5_12 for name in _model_names} UpperCAmelCase : Optional[Any] = {f"""funnel-transformer/{name}""": {"do_lower_case": True} for name in _model_names} class __lowercase ( a_ ): """simple docstring""" UpperCamelCase : int = VOCAB_FILES_NAMES UpperCamelCase : Tuple = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Dict = PRETRAINED_INIT_CONFIGURATION UpperCamelCase : Any = FunnelTokenizer UpperCamelCase : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : int = 2 def __init__( self , A=None , A=None , A=True , A="<unk>" , A="<sep>" , A="<pad>" , A="<cls>" , A="<mask>" , A="<s>" , A="</s>" , A=True , A=True , A=None , A="##" , **A , ) -> Tuple: '''simple docstring''' super().__init__( A , tokenizer_file=A , do_lower_case=A , unk_token=A , sep_token=A , pad_token=A , cls_token=A , mask_token=A , bos_token=A , eos_token=A , clean_text=A , tokenize_chinese_chars=A , strip_accents=A , wordpieces_prefix=A , **A , ) lowerCamelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , A ) != do_lower_case or normalizer_state.get("""strip_accents""" , A ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , A ) != tokenize_chinese_chars ): lowerCamelCase = getattr(A , normalizer_state.pop("""type""" ) ) lowerCamelCase = do_lower_case lowerCamelCase = strip_accents lowerCamelCase = tokenize_chinese_chars lowerCamelCase = normalizer_class(**A ) lowerCamelCase = do_lower_case def __A ( self , A , A=None ) -> Tuple: '''simple docstring''' lowerCamelCase = [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 __A ( self , A , A = None ) -> List[int]: '''simple docstring''' lowerCamelCase = [self.sep_token_id] lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __A ( self , A , A = None ) -> Tuple[str]: '''simple docstring''' lowerCamelCase = self._tokenizer.model.save(A , name=A ) return tuple(A )
252
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : List[str] = { "configuration_x_clip": [ "XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "XCLIPConfig", "XCLIPTextConfig", "XCLIPVisionConfig", ], "processing_x_clip": ["XCLIPProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ "XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "XCLIPModel", "XCLIPPreTrainedModel", "XCLIPTextModel", "XCLIPVisionModel", ] if TYPE_CHECKING: from .configuration_x_clip import ( XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, XCLIPConfig, XCLIPTextConfig, XCLIPVisionConfig, ) from .processing_x_clip import XCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_x_clip import ( XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, XCLIPModel, XCLIPPreTrainedModel, XCLIPTextModel, XCLIPVisionModel, ) else: import sys UpperCAmelCase : Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
252
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel @require_tf class lowerCamelCase__ : '''simple docstring''' _lowerCamelCase = MBartConfig _lowerCamelCase = {} _lowerCamelCase = '''gelu''' def __init__( self ,lowerCamelCase_ ,lowerCamelCase_=1_3 ,lowerCamelCase_=7 ,lowerCamelCase_=True ,lowerCamelCase_=False ,lowerCamelCase_=9_9 ,lowerCamelCase_=3_2 ,lowerCamelCase_=2 ,lowerCamelCase_=4 ,lowerCamelCase_=3_7 ,lowerCamelCase_=0.1 ,lowerCamelCase_=0.1 ,lowerCamelCase_=2_0 ,lowerCamelCase_=2 ,lowerCamelCase_=1 ,lowerCamelCase_=0 ,) -> int: A = parent A = batch_size A = seq_length A = is_training A = use_labels A = vocab_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = eos_token_id A = pad_token_id A = bos_token_id def UpperCamelCase__ ( self ) -> Optional[int]: A = ids_tensor([self.batch_size, self.seq_length - 1] ,self.vocab_size ) A = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) ,1 ) A = tf.concat([input_ids, eos_tensor] ,axis=1 ) A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = 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 ,) A = prepare_mbart_inputs_dict(_a ,_a ,_a ) return config, inputs_dict def UpperCamelCase__ ( self ,lowerCamelCase_ ,lowerCamelCase_ ) -> List[str]: A = TFMBartModel(config=_a ).get_decoder() A = inputs_dict["""input_ids"""] A = input_ids[:1, :] A = inputs_dict["""attention_mask"""][:1, :] A = inputs_dict["""head_mask"""] A = 1 # first forward pass A = model(_a ,attention_mask=_a ,head_mask=_a ,use_cache=_a ) A , A = outputs.to_tuple() A = past_key_values[1] def _A ( _a : Dict , _a : Optional[int] , _a : Optional[int] , _a : Optional[Any]=None , _a : Tuple=None , _a : Dict=None , _a : Tuple=None , _a : Tuple=None , ): """simple docstring""" if attention_mask is None: A = tf.cast(tf.math.not_equal(UpperCamelCase__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: A = 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: A = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: A = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: A = 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 lowerCamelCase__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' _lowerCamelCase = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else () _lowerCamelCase = (TFMBartForConditionalGeneration,) if is_tf_available() else () _lowerCamelCase = ( { '''conversational''': TFMBartForConditionalGeneration, '''feature-extraction''': TFMBartModel, '''summarization''': TFMBartForConditionalGeneration, '''text2text-generation''': TFMBartForConditionalGeneration, '''translation''': TFMBartForConditionalGeneration, } if is_tf_available() else {} ) _lowerCamelCase = True _lowerCamelCase = False _lowerCamelCase = False def UpperCamelCase__ ( self ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ) -> Optional[int]: if pipeline_test_casse_name != "FeatureExtractionPipelineTests": # Exception encountered when calling layer '...' return True return False def UpperCamelCase__ ( self ) -> Optional[int]: A = TFMBartModelTester(self ) A = ConfigTester(self ,config_class=_a ) def UpperCamelCase__ ( self ) -> Any: self.config_tester.run_common_tests() def UpperCamelCase__ ( self ) -> Optional[Any]: A = 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 lowerCamelCase__ ( unittest.TestCase ): '''simple docstring''' _lowerCamelCase = [ ''' UN Chief Says There Is No Military Solution in Syria''', ] _lowerCamelCase = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', ] _lowerCamelCase = '''facebook/mbart-large-en-ro''' @cached_property def UpperCamelCase__ ( self ) -> Union[str, Any]: return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def UpperCamelCase__ ( self ) -> Optional[int]: A = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def UpperCamelCase__ ( self ,**lowerCamelCase_ ) -> Tuple: A = self.translate_src_text(**_a ) self.assertListEqual(self.expected_text ,_a ) def UpperCamelCase__ ( self ,**lowerCamelCase_ ) -> int: A = self.tokenizer(self.src_text ,**_a ,return_tensors="""tf""" ) A = self.model.generate( model_inputs.input_ids ,attention_mask=model_inputs.attention_mask ,num_beams=2 ) A = self.tokenizer.batch_decode(_a ,skip_special_tokens=_a ) return generated_words @slow def UpperCamelCase__ ( self ) -> List[str]: self._assert_generated_batch_equal_expected()
363
"""simple docstring""" import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class lowerCamelCase__ ( SCREAMING_SNAKE_CASE ): '''simple docstring''' _lowerCamelCase = ['''image_processor''', '''tokenizer'''] _lowerCamelCase = '''OwlViTImageProcessor''' _lowerCamelCase = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__( self ,lowerCamelCase_=None ,lowerCamelCase_=None ,**lowerCamelCase_ ) -> Tuple: A = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" ,lowerCamelCase_ ,) A = kwargs.pop("""feature_extractor""" ) A = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(lowerCamelCase_ ,lowerCamelCase_ ) def __call__( self ,lowerCamelCase_=None ,lowerCamelCase_=None ,lowerCamelCase_=None ,lowerCamelCase_="max_length" ,lowerCamelCase_="np" ,**lowerCamelCase_ ) -> Optional[Any]: if text is None and query_images is None and images is None: raise ValueError( """You have to specify at least one text or query image or image. All three cannot be none.""" ) if text is not None: if isinstance(lowerCamelCase_ ,lowerCamelCase_ ) or (isinstance(lowerCamelCase_ ,lowerCamelCase_ ) and not isinstance(text[0] ,lowerCamelCase_ )): A = [self.tokenizer(lowerCamelCase_ ,padding=lowerCamelCase_ ,return_tensors=lowerCamelCase_ ,**lowerCamelCase_ )] elif isinstance(lowerCamelCase_ ,lowerCamelCase_ ) and isinstance(text[0] ,lowerCamelCase_ ): A = [] # Maximum number of queries across batch A = max([len(lowerCamelCase_ ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(lowerCamelCase_ ) != max_num_queries: A = t + [""" """] * (max_num_queries - len(lowerCamelCase_ )) A = self.tokenizer(lowerCamelCase_ ,padding=lowerCamelCase_ ,return_tensors=lowerCamelCase_ ,**lowerCamelCase_ ) encodings.append(lowerCamelCase_ ) else: raise TypeError("""Input text should be a string, a list of strings or a nested list of strings""" ) if return_tensors == "np": A = np.concatenate([encoding["""input_ids"""] for encoding in encodings] ,axis=0 ) A = np.concatenate([encoding["""attention_mask"""] for encoding in encodings] ,axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp A = jnp.concatenate([encoding["""input_ids"""] for encoding in encodings] ,axis=0 ) A = jnp.concatenate([encoding["""attention_mask"""] for encoding in encodings] ,axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch A = torch.cat([encoding["""input_ids"""] for encoding in encodings] ,dim=0 ) A = torch.cat([encoding["""attention_mask"""] for encoding in encodings] ,dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf A = tf.stack([encoding["""input_ids"""] for encoding in encodings] ,axis=0 ) A = tf.stack([encoding["""attention_mask"""] for encoding in encodings] ,axis=0 ) else: raise ValueError("""Target return tensor type could not be returned""" ) A = BatchEncoding() A = input_ids A = attention_mask if query_images is not None: A = BatchEncoding() A = self.image_processor( lowerCamelCase_ ,return_tensors=lowerCamelCase_ ,**lowerCamelCase_ ).pixel_values A = query_pixel_values if images is not None: A = self.image_processor(lowerCamelCase_ ,return_tensors=lowerCamelCase_ ,**lowerCamelCase_ ) if text is not None and images is not None: A = image_features.pixel_values return encoding elif query_images is not None and images is not None: A = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**lowerCamelCase_ ) ,tensor_type=lowerCamelCase_ ) def UpperCamelCase__ ( self ,*lowerCamelCase_ ,**lowerCamelCase_ ) -> int: return self.image_processor.post_process(*lowerCamelCase_ ,**lowerCamelCase_ ) def UpperCamelCase__ ( self ,*lowerCamelCase_ ,**lowerCamelCase_ ) -> Optional[Any]: return self.image_processor.post_process_object_detection(*lowerCamelCase_ ,**lowerCamelCase_ ) def UpperCamelCase__ ( self ,*lowerCamelCase_ ,**lowerCamelCase_ ) -> Optional[Any]: return self.image_processor.post_process_image_guided_detection(*lowerCamelCase_ ,**lowerCamelCase_ ) def UpperCamelCase__ ( self ,*lowerCamelCase_ ,**lowerCamelCase_ ) -> List[str]: return self.tokenizer.batch_decode(*lowerCamelCase_ ,**lowerCamelCase_ ) def UpperCamelCase__ ( self ,*lowerCamelCase_ ,**lowerCamelCase_ ) -> List[str]: return self.tokenizer.decode(*lowerCamelCase_ ,**lowerCamelCase_ ) @property def UpperCamelCase__ ( self ) -> Union[str, Any]: warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" ,lowerCamelCase_ ,) return self.image_processor_class @property def UpperCamelCase__ ( self ) -> Union[str, Any]: warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" ,lowerCamelCase_ ,) return self.image_processor
77
0
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roberta import RobertaTokenizer __lowercase = logging.get_logger(__name__) __lowercase = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} __lowercase = { """vocab_file""": { """roberta-base""": """https://huggingface.co/roberta-base/resolve/main/vocab.json""", """roberta-large""": """https://huggingface.co/roberta-large/resolve/main/vocab.json""", """roberta-large-mnli""": """https://huggingface.co/roberta-large-mnli/resolve/main/vocab.json""", """distilroberta-base""": """https://huggingface.co/distilroberta-base/resolve/main/vocab.json""", """roberta-base-openai-detector""": """https://huggingface.co/roberta-base-openai-detector/resolve/main/vocab.json""", """roberta-large-openai-detector""": ( """https://huggingface.co/roberta-large-openai-detector/resolve/main/vocab.json""" ), }, """merges_file""": { """roberta-base""": """https://huggingface.co/roberta-base/resolve/main/merges.txt""", """roberta-large""": """https://huggingface.co/roberta-large/resolve/main/merges.txt""", """roberta-large-mnli""": """https://huggingface.co/roberta-large-mnli/resolve/main/merges.txt""", """distilroberta-base""": """https://huggingface.co/distilroberta-base/resolve/main/merges.txt""", """roberta-base-openai-detector""": """https://huggingface.co/roberta-base-openai-detector/resolve/main/merges.txt""", """roberta-large-openai-detector""": ( """https://huggingface.co/roberta-large-openai-detector/resolve/main/merges.txt""" ), }, """tokenizer_file""": { """roberta-base""": """https://huggingface.co/roberta-base/resolve/main/tokenizer.json""", """roberta-large""": """https://huggingface.co/roberta-large/resolve/main/tokenizer.json""", """roberta-large-mnli""": """https://huggingface.co/roberta-large-mnli/resolve/main/tokenizer.json""", """distilroberta-base""": """https://huggingface.co/distilroberta-base/resolve/main/tokenizer.json""", """roberta-base-openai-detector""": ( """https://huggingface.co/roberta-base-openai-detector/resolve/main/tokenizer.json""" ), """roberta-large-openai-detector""": ( """https://huggingface.co/roberta-large-openai-detector/resolve/main/tokenizer.json""" ), }, } __lowercase = { """roberta-base""": 512, """roberta-large""": 512, """roberta-large-mnli""": 512, """distilroberta-base""": 512, """roberta-base-openai-detector""": 512, """roberta-large-openai-detector""": 512, } class _A ( _a ): """simple docstring""" UpperCAmelCase : str = VOCAB_FILES_NAMES UpperCAmelCase : Any = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase : Any = ["""input_ids""", """attention_mask"""] UpperCAmelCase : int = RobertaTokenizer def __init__( self : Tuple , __UpperCAmelCase : Any=None , __UpperCAmelCase : str=None , __UpperCAmelCase : List[Any]=None , __UpperCAmelCase : List[Any]="replace" , __UpperCAmelCase : List[str]="<s>" , __UpperCAmelCase : int="</s>" , __UpperCAmelCase : List[str]="</s>" , __UpperCAmelCase : str="<s>" , __UpperCAmelCase : Dict="<unk>" , __UpperCAmelCase : Dict="<pad>" , __UpperCAmelCase : Dict="<mask>" , __UpperCAmelCase : int=False , __UpperCAmelCase : Dict=True , **__UpperCAmelCase : Dict , ): super().__init__( __UpperCAmelCase , __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , errors=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , add_prefix_space=__UpperCAmelCase , trim_offsets=__UpperCAmelCase , **__UpperCAmelCase , ) a : Union[str, Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()) if pre_tok_state.get("add_prefix_space" , __UpperCAmelCase) != add_prefix_space: a : Optional[Any] = getattr(__UpperCAmelCase , pre_tok_state.pop("type")) a : Optional[int] = add_prefix_space a : Dict = pre_tok_class(**__UpperCAmelCase) a : Tuple = add_prefix_space a : str = "post_processor" a : Dict = getattr(self.backend_tokenizer , __UpperCAmelCase , __UpperCAmelCase) if tokenizer_component_instance: a : Union[str, Any] = json.loads(tokenizer_component_instance.__getstate__()) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: a : int = tuple(state["sep"]) if "cls" in state: a : Any = tuple(state["cls"]) a : Dict = False if state.get("add_prefix_space" , __UpperCAmelCase) != add_prefix_space: a : Optional[int] = add_prefix_space a : int = True if state.get("trim_offsets" , __UpperCAmelCase) != trim_offsets: a : List[str] = trim_offsets a : List[str] = True if changes_to_apply: a : str = getattr(__UpperCAmelCase , state.pop("type")) a : Optional[int] = component_class(**__UpperCAmelCase) setattr(self.backend_tokenizer , __UpperCAmelCase , __UpperCAmelCase) @property def __snake_case ( self : List[Any]): if self._mask_token is None: if self.verbose: logger.error("Using mask_token, but it is not set yet.") return None return str(self._mask_token) @mask_token.setter def __snake_case ( self : int , __UpperCAmelCase : Any): a : Any = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase) if isinstance(__UpperCAmelCase , __UpperCAmelCase) else value a : str = value def __snake_case ( self : Dict , *__UpperCAmelCase : int , **__UpperCAmelCase : Tuple): a : Tuple = kwargs.get("is_split_into_words" , __UpperCAmelCase) assert self.add_prefix_space or not is_split_into_words, ( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*__UpperCAmelCase , **__UpperCAmelCase) def __snake_case ( self : Optional[int] , *__UpperCAmelCase : Dict , **__UpperCAmelCase : List[Any]): a : Dict = kwargs.get("is_split_into_words" , __UpperCAmelCase) assert self.add_prefix_space or not is_split_into_words, ( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._encode_plus(*__UpperCAmelCase , **__UpperCAmelCase) def __snake_case ( self : Any , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None): a : str = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase) return tuple(__UpperCAmelCase) def __snake_case ( self : Tuple , __UpperCAmelCase : Any , __UpperCAmelCase : Dict=None): a : List[Any] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def __snake_case ( self : List[str] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None): a : Tuple = [self.sep_token_id] a : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep) * [0]
40
"""simple docstring""" def _SCREAMING_SNAKE_CASE ( lowercase_ ) -> List[str]: A__ = len(lowercase_ ) while cur > 1: # Find the maximum number in arr A__ = arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi A__ = arr[mi::-1] + arr[mi + 1 : len(lowercase_ )] # Reverse whole list A__ = arr[cur - 1 :: -1] + arr[cur : len(lowercase_ )] cur -= 1 return arr if __name__ == "__main__": SCREAMING_SNAKE_CASE = input("Enter numbers separated by a comma:\n").strip() SCREAMING_SNAKE_CASE = [int(item) for item in user_input.split(",")] print(pancake_sort(unsorted))
247
0
import os import unicodedata 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 __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {'''vocab_file''': '''spiece.model'''} __UpperCAmelCase = { '''vocab_file''': { '''albert-base-v1''': '''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''', '''albert-large-v1''': '''https://huggingface.co/albert-large-v1/resolve/main/spiece.model''', '''albert-xlarge-v1''': '''https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model''', '''albert-xxlarge-v1''': '''https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model''', '''albert-base-v2''': '''https://huggingface.co/albert-base-v2/resolve/main/spiece.model''', '''albert-large-v2''': '''https://huggingface.co/albert-large-v2/resolve/main/spiece.model''', '''albert-xlarge-v2''': '''https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model''', '''albert-xxlarge-v2''': '''https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model''', } } __UpperCAmelCase = { '''albert-base-v1''': 5_12, '''albert-large-v1''': 5_12, '''albert-xlarge-v1''': 5_12, '''albert-xxlarge-v1''': 5_12, '''albert-base-v2''': 5_12, '''albert-large-v2''': 5_12, '''albert-xlarge-v2''': 5_12, '''albert-xxlarge-v2''': 5_12, } __UpperCAmelCase = '''▁''' class lowerCamelCase__ ( __lowercase ): _lowerCAmelCase = VOCAB_FILES_NAMES _lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : Dict , _a : Optional[int] , _a : Tuple=True , _a : Any=True , _a : List[Any]=False , _a : List[str]="[CLS]" , _a : List[Any]="[SEP]" , _a : List[str]="<unk>" , _a : Dict="[SEP]" , _a : Tuple="<pad>" , _a : str="[CLS]" , _a : List[str]="[MASK]" , _a : Optional[Dict[str, Any]] = None , **_a : Tuple , ): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. a__: List[Any] =( AddedToken(snake_case_ , lstrip=snake_case_ , rstrip=snake_case_ , normalized=snake_case_ ) if isinstance(snake_case_ , snake_case_ ) else mask_token ) a__: int ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=snake_case_ , remove_space=snake_case_ , keep_accents=snake_case_ , bos_token=snake_case_ , eos_token=snake_case_ , unk_token=snake_case_ , sep_token=snake_case_ , pad_token=snake_case_ , cls_token=snake_case_ , mask_token=snake_case_ , sp_model_kwargs=self.sp_model_kwargs , **snake_case_ , ) a__: List[str] =do_lower_case a__: Optional[int] =remove_space a__: int =keep_accents a__: Dict =vocab_file a__: List[str] =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(snake_case_ ) @property def _lowerCamelCase ( self : Optional[Any] ): return len(self.sp_model ) def _lowerCamelCase ( self : List[Any] ): a__: Optional[Any] ={self.convert_ids_to_tokens(snake_case_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ): a__: Union[str, Any] =self.__dict__.copy() a__: Optional[int] =None return state def __setstate__( self : Any , _a : Optional[int] ): a__: Tuple =d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): a__: Union[str, Any] ={} a__: List[str] =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _lowerCamelCase ( self : Optional[Any] , _a : Union[str, Any] ): if self.remove_space: a__: int =''' '''.join(inputs.strip().split() ) else: a__: Union[str, Any] =inputs a__: int =outputs.replace("``" , "\"" ).replace("\'\'" , "\"" ) if not self.keep_accents: a__: Dict =unicodedata.normalize("NFKD" , snake_case_ ) a__: str =''''''.join([c for c in outputs if not unicodedata.combining(snake_case_ )] ) if self.do_lower_case: a__: Optional[Any] =outputs.lower() return outputs def _lowerCamelCase ( self : Optional[int] , _a : str ): a__: List[Any] =self.preprocess_text(snake_case_ ) a__: Any =self.sp_model.encode(snake_case_ , out_type=snake_case_ ) a__: str =[] for piece in pieces: if len(snake_case_ ) > 1 and piece[-1] == str("," ) and piece[-2].isdigit(): a__: Tuple =self.sp_model.EncodeAsPieces(piece[:-1].replace(snake_case_ , "" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: a__: int =cur_pieces[1:] else: a__: str =cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(snake_case_ ) else: new_pieces.append(snake_case_ ) return new_pieces def _lowerCamelCase ( self : List[Any] , _a : Dict ): return self.sp_model.PieceToId(snake_case_ ) def _lowerCamelCase ( self : int , _a : Tuple ): return self.sp_model.IdToPiece(snake_case_ ) def _lowerCamelCase ( self : Union[str, Any] , _a : Union[str, Any] ): a__: Any =[] a__: Optional[Any] ='''''' a__: Dict =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(snake_case_ ) + token a__: Optional[int] =True a__: int =[] else: current_sub_tokens.append(snake_case_ ) a__: Any =False out_string += self.sp_model.decode(snake_case_ ) return out_string.strip() def _lowerCamelCase ( self : List[Any] , _a : List[int] , _a : Optional[List[int]] = None ): a__: Tuple =[self.sep_token_id] a__: Any =[self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _lowerCamelCase ( self : str , _a : List[int] , _a : Optional[List[int]] = None , _a : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=snake_case_ , token_ids_a=snake_case_ , already_has_special_tokens=snake_case_ ) if token_ids_a is not None: return [1] + ([0] * len(snake_case_ )) + [1] + ([0] * len(snake_case_ )) + [1] return [1] + ([0] * len(snake_case_ )) + [1] def _lowerCamelCase ( self : Union[str, Any] , _a : List[int] , _a : Optional[List[int]] = None ): a__: Union[str, Any] =[self.sep_token_id] a__: 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 ) * [0] + len(token_ids_a + sep ) * [1] def _lowerCamelCase ( self : str , _a : str , _a : Optional[str] = None ): if not os.path.isdir(snake_case_ ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return a__: Optional[Any] =os.path.join( snake_case_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , snake_case_ ) elif not os.path.isfile(self.vocab_file ): with open(snake_case_ , "wb" ) as fi: a__: int =self.sp_model.serialized_model_proto() fi.write(snake_case_ ) return (out_vocab_file,)
351
import json import os import torch from diffusers import UNetaDModel os.makedirs('''hub/hopper-medium-v2/unet/hor32''', exist_ok=True) os.makedirs('''hub/hopper-medium-v2/unet/hor128''', exist_ok=True) os.makedirs('''hub/hopper-medium-v2/value_function''', exist_ok=True) def __lowerCamelCase ( __magic_name__ : List[Any] ): if hor == 128: a__: Union[str, Any] =("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D") a__: Optional[int] =(32, 128, 256) a__: Tuple =("UpResnetBlock1D", "UpResnetBlock1D") elif hor == 32: a__: Tuple =("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D") a__: List[Any] =(32, 64, 128, 256) a__: List[str] =("UpResnetBlock1D", "UpResnetBlock1D", "UpResnetBlock1D") a__: Dict =torch.load(F"/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch" ) a__: Optional[int] =model.state_dict() a__: str ={ "down_block_types": down_block_types, "block_out_channels": block_out_channels, "up_block_types": up_block_types, "layers_per_block": 1, "use_timestep_embedding": True, "out_block_type": "OutConv1DBlock", "norm_num_groups": 8, "downsample_each_block": False, "in_channels": 14, "out_channels": 14, "extra_in_channels": 0, "time_embedding_type": "positional", "flip_sin_to_cos": False, "freq_shift": 1, "sample_size": 65_536, "mid_block_type": "MidResTemporalBlock1D", "act_fn": "mish", } a__: List[Any] =UNetaDModel(**__magic_name__ ) print(F"length of state dict: {len(state_dict.keys() )}" ) print(F"length of value function dict: {len(hf_value_function.state_dict().keys() )}" ) a__: Tuple =dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): a__: Dict =state_dict.pop(__magic_name__ ) hf_value_function.load_state_dict(__magic_name__ ) torch.save(hf_value_function.state_dict() , F"hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin" ) with open(F"hub/hopper-medium-v2/unet/hor{hor}/config.json" , "w" ) as f: json.dump(__magic_name__ , __magic_name__ ) def __lowerCamelCase ( ): a__: Union[str, Any] ={ "in_channels": 14, "down_block_types": ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D"), "up_block_types": (), "out_block_type": "ValueFunction", "mid_block_type": "ValueFunctionMidBlock1D", "block_out_channels": (32, 64, 128, 256), "layers_per_block": 1, "downsample_each_block": True, "sample_size": 65_536, "out_channels": 14, "extra_in_channels": 0, "time_embedding_type": "positional", "use_timestep_embedding": True, "flip_sin_to_cos": False, "freq_shift": 1, "norm_num_groups": 8, "act_fn": "mish", } a__: Union[str, Any] =torch.load("/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch" ) a__: Any =model a__: str =UNetaDModel(**__magic_name__ ) print(F"length of state dict: {len(state_dict.keys() )}" ) print(F"length of value function dict: {len(hf_value_function.state_dict().keys() )}" ) a__: List[str] =dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): a__: List[Any] =state_dict.pop(__magic_name__ ) hf_value_function.load_state_dict(__magic_name__ ) torch.save(hf_value_function.state_dict() , "hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin" ) with open("hub/hopper-medium-v2/value_function/config.json" , "w" ) as f: json.dump(__magic_name__ , __magic_name__ ) if __name__ == "__main__": unet(32) # unet(128) value_function()
42
0
'''simple docstring''' def lowerCamelCase ( UpperCAmelCase__ : Optional[int] ) -> str: if number > 0: raise ValueError("""input must be a negative integer""" ) lowercase_ : Dict = len(bin(__A )[3:] ) lowercase_ : Union[str, Any] = bin(abs(__A ) - (1 << binary_number_length) )[3:] lowercase_ : Optional[int] = ( ( """1""" + """0""" * (binary_number_length - len(__A )) + twos_complement_number ) if number < 0 else """0""" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
239
'''simple docstring''' from __future__ import annotations import math def _UpperCamelCase ( __A , __A , __A , __A , __A ) -> int: '''simple docstring''' if depth < 0: raise ValueError("Depth cannot be less than 0" ) if not scores: raise ValueError("Scores cannot be empty" ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 , node_index * 2 , __A , __A , __A ) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , __A , __A , __A ) , minimax(depth + 1 , node_index * 2 + 1 , __A , __A , __A ) , ) ) def _UpperCamelCase ( ) -> None: '''simple docstring''' UpperCamelCase__ = [90, 23, 6, 33, 21, 65, 123, 34423] UpperCamelCase__ = math.log(len(__A ) , 2 ) print(F'''Optimal value : {minimax(0 , 0 , __A , __A , __A )}''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
80
0
import argparse import logging import os import re import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, DataCollatorForLanguageModeling, PushToHubCallback, TFAutoModelForMaskedLM, create_optimizer, ) UpperCAmelCase_ = logging.getLogger(__name__) UpperCAmelCase_ = tf.data.AUTOTUNE def _UpperCamelCase ( ): '''simple docstring''' UpperCAmelCase__ = argparse.ArgumentParser(description="""Train a masked language model on TPU.""" ) parser.add_argument( """--pretrained_model_config""" , type=SCREAMING_SNAKE_CASE__ , default="""roberta-base""" , help="""The model config to use. Note that we don't copy the model's weights, only the config!""" , ) parser.add_argument( """--tokenizer""" , type=SCREAMING_SNAKE_CASE__ , default="""unigram-tokenizer-wikitext""" , help="""The name of the tokenizer to load. We use the pretrained tokenizer to initialize the model's vocab size.""" , ) parser.add_argument( """--per_replica_batch_size""" , type=SCREAMING_SNAKE_CASE__ , default=8 , help="""Batch size per TPU core.""" , ) parser.add_argument( """--no_tpu""" , action="""store_true""" , help="""If set, run on CPU and don't try to initialize a TPU. Useful for debugging on non-TPU instances.""" , ) parser.add_argument( """--tpu_name""" , type=SCREAMING_SNAKE_CASE__ , help="""Name of TPU resource to initialize. Should be blank on Colab, and 'local' on TPU VMs.""" , default="""local""" , ) parser.add_argument( """--tpu_zone""" , type=SCREAMING_SNAKE_CASE__ , help="""Google cloud zone that TPU resource is located in. Only used for non-Colab TPU nodes.""" , ) parser.add_argument( """--gcp_project""" , type=SCREAMING_SNAKE_CASE__ , help="""Google cloud project name. Only used for non-Colab TPU nodes.""" ) parser.add_argument( """--bfloat16""" , action="""store_true""" , help="""Use mixed-precision bfloat16 for training. This is the recommended lower-precision format for TPU.""" , ) parser.add_argument( """--train_dataset""" , type=SCREAMING_SNAKE_CASE__ , help="""Path to training dataset to load. If the path begins with `gs://`""" """ then the dataset will be loaded from a Google Cloud Storage bucket.""" , ) parser.add_argument( """--shuffle_buffer_size""" , type=SCREAMING_SNAKE_CASE__ , default=2**18 , help="""Size of the shuffle buffer (in samples)""" , ) parser.add_argument( """--eval_dataset""" , type=SCREAMING_SNAKE_CASE__ , help="""Path to evaluation dataset to load. If the path begins with `gs://`""" """ then the dataset will be loaded from a Google Cloud Storage bucket.""" , ) parser.add_argument( """--num_epochs""" , type=SCREAMING_SNAKE_CASE__ , default=1 , help="""Number of epochs to train for.""" , ) parser.add_argument( """--learning_rate""" , type=SCREAMING_SNAKE_CASE__ , default=1e-4 , help="""Learning rate to use for training.""" , ) parser.add_argument( """--weight_decay_rate""" , type=SCREAMING_SNAKE_CASE__ , default=1e-3 , help="""Weight decay rate to use for training.""" , ) parser.add_argument( """--max_length""" , type=SCREAMING_SNAKE_CASE__ , default=512 , help="""Maximum length of tokenized sequences. Should match the setting used in prepare_tfrecord_shards.py""" , ) parser.add_argument( """--mlm_probability""" , type=SCREAMING_SNAKE_CASE__ , default=0.15 , help="""Fraction of tokens to mask during training.""" , ) parser.add_argument("""--output_dir""" , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help="""Path to save model checkpoints to.""" ) parser.add_argument("""--hub_model_id""" , type=SCREAMING_SNAKE_CASE__ , help="""Model ID to upload to on the Hugging Face Hub.""" ) UpperCAmelCase__ = parser.parse_args() return args def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' try: if args.tpu_name: UpperCAmelCase__ = tf.distribute.cluster_resolver.TPUClusterResolver( args.tpu_name , zone=args.tpu_zone , project=args.gcp_project ) else: UpperCAmelCase__ = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: raise RuntimeError( """Couldn't connect to TPU! Most likely you need to specify --tpu_name, --tpu_zone, or """ """--gcp_project. When running on a TPU VM, use --tpu_name local.""" ) tf.config.experimental_connect_to_cluster(SCREAMING_SNAKE_CASE__ ) tf.tpu.experimental.initialize_tpu_system(SCREAMING_SNAKE_CASE__ ) return tpu def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' UpperCAmelCase__ = 0 for file in file_list: UpperCAmelCase__ = file.split("""/""" )[-1] UpperCAmelCase__ = re.search(r"""-\d+-(\d+)\.tfrecord""" , SCREAMING_SNAKE_CASE__ ).group(1 ) UpperCAmelCase__ = int(SCREAMING_SNAKE_CASE__ ) num_samples += sample_count return num_samples def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=None ): '''simple docstring''' UpperCAmelCase__ = count_samples(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase__ = tf.data.Dataset.from_tensor_slices(SCREAMING_SNAKE_CASE__ ) if shuffle: UpperCAmelCase__ = dataset.shuffle(len(SCREAMING_SNAKE_CASE__ ) ) UpperCAmelCase__ = tf.data.TFRecordDataset(SCREAMING_SNAKE_CASE__ , num_parallel_reads=SCREAMING_SNAKE_CASE__ ) # TF can't infer the total sample count because it doesn't read all the records yet, so we assert it here UpperCAmelCase__ = dataset.apply(tf.data.experimental.assert_cardinality(SCREAMING_SNAKE_CASE__ ) ) UpperCAmelCase__ = dataset.map(SCREAMING_SNAKE_CASE__ , num_parallel_calls=SCREAMING_SNAKE_CASE__ ) if shuffle: assert shuffle_buffer_size is not None UpperCAmelCase__ = dataset.shuffle(args.shuffle_buffer_size ) UpperCAmelCase__ = dataset.batch(SCREAMING_SNAKE_CASE__ , drop_remainder=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase__ = dataset.map(SCREAMING_SNAKE_CASE__ , num_parallel_calls=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase__ = dataset.prefetch(SCREAMING_SNAKE_CASE__ ) return dataset def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): '''simple docstring''' if not args.no_tpu: UpperCAmelCase__ = initialize_tpu(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase__ = tf.distribute.TPUStrategy(SCREAMING_SNAKE_CASE__ ) else: UpperCAmelCase__ = tf.distribute.OneDeviceStrategy(device="""/gpu:0""" ) if args.bfloataa: tf.keras.mixed_precision.set_global_policy("""mixed_bfloat16""" ) UpperCAmelCase__ = AutoTokenizer.from_pretrained(args.tokenizer ) UpperCAmelCase__ = AutoConfig.from_pretrained(args.pretrained_model_config ) UpperCAmelCase__ = tokenizer.vocab_size UpperCAmelCase__ = tf.io.gfile.glob(os.path.join(args.train_dataset , """*.tfrecord""" ) ) if not training_records: raise ValueError(F'''No .tfrecord files found in {args.train_dataset}.''' ) UpperCAmelCase__ = tf.io.gfile.glob(os.path.join(args.eval_dataset , """*.tfrecord""" ) ) if not eval_records: raise ValueError(F'''No .tfrecord files found in {args.eval_dataset}.''' ) UpperCAmelCase__ = count_samples(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase__ = num_train_samples // (args.per_replica_batch_size * strategy.num_replicas_in_sync) UpperCAmelCase__ = steps_per_epoch * args.num_epochs with strategy.scope(): UpperCAmelCase__ = TFAutoModelForMaskedLM.from_config(SCREAMING_SNAKE_CASE__ ) model(model.dummy_inputs ) # Pass some dummy inputs through the model to ensure all the weights are built UpperCAmelCase__ , UpperCAmelCase__ = create_optimizer( num_train_steps=SCREAMING_SNAKE_CASE__ , num_warmup_steps=total_train_steps // 20 , init_lr=args.learning_rate , weight_decay_rate=args.weight_decay_rate , ) # Transformers models compute the right loss for their task by default when labels are passed, and will # use this for training unless you specify your own loss function in compile(). model.compile(optimizer=SCREAMING_SNAKE_CASE__ , metrics=["""accuracy"""] ) def decode_fn(SCREAMING_SNAKE_CASE__ : Optional[Any] ): UpperCAmelCase__ = { """input_ids""": tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), """attention_mask""": tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), } return tf.io.parse_single_example(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Many of the data collators in Transformers are TF-compilable when return_tensors == "tf", so we can # use their methods in our data pipeline. UpperCAmelCase__ = DataCollatorForLanguageModeling( tokenizer=SCREAMING_SNAKE_CASE__ , mlm_probability=args.mlm_probability , mlm=SCREAMING_SNAKE_CASE__ , return_tensors="""tf""" ) def mask_with_collator(SCREAMING_SNAKE_CASE__ : Optional[int] ): # TF really needs an isin() function UpperCAmelCase__ = ( ~tf.cast(batch["""attention_mask"""] , tf.bool ) | (batch["""input_ids"""] == tokenizer.cls_token_id) | (batch["""input_ids"""] == tokenizer.sep_token_id) ) UpperCAmelCase__ , UpperCAmelCase__ = data_collator.tf_mask_tokens( batch["""input_ids"""] , vocab_size=len(SCREAMING_SNAKE_CASE__ ) , mask_token_id=tokenizer.mask_token_id , special_tokens_mask=SCREAMING_SNAKE_CASE__ , ) return batch UpperCAmelCase__ = args.per_replica_batch_size * strategy.num_replicas_in_sync UpperCAmelCase__ = prepare_dataset( SCREAMING_SNAKE_CASE__ , decode_fn=SCREAMING_SNAKE_CASE__ , mask_fn=SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , shuffle=SCREAMING_SNAKE_CASE__ , shuffle_buffer_size=args.shuffle_buffer_size , ) UpperCAmelCase__ = prepare_dataset( SCREAMING_SNAKE_CASE__ , decode_fn=SCREAMING_SNAKE_CASE__ , mask_fn=SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , shuffle=SCREAMING_SNAKE_CASE__ , ) UpperCAmelCase__ = [] if args.hub_model_id: callbacks.append( PushToHubCallback(output_dir=args.output_dir , hub_model_id=args.hub_model_id , tokenizer=SCREAMING_SNAKE_CASE__ ) ) model.fit( SCREAMING_SNAKE_CASE__ , validation_data=SCREAMING_SNAKE_CASE__ , epochs=args.num_epochs , callbacks=SCREAMING_SNAKE_CASE__ , ) model.save_pretrained(args.output_dir ) if __name__ == "__main__": UpperCAmelCase_ = parse_args() main(args)
368
'''simple docstring''' import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) UpperCAmelCase_ = logging.getLogger(__name__) UpperCAmelCase_ = 'Hello world! cécé herlolip' UpperCAmelCase_ = namedtuple( 'BertAbsConfig', [ 'temp_dir', 'large', 'use_bert_emb', 'finetune_bert', 'encoder', 'share_emb', 'max_pos', 'enc_layers', 'enc_hidden_size', 'enc_heads', 'enc_ff_size', 'enc_dropout', 'dec_layers', 'dec_hidden_size', 'dec_heads', 'dec_ff_size', 'dec_dropout', ], ) def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple ): '''simple docstring''' UpperCAmelCase__ = BertAbsConfig( temp_dir=""".""" , finetune_bert=SCREAMING_SNAKE_CASE__ , large=SCREAMING_SNAKE_CASE__ , share_emb=SCREAMING_SNAKE_CASE__ , use_bert_emb=SCREAMING_SNAKE_CASE__ , encoder="""bert""" , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2048 , dec_dropout=0.2 , ) UpperCAmelCase__ = torch.load(SCREAMING_SNAKE_CASE__ , lambda SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : storage ) UpperCAmelCase__ = AbsSummarizer(SCREAMING_SNAKE_CASE__ , torch.device("""cpu""" ) , SCREAMING_SNAKE_CASE__ ) original.eval() UpperCAmelCase__ = BertAbsSummarizer(SCREAMING_SNAKE_CASE__ , torch.device("""cpu""" ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("""convert the model""" ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("""Make sure that the models' outputs are identical""" ) UpperCAmelCase__ = BertTokenizer.from_pretrained("""bert-base-uncased""" ) # prepare the model inputs UpperCAmelCase__ = tokenizer.encode("""This is sample éàalj'-.""" ) encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(SCREAMING_SNAKE_CASE__ )) ) UpperCAmelCase__ = torch.tensor(SCREAMING_SNAKE_CASE__ ).unsqueeze(0 ) UpperCAmelCase__ = tokenizer.encode("""This is sample 3 éàalj'-.""" ) decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(SCREAMING_SNAKE_CASE__ )) ) UpperCAmelCase__ = torch.tensor(SCREAMING_SNAKE_CASE__ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass UpperCAmelCase__ = encoder_input_ids UpperCAmelCase__ = decoder_input_ids UpperCAmelCase__ = UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = UpperCAmelCase__ = None UpperCAmelCase__ = UpperCAmelCase__ = None UpperCAmelCase__ = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical UpperCAmelCase__ = original(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )[0] UpperCAmelCase__ = original.generator(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase__ = new_model( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )[0] UpperCAmelCase__ = new_model.generator(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase__ = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(SCREAMING_SNAKE_CASE__ ) ) UpperCAmelCase__ = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(SCREAMING_SNAKE_CASE__ ) ) UpperCAmelCase__ = torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) if are_identical: logging.info("""all weights are equal up to 1e-3""" ) else: raise ValueError("""the weights are different. The new model is likely different from the original one.""" ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("""saving the model's state dictionary""" ) torch.save( new_model.state_dict() , """./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin""" ) if __name__ == "__main__": UpperCAmelCase_ = argparse.ArgumentParser() parser.add_argument( '--bertabs_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.', ) UpperCAmelCase_ = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
61
0
"""simple docstring""" import unittest from knapsack import knapsack as k class _A ( unittest.TestCase ): """simple docstring""" def __snake_case ( self : List[Any]): a : str = 0 a : Optional[int] = [0] a : Union[str, Any] = [0] a : Any = len(__UpperCAmelCase) self.assertEqual(k.knapsack(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase) , 0) a : List[str] = [60] a : str = [10] a : Optional[int] = len(__UpperCAmelCase) self.assertEqual(k.knapsack(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase) , 0) def __snake_case ( self : Optional[int]): a : Any = 3 a : str = [1, 2, 3] a : Tuple = [3, 2, 1] a : Any = len(__UpperCAmelCase) self.assertEqual(k.knapsack(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase) , 5) def __snake_case ( self : Tuple): a : int = 50 a : List[Any] = [60, 100, 120] a : Optional[int] = [10, 20, 30] a : str = len(__UpperCAmelCase) self.assertEqual(k.knapsack(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase) , 220) if __name__ == "__main__": unittest.main()
40
"""simple docstring""" from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def lowercase ( A_ , A_ , A_ = False )-> list[float]: '''simple docstring''' if radian_mode: return [magnitude * cos(A_ ), magnitude * sin(A_ )] return [magnitude * cos(radians(A_ ) ), magnitude * sin(radians(A_ ) )] def lowercase ( A_ , A_ , A_ = 10**-1 )-> bool: '''simple docstring''' a : NDArray[floataa] = cross(A_ , A_ ) a : float = sum(A_ ) return abs(A_ ) < eps if __name__ == "__main__": # Test to check if it works __lowercase = array( [ polar_force(7_18.4, 180 - 30), polar_force(8_79.54, 45), polar_force(100, -90), ] ) __lowercase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg __lowercase = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) __lowercase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg __lowercase = array([[0, -2000], [0, -1200], [0, 15600], [0, -12400]]) __lowercase = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
40
1
"""simple docstring""" from typing import List, Optional, Union import numpy as np from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ....feature_extraction_sequence_utils import SequenceFeatureExtractor from ....feature_extraction_utils import BatchFeature from ....file_utils import PaddingStrategy, TensorType from ....utils import logging lowercase__ : List[Any] = logging.get_logger(__name__) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" _SCREAMING_SNAKE_CASE = ["""input_features""", """attention_mask"""] def __init__( self : int , SCREAMING_SNAKE_CASE_ : Tuple=8_0 , SCREAMING_SNAKE_CASE_ : Optional[Any]=1_6_0_0_0 , SCREAMING_SNAKE_CASE_ : Optional[Any]=0.0 , SCREAMING_SNAKE_CASE_ : Optional[Any]=1_0 , SCREAMING_SNAKE_CASE_ : str=2_5 , SCREAMING_SNAKE_CASE_ : Optional[int]="hamming_window" , SCREAMING_SNAKE_CASE_ : List[Any]=3_2_7_6_8.0 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0.97 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=1.0 , SCREAMING_SNAKE_CASE_ : Tuple=True , SCREAMING_SNAKE_CASE_ : Tuple=True , SCREAMING_SNAKE_CASE_ : Any=False , **SCREAMING_SNAKE_CASE_ : Any , ): super().__init__(feature_size=SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , padding_value=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : str = feature_size lowerCAmelCase_ : Dict = sampling_rate lowerCAmelCase_ : List[Any] = padding_value lowerCAmelCase_ : Tuple = hop_length lowerCAmelCase_ : int = win_length lowerCAmelCase_ : Optional[int] = frame_signal_scale lowerCAmelCase_ : Dict = preemphasis_coeff lowerCAmelCase_ : Optional[Any] = mel_floor lowerCAmelCase_ : List[Any] = normalize_means lowerCAmelCase_ : List[Any] = normalize_vars lowerCAmelCase_ : Any = win_function lowerCAmelCase_ : Optional[Any] = return_attention_mask lowerCAmelCase_ : Optional[int] = win_length * sampling_rate // 1_0_0_0 lowerCAmelCase_ : Optional[int] = hop_length * sampling_rate // 1_0_0_0 lowerCAmelCase_ : List[str] = optimal_fft_length(self.sample_size ) lowerCAmelCase_ : str = (self.n_fft // 2) + 1 def SCREAMING_SNAKE_CASE__ ( self : str , SCREAMING_SNAKE_CASE_ : np.array ): if self.win_function == "hamming_window": lowerCAmelCase_ : List[Any] = window_function(window_length=self.sample_size , name=self.win_function , periodic=SCREAMING_SNAKE_CASE_ ) else: lowerCAmelCase_ : str = window_function(window_length=self.sample_size , name=self.win_function ) lowerCAmelCase_ : Dict = mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.feature_size , min_frequency=0.0 , max_frequency=self.sampling_rate / 2.0 , sampling_rate=self.sampling_rate , ) lowerCAmelCase_ : List[Any] = spectrogram( one_waveform * self.frame_signal_scale , window=SCREAMING_SNAKE_CASE_ , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , center=SCREAMING_SNAKE_CASE_ , preemphasis=self.preemphasis_coeff , mel_filters=SCREAMING_SNAKE_CASE_ , mel_floor=self.mel_floor , log_mel='log' , ) return msfc_features.T def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Tuple ): # make sure we normalize float32 arrays if self.normalize_means: lowerCAmelCase_ : int = x[:input_length].mean(axis=0 ) lowerCAmelCase_ : str = np.subtract(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if self.normalize_vars: lowerCAmelCase_ : int = x[:input_length].std(axis=0 ) lowerCAmelCase_ : List[str] = np.divide(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if input_length < x.shape[0]: lowerCAmelCase_ : str = padding_value # make sure array is in float32 lowerCAmelCase_ : List[Any] = x.astype(np.floataa ) return x def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : List[np.ndarray] , SCREAMING_SNAKE_CASE_ : Optional[np.ndarray] = None ): lowerCAmelCase_ : Union[str, Any] = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [self._normalize_one(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.padding_value ) for x, n in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )] def __call__( self : List[str] , SCREAMING_SNAKE_CASE_ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , SCREAMING_SNAKE_CASE_ : Union[bool, str, PaddingStrategy] = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[bool] = None , SCREAMING_SNAKE_CASE_ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE_ : Optional[int] = None , **SCREAMING_SNAKE_CASE_ : Union[str, Any] , ): if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F"The model corresponding to this feature extractor: {self} was trained using a sampling rate of" F" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with" F" {self.sampling_rate} and not {sampling_rate}." ) else: logger.warning( 'It is strongly recommended to pass the ``sampling_rate`` argument to this function. ' 'Failing to do so can result in silent errors that might be hard to debug.' ) lowerCAmelCase_ : List[Any] = isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(F"Only mono-channel audio is supported for input to {self}" ) lowerCAmelCase_ : Tuple = is_batched_numpy or ( isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: lowerCAmelCase_ : Optional[Any] = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ): lowerCAmelCase_ : List[Any] = np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) elif isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): lowerCAmelCase_ : Union[str, Any] = raw_speech.astype(np.floataa ) # always return batch if not is_batched: lowerCAmelCase_ : str = [raw_speech] # extract fbank features lowerCAmelCase_ : Dict = [self._extract_mfsc_features(SCREAMING_SNAKE_CASE_ ) for one_waveform in raw_speech] # convert into correct format for padding lowerCAmelCase_ : str = BatchFeature({'input_features': features} ) lowerCAmelCase_ : Union[str, Any] = self.pad( SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # make sure list is in array format lowerCAmelCase_ : Any = padded_inputs.get('input_features' ) if isinstance(input_features[0] , SCREAMING_SNAKE_CASE_ ): lowerCAmelCase_ : Union[str, Any] = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for feature in input_features] lowerCAmelCase_ : Union[str, Any] = padded_inputs.get('attention_mask' ) if attention_mask is not None: lowerCAmelCase_ : int = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.intaa ) for array in attention_mask] if self.normalize_means or self.normalize_vars: lowerCAmelCase_ : Optional[int] = ( np.array(SCREAMING_SNAKE_CASE_ , dtype=np.intaa ) if self._get_padding_strategies(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ ) is not PaddingStrategy.DO_NOT_PAD and padding else None ) lowerCAmelCase_ : Optional[int] = self.normalize( padded_inputs['input_features'] , attention_mask=SCREAMING_SNAKE_CASE_ ) if return_tensors is not None: lowerCAmelCase_ : Union[str, Any] = padded_inputs.convert_to_tensors(SCREAMING_SNAKE_CASE_ ) return padded_inputs
361
"""simple docstring""" from __future__ import annotations def UpperCamelCase_ ( lowerCAmelCase__ : int ) -> list[int]: """simple docstring""" lowerCAmelCase_ : Any = 2 lowerCAmelCase_ : List[Any] = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(lowerCAmelCase__ ) if n > 1: factors.append(lowerCAmelCase__ ) return factors if __name__ == "__main__": import doctest doctest.testmod()
289
0
"""simple docstring""" import argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": __A : Any = argparse.ArgumentParser( description=( '''Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel for Transfer Learned''' ''' Distillation''' ) ) parser.add_argument('''--model_type''', default='''roberta''', choices=['''roberta''', '''gpt2''']) parser.add_argument('''--model_name''', default='''roberta-large''', type=str) parser.add_argument('''--dump_checkpoint''', default='''serialization_dir/tf_roberta_048131723.pth''', type=str) parser.add_argument('''--vocab_transform''', action='''store_true''') __A : Union[str, Any] = parser.parse_args() if args.model_type == "roberta": __A : Any = RobertaForMaskedLM.from_pretrained(args.model_name) __A : Optional[Any] = '''roberta''' elif args.model_type == "gpt2": __A : Tuple = GPTaLMHeadModel.from_pretrained(args.model_name) __A : List[Any] = '''transformer''' __A : Any = model.state_dict() __A : Any = {} # Embeddings # if args.model_type == "gpt2": for param_name in ["wte.weight", "wpe.weight"]: __A : Optional[int] = state_dict[F"""{prefix}.{param_name}"""] else: for w in ["word_embeddings", "position_embeddings", "token_type_embeddings"]: __A : Tuple = F"""{prefix}.embeddings.{w}.weight""" __A : Union[str, Any] = state_dict[param_name] for w in ["weight", "bias"]: __A : Union[str, Any] = F"""{prefix}.embeddings.LayerNorm.{w}""" __A : List[str] = state_dict[param_name] # Transformer Blocks # __A : Optional[int] = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: if args.model_type == "gpt2": for layer in ["ln_1", "attn.c_attn", "attn.c_proj", "ln_2", "mlp.c_fc", "mlp.c_proj"]: for w in ["weight", "bias"]: __A : Union[str, Any] = state_dict[ F"""{prefix}.h.{teacher_idx}.{layer}.{w}""" ] __A : int = state_dict[F"""{prefix}.h.{teacher_idx}.attn.bias"""] else: for layer in [ "attention.self.query", "attention.self.key", "attention.self.value", "attention.output.dense", "attention.output.LayerNorm", "intermediate.dense", "output.dense", "output.LayerNorm", ]: for w in ["weight", "bias"]: __A : Optional[Any] = state_dict[ F"""{prefix}.encoder.layer.{teacher_idx}.{layer}.{w}""" ] std_idx += 1 # Language Modeling Head ###s if args.model_type == "roberta": for layer in ["lm_head.decoder.weight", "lm_head.bias"]: __A : List[str] = state_dict[F"""{layer}"""] if args.vocab_transform: for w in ["weight", "bias"]: __A : List[str] = state_dict[F"""lm_head.dense.{w}"""] __A : Optional[int] = state_dict[F"""lm_head.layer_norm.{w}"""] elif args.model_type == "gpt2": for w in ["weight", "bias"]: __A : Union[str, Any] = state_dict[F"""{prefix}.ln_f.{w}"""] __A : Optional[int] = state_dict['''lm_head.weight'''] print(F"""N layers selected for distillation: {std_idx}""") print(F"""Number of params transferred for distillation: {len(compressed_sd.keys())}""") print(F"""Save transferred checkpoint to {args.dump_checkpoint}.""") torch.save(compressed_sd, args.dump_checkpoint)
33
"""simple docstring""" from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=_a) class UpperCAmelCase_ ( _a): lowerCamelCase__ : str = field(default="language-modeling" , metadata={"include_in_asdict_even_if_is_default": True}) lowerCamelCase__ : ClassVar[Features] = Features({"text": Value("string")}) lowerCamelCase__ : ClassVar[Features] = Features({}) lowerCamelCase__ : str = "text" @property def _UpperCAmelCase ( self ) -> Dict[str, str]: return {self.text_column: "text"}
77
0
'''simple docstring''' import hashlib import unittest from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available from transformers.pipelines import DepthEstimationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_torch_available(): import torch if is_vision_available(): from PIL import Image else: class _snake_case : @staticmethod def UpperCamelCase__ ( *_snake_case ,**_snake_case ): pass def a__ ( _SCREAMING_SNAKE_CASE : List[str] ) -> str: UpperCAmelCase_ : Tuple = hashlib.mda(image.tobytes() ) return m.hexdigest() @is_pipeline_test @require_vision @require_timm @require_torch class _snake_case (unittest.TestCase): __A : List[Any] =MODEL_FOR_DEPTH_ESTIMATION_MAPPING def UpperCamelCase__ ( self ,_snake_case ,_snake_case ,_snake_case ): UpperCAmelCase_ : int = DepthEstimationPipeline(model=_UpperCAmelCase ,image_processor=_UpperCAmelCase ) return depth_estimator, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def UpperCamelCase__ ( self ,_snake_case ,_snake_case ): UpperCAmelCase_ : List[str] = depth_estimator("./tests/fixtures/tests_samples/COCO/000000039769.png" ) self.assertEqual({"predicted_depth": ANY(torch.Tensor ), "depth": ANY(Image.Image )} ,_UpperCAmelCase ) import datasets UpperCAmelCase_ : Optional[int] = datasets.load_dataset("hf-internal-testing/fixtures_image_utils" ,"image" ,split="test" ) UpperCAmelCase_ : Dict = depth_estimator( [ Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ), "http://images.cocodataset.org/val2017/000000039769.jpg", # RGBA dataset[0]["file"], # LA dataset[1]["file"], # L dataset[2]["file"], ] ) self.assertEqual( [ {"predicted_depth": ANY(torch.Tensor ), "depth": ANY(Image.Image )}, {"predicted_depth": ANY(torch.Tensor ), "depth": ANY(Image.Image )}, {"predicted_depth": ANY(torch.Tensor ), "depth": ANY(Image.Image )}, {"predicted_depth": ANY(torch.Tensor ), "depth": ANY(Image.Image )}, {"predicted_depth": ANY(torch.Tensor ), "depth": ANY(Image.Image )}, ] ,_UpperCAmelCase ,) @require_tf @unittest.skip("Depth estimation is not implemented in TF" ) def UpperCamelCase__ ( self ): pass @slow @require_torch def UpperCamelCase__ ( self ): UpperCAmelCase_ : List[str] = 'Intel/dpt-large' UpperCAmelCase_ : Optional[int] = pipeline("depth-estimation" ,model=_UpperCAmelCase ) UpperCAmelCase_ : Optional[int] = depth_estimator("http://images.cocodataset.org/val2017/000000039769.jpg" ) UpperCAmelCase_ : Any = hashimage(outputs["depth"] ) # This seems flaky. # self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977") self.assertEqual(nested_simplify(outputs["predicted_depth"].max().item() ) ,29.304 ) self.assertEqual(nested_simplify(outputs["predicted_depth"].min().item() ) ,2.662 ) @require_torch def UpperCamelCase__ ( self ): # This is highly irregular to have no small tests. self.skipTest("There is not hf-internal-testing tiny model for either GLPN nor DPT" )
368
'''simple docstring''' from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask if is_tf_available(): import tensorflow as tf from transformers import TFBlipTextModel from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST class _snake_case : def __init__( self ,_snake_case ,_snake_case=12 ,_snake_case=7 ,_snake_case=True ,_snake_case=True ,_snake_case=True ,_snake_case=99 ,_snake_case=32 ,_snake_case=32 ,_snake_case=2 ,_snake_case=4 ,_snake_case=37 ,_snake_case=0.1 ,_snake_case=0.1 ,_snake_case=5_12 ,_snake_case=0.02 ,_snake_case=0 ,_snake_case=None ,): UpperCAmelCase_ : Any = parent UpperCAmelCase_ : int = batch_size UpperCAmelCase_ : Optional[int] = seq_length UpperCAmelCase_ : Union[str, Any] = is_training UpperCAmelCase_ : str = use_input_mask UpperCAmelCase_ : List[Any] = use_labels UpperCAmelCase_ : Union[str, Any] = vocab_size UpperCAmelCase_ : List[Any] = hidden_size UpperCAmelCase_ : Any = projection_dim UpperCAmelCase_ : Optional[Any] = num_hidden_layers UpperCAmelCase_ : Union[str, Any] = num_attention_heads UpperCAmelCase_ : Optional[Any] = intermediate_size UpperCAmelCase_ : Any = dropout UpperCAmelCase_ : Dict = attention_dropout UpperCAmelCase_ : Optional[Any] = max_position_embeddings UpperCAmelCase_ : List[Any] = initializer_range UpperCAmelCase_ : Optional[int] = scope UpperCAmelCase_ : List[str] = bos_token_id def UpperCamelCase__ ( self ): UpperCAmelCase_ : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) UpperCAmelCase_ : List[Any] = None if self.use_input_mask: UpperCAmelCase_ : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) if input_mask is not None: UpperCAmelCase_ : Any = input_mask.numpy() UpperCAmelCase_ , UpperCAmelCase_ : str = input_mask.shape UpperCAmelCase_ : str = np.random.randint(1 ,seq_length - 1 ,size=(batch_size,) ) for batch_idx, start_index in enumerate(_snake_case ): UpperCAmelCase_ : Optional[int] = 1 UpperCAmelCase_ : Union[str, Any] = 0 UpperCAmelCase_ : int = self.get_config() return config, input_ids, tf.convert_to_tensor(_snake_case ) def UpperCamelCase__ ( self ): return BlipTextConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,projection_dim=self.projection_dim ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,dropout=self.dropout ,attention_dropout=self.attention_dropout ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,bos_token_id=self.bos_token_id ,) def UpperCamelCase__ ( self ,_snake_case ,_snake_case ,_snake_case ): UpperCAmelCase_ : Union[str, Any] = TFBlipTextModel(config=_snake_case ) UpperCAmelCase_ : Optional[int] = model(_snake_case ,attention_mask=_snake_case ,training=_snake_case ) UpperCAmelCase_ : Dict = model(_snake_case ,training=_snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape ,(self.batch_size, self.hidden_size) ) def UpperCamelCase__ ( self ): UpperCAmelCase_ : Optional[int] = self.prepare_config_and_inputs() UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : str = config_and_inputs UpperCAmelCase_ : str = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class _snake_case (__SCREAMING_SNAKE_CASE , unittest.TestCase): __A : Tuple =(TFBlipTextModel,) if is_tf_available() else () __A : List[Any] =False __A : List[Any] =False __A : Any =False def UpperCamelCase__ ( self ): UpperCAmelCase_ : Any = BlipTextModelTester(self ) UpperCAmelCase_ : List[Any] = ConfigTester(self ,config_class=_snake_case ,hidden_size=37 ) def UpperCamelCase__ ( self ): self.config_tester.run_common_tests() def UpperCamelCase__ ( self ): UpperCAmelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_snake_case ) def UpperCamelCase__ ( self ): pass def UpperCamelCase__ ( self ): pass @unittest.skip(reason="Blip does not use inputs_embeds" ) def UpperCamelCase__ ( self ): pass @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING" ) def UpperCamelCase__ ( self ): pass @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING" ) def UpperCamelCase__ ( self ): pass @slow def UpperCamelCase__ ( self ): for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : int = TFBlipTextModel.from_pretrained(_snake_case ) self.assertIsNotNone(_snake_case ) def UpperCamelCase__ ( self ,_snake_case=True ): super().test_pt_tf_model_equivalence(allow_missing_keys=_snake_case )
67
0
'''simple docstring''' import string def __lowerCamelCase ( lowerCAmelCase_ ) -> None: for key in range(len(string.ascii_uppercase ) ): _a : Union[str, Any] = '' for symbol in message: if symbol in string.ascii_uppercase: _a : Optional[Any] = string.ascii_uppercase.find(lowerCAmelCase_ ) _a : List[str] = num - key if num < 0: _a : str = num + len(string.ascii_uppercase ) _a : int = translated + string.ascii_uppercase[num] else: _a : Dict = translated + symbol print(f"""Decryption using Key #{key}: {translated}""" ) def __lowerCamelCase ( ) -> None: _a : int = input('Encrypted message: ' ) _a : Tuple = message.upper() decrypt(lowerCAmelCase_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
89
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowercase : List[str] = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Optional[int] = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Tuple = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys lowercase : List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
42
0
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging UpperCAmelCase: List[Any] = logging.get_logger(__name__) class UpperCamelCase ( _lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = ["pixel_values"] def __init__( self ,UpperCAmelCase_ = True ,UpperCAmelCase_ = None ,UpperCAmelCase_ = PILImageResampling.BILINEAR ,UpperCAmelCase_ = True ,UpperCAmelCase_ = None ,UpperCAmelCase_ = True ,UpperCAmelCase_ = 1 / 2_55 ,UpperCAmelCase_ = True ,UpperCAmelCase_ = None ,UpperCAmelCase_ = None ,**UpperCAmelCase_ ,): super().__init__(**UpperCAmelCase_ ) _lowercase : List[Any] = size if size is not None else {"""shortest_edge""": 2_56} _lowercase : Any = get_size_dict(UpperCAmelCase_ ,default_to_square=UpperCAmelCase_ ) _lowercase : Dict = crop_size if crop_size is not None else {"""height""": 2_24, """width""": 2_24} _lowercase : Dict = get_size_dict(UpperCAmelCase_ ) _lowercase : List[str] = do_resize _lowercase : List[Any] = size _lowercase : Optional[int] = resample _lowercase : Dict = do_center_crop _lowercase : Dict = crop_size _lowercase : Dict = do_rescale _lowercase : Any = rescale_factor _lowercase : Optional[int] = do_normalize _lowercase : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN _lowercase : Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def lowerCamelCase__ ( self ,UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ = PILImageResampling.BICUBIC ,UpperCAmelCase_ = None ,**UpperCAmelCase_ ,): _lowercase : str = get_size_dict(UpperCAmelCase_ ,default_to_square=UpperCAmelCase_ ) if "shortest_edge" not in size: raise ValueError(f"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" ) _lowercase : Any = get_resize_output_image_size(UpperCAmelCase_ ,size=size["""shortest_edge"""] ,default_to_square=UpperCAmelCase_ ) return resize(UpperCAmelCase_ ,size=UpperCAmelCase_ ,resample=UpperCAmelCase_ ,data_format=UpperCAmelCase_ ,**UpperCAmelCase_ ) def lowerCamelCase__ ( self ,UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ = None ,**UpperCAmelCase_ ,): _lowercase : List[Any] = get_size_dict(UpperCAmelCase_ ) return center_crop(UpperCAmelCase_ ,size=(size["""height"""], size["""width"""]) ,data_format=UpperCAmelCase_ ,**UpperCAmelCase_ ) def lowerCamelCase__ ( self ,UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ = None ,**UpperCAmelCase_ ): return rescale(UpperCAmelCase_ ,scale=UpperCAmelCase_ ,data_format=UpperCAmelCase_ ,**UpperCAmelCase_ ) def lowerCamelCase__ ( self ,UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ = None ,**UpperCAmelCase_ ,): return normalize(UpperCAmelCase_ ,mean=UpperCAmelCase_ ,std=UpperCAmelCase_ ,data_format=UpperCAmelCase_ ,**UpperCAmelCase_ ) def lowerCamelCase__ ( self ,UpperCAmelCase_ ,UpperCAmelCase_ = None ,UpperCAmelCase_ = None ,UpperCAmelCase_ = None ,UpperCAmelCase_ = None ,UpperCAmelCase_ = None ,UpperCAmelCase_ = None ,UpperCAmelCase_ = None ,UpperCAmelCase_ = None ,UpperCAmelCase_ = None ,UpperCAmelCase_ = None ,UpperCAmelCase_ = None ,UpperCAmelCase_ = ChannelDimension.FIRST ,**UpperCAmelCase_ ,): _lowercase : List[str] = do_resize if do_resize is not None else self.do_resize _lowercase : Dict = size if size is not None else self.size _lowercase : Union[str, Any] = get_size_dict(UpperCAmelCase_ ,default_to_square=UpperCAmelCase_ ) _lowercase : Optional[int] = resample if resample is not None else self.resample _lowercase : Any = do_center_crop if do_center_crop is not None else self.do_center_crop _lowercase : Tuple = crop_size if crop_size is not None else self.crop_size _lowercase : Any = get_size_dict(UpperCAmelCase_ ) _lowercase : Tuple = do_rescale if do_rescale is not None else self.do_rescale _lowercase : int = rescale_factor if rescale_factor is not None else self.rescale_factor _lowercase : Tuple = do_normalize if do_normalize is not None else self.do_normalize _lowercase : Union[str, Any] = image_mean if image_mean is not None else self.image_mean _lowercase : Optional[int] = image_std if image_std is not None else self.image_std _lowercase : Any = make_list_of_images(UpperCAmelCase_ ) if not valid_images(UpperCAmelCase_ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. _lowercase : Optional[int] = [to_numpy_array(UpperCAmelCase_ ) for image in images] if do_resize: _lowercase : List[str] = [self.resize(image=UpperCAmelCase_ ,size=UpperCAmelCase_ ,resample=UpperCAmelCase_ ) for image in images] if do_center_crop: _lowercase : Any = [self.center_crop(image=UpperCAmelCase_ ,size=UpperCAmelCase_ ) for image in images] if do_rescale: _lowercase : List[Any] = [self.rescale(image=UpperCAmelCase_ ,scale=UpperCAmelCase_ ) for image in images] if do_normalize: _lowercase : Union[str, Any] = [self.normalize(image=UpperCAmelCase_ ,mean=UpperCAmelCase_ ,std=UpperCAmelCase_ ) for image in images] _lowercase : Optional[Any] = [to_channel_dimension_format(UpperCAmelCase_ ,UpperCAmelCase_ ) for image in images] _lowercase : Dict = {"""pixel_values""": images} return BatchFeature(data=UpperCAmelCase_ ,tensor_type=UpperCAmelCase_ )
353
"""simple docstring""" import pprint import requests UpperCAmelCase: Tuple = """https://zenquotes.io/api""" def __SCREAMING_SNAKE_CASE ( ): return requests.get(API_ENDPOINT_URL + """/today""" ).json() def __SCREAMING_SNAKE_CASE ( ): return requests.get(API_ENDPOINT_URL + """/random""" ).json() if __name__ == "__main__": UpperCAmelCase: int = random_quotes() pprint.pprint(response)
336
0
import fcntl import os import socket import torch import torch.distributed as dist def lowerCamelCase_ ( *_a ): """simple docstring""" with open(__lowerCamelCase , '''r''' ) as fh: fcntl.flock(__lowerCamelCase , fcntl.LOCK_EX ) try: print(*__lowerCamelCase ) finally: fcntl.flock(__lowerCamelCase , fcntl.LOCK_UN ) lowerCamelCase = int(os.environ['''LOCAL_RANK''']) torch.cuda.set_device(local_rank) lowerCamelCase = torch.device('''cuda''', local_rank) lowerCamelCase = socket.gethostname() lowerCamelCase = f'''[{hostname}-{local_rank}]''' try: # test distributed dist.init_process_group('''nccl''') dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM) dist.barrier() # test cuda is available and can allocate memory torch.cuda.is_available() torch.ones(1).cuda(local_rank) # global rank lowerCamelCase = dist.get_rank() lowerCamelCase = dist.get_world_size() printflock(f'''{gpu} is OK (global rank: {rank}/{world_size})''') dist.barrier() if rank == 0: printflock(f'''pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}''') except Exception: printflock(f'''{gpu} is broken''') raise
131
"""simple docstring""" import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class A_ (lowercase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = (DDIMParallelScheduler,) SCREAMING_SNAKE_CASE__ : Optional[Any] = (("""eta""", 0.0), ("""num_inference_steps""", 50)) def UpperCamelCase__ ( self , **lowercase_ ): """simple docstring""" UpperCAmelCase_ : int = { "num_train_timesteps": 1000, "beta_start": 0.00_01, "beta_end": 0.02, "beta_schedule": "linear", "clip_sample": True, } config.update(**lowercase_ ) return config def UpperCamelCase__ ( self , **lowercase_ ): """simple docstring""" UpperCAmelCase_ : Dict = self.scheduler_classes[0] UpperCAmelCase_ : Union[str, Any] = self.get_scheduler_config(**lowercase_ ) UpperCAmelCase_ : int = scheduler_class(**lowercase_ ) UpperCAmelCase_ , UpperCAmelCase_ : str = 10, 0.0 UpperCAmelCase_ : Optional[int] = self.dummy_model() UpperCAmelCase_ : str = self.dummy_sample_deter scheduler.set_timesteps(lowercase_ ) for t in scheduler.timesteps: UpperCAmelCase_ : Dict = model(lowercase_ , lowercase_ ) UpperCAmelCase_ : Dict = scheduler.step(lowercase_ , lowercase_ , lowercase_ , lowercase_ ).prev_sample return sample def UpperCamelCase__ ( self ): """simple docstring""" for timesteps in [100, 500, 1000]: self.check_over_configs(num_train_timesteps=lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" for steps_offset in [0, 1]: self.check_over_configs(steps_offset=lowercase_ ) UpperCAmelCase_ : str = self.scheduler_classes[0] UpperCAmelCase_ : List[str] = self.get_scheduler_config(steps_offset=1 ) UpperCAmelCase_ : List[str] = scheduler_class(**lowercase_ ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1] ) ) def UpperCamelCase__ ( self ): """simple docstring""" for beta_start, beta_end in zip([0.00_01, 0.0_01, 0.01, 0.1] , [0.0_02, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=lowercase_ , beta_end=lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" self.check_over_configs(thresholding=lowercase_ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=lowercase_ , prediction_type=lowercase_ , sample_max_value=lowercase_ , ) def UpperCamelCase__ ( self ): """simple docstring""" for t in [1, 10, 49]: self.check_over_forward(time_step=lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500] ): self.check_over_forward(time_step=lowercase_ , num_inference_steps=lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=lowercase_ , eta=lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Union[str, Any] = self.scheduler_classes[0] UpperCAmelCase_ : List[str] = self.get_scheduler_config() UpperCAmelCase_ : List[str] = scheduler_class(**lowercase_ ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(420 , 400 ) - 0.1_47_71 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(980 , 960 ) - 0.3_24_60 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 , 486 ) - 0.0_09_79 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 , 998 ) - 0.02 ) ) < 1E-5 def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Tuple = self.scheduler_classes[0] UpperCAmelCase_ : Optional[int] = self.get_scheduler_config() UpperCAmelCase_ : List[str] = scheduler_class(**lowercase_ ) UpperCAmelCase_ , UpperCAmelCase_ : Tuple = 10, 0.0 scheduler.set_timesteps(lowercase_ ) UpperCAmelCase_ : Union[str, Any] = self.dummy_model() UpperCAmelCase_ : List[str] = self.dummy_sample_deter UpperCAmelCase_ : Any = self.dummy_sample_deter + 0.1 UpperCAmelCase_ : int = self.dummy_sample_deter - 0.1 UpperCAmelCase_ : List[Any] = samplea.shape[0] UpperCAmelCase_ : int = torch.stack([samplea, samplea, samplea] , dim=0 ) UpperCAmelCase_ : int = torch.arange(lowercase_ )[0:3, None].repeat(1 , lowercase_ ) UpperCAmelCase_ : int = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) UpperCAmelCase_ : Optional[Any] = scheduler.batch_step_no_noise(lowercase_ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , lowercase_ ) UpperCAmelCase_ : List[Any] = torch.sum(torch.abs(lowercase_ ) ) UpperCAmelCase_ : str = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 11_47.79_04 ) < 1E-2 assert abs(result_mean.item() - 0.49_82 ) < 1E-3 def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Tuple = self.full_loop() UpperCAmelCase_ : int = torch.sum(torch.abs(lowercase_ ) ) UpperCAmelCase_ : List[str] = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 1_72.00_67 ) < 1E-2 assert abs(result_mean.item() - 0.22_39_67 ) < 1E-3 def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : List[str] = self.full_loop(prediction_type="v_prediction" ) UpperCAmelCase_ : str = torch.sum(torch.abs(lowercase_ ) ) UpperCAmelCase_ : Dict = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 52.53_02 ) < 1E-2 assert abs(result_mean.item() - 0.06_84 ) < 1E-3 def UpperCamelCase__ ( self ): """simple docstring""" # We specify different beta, so that the first alpha is 0.99 UpperCAmelCase_ : List[str] = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01 ) UpperCAmelCase_ : Dict = torch.sum(torch.abs(lowercase_ ) ) UpperCAmelCase_ : Tuple = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 1_49.82_95 ) < 1E-2 assert abs(result_mean.item() - 0.19_51 ) < 1E-3 def UpperCamelCase__ ( self ): """simple docstring""" # We specify different beta, so that the first alpha is 0.99 UpperCAmelCase_ : int = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01 ) UpperCAmelCase_ : List[Any] = torch.sum(torch.abs(lowercase_ ) ) UpperCAmelCase_ : Dict = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 1_49.07_84 ) < 1E-2 assert abs(result_mean.item() - 0.19_41 ) < 1E-3
61
0
def __lowerCAmelCase ( SCREAMING_SNAKE_CASE_ ): return "".join(chr(ord(SCREAMING_SNAKE_CASE_ ) - 32 ) if "a" <= char <= "z" else char for char in word ) if __name__ == "__main__": from doctest import testmod testmod()
224
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 lowercase_ = logging.get_logger(__name__) lowercase_ = { """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 _snake_case ( lowercase__): UpperCamelCase__ : Any ="""perceiver""" def __init__( self : Any, __lowercase : Optional[Any]=256, __lowercase : List[str]=1280, __lowercase : Dict=768, __lowercase : int=1, __lowercase : Dict=26, __lowercase : Any=8, __lowercase : List[Any]=8, __lowercase : Dict=None, __lowercase : List[Any]=None, __lowercase : str="kv", __lowercase : str=1, __lowercase : Optional[Any]=1, __lowercase : str="gelu", __lowercase : List[str]=0.1, __lowercase : int=0.02, __lowercase : Union[str, Any]=1e-1_2, __lowercase : Optional[Any]=True, __lowercase : Optional[Any]=262, __lowercase : str=2048, __lowercase : Optional[Any]=56, __lowercase : str=[368, 496], __lowercase : str=16, __lowercase : int=1920, __lowercase : Dict=16, __lowercase : List[Any]=[1, 16, 224, 224], **__lowercase : str, ): super().__init__(**__lowercase ) lowercase__ = num_latents lowercase__ = d_latents lowercase__ = d_model lowercase__ = num_blocks lowercase__ = num_self_attends_per_block lowercase__ = num_self_attention_heads lowercase__ = num_cross_attention_heads lowercase__ = qk_channels lowercase__ = v_channels lowercase__ = cross_attention_shape_for_attention lowercase__ = self_attention_widening_factor lowercase__ = cross_attention_widening_factor lowercase__ = hidden_act lowercase__ = attention_probs_dropout_prob lowercase__ = initializer_range lowercase__ = layer_norm_eps lowercase__ = use_query_residual # masked language modeling attributes lowercase__ = vocab_size lowercase__ = max_position_embeddings # image classification attributes lowercase__ = image_size # flow attributes lowercase__ = train_size # multimodal autoencoding attributes lowercase__ = num_frames lowercase__ = audio_samples_per_frame lowercase__ = samples_per_patch lowercase__ = output_shape class _snake_case ( lowercase__): @property def A__ ( self : Optional[int] ): if self.task == "multiple-choice": lowercase__ = {0: "batch", 1: "choice", 2: "sequence"} else: lowercase__ = {0: "batch", 1: "sequence"} return OrderedDict( [ ("inputs", dynamic_axis), ("attention_mask", dynamic_axis), ] ) @property def A__ ( self : Optional[Any] ): return 1e-4 def A__ ( self : Tuple, __lowercase : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"], __lowercase : int = -1, __lowercase : int = -1, __lowercase : int = -1, __lowercase : bool = False, __lowercase : Optional[TensorType] = None, __lowercase : int = 3, __lowercase : int = 40, __lowercase : int = 40, ): # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified if isinstance(__lowercase, __lowercase ): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX lowercase__ = compute_effective_axis_dimension( __lowercase, 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 lowercase__ = preprocessor.num_special_tokens_to_add(__lowercase ) lowercase__ = compute_effective_axis_dimension( __lowercase, fixed_dimension=OnnxConfig.default_fixed_sequence, num_token_to_add=__lowercase ) # Generate dummy inputs according to compute batch and sequence lowercase__ = [" ".join(["a"] ) * seq_length] * batch_size lowercase__ = dict(preprocessor(__lowercase, return_tensors=__lowercase ) ) lowercase__ = inputs.pop("input_ids" ) return inputs elif isinstance(__lowercase, __lowercase ) 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 lowercase__ = compute_effective_axis_dimension(__lowercase, fixed_dimension=OnnxConfig.default_fixed_batch ) lowercase__ = self._generate_dummy_images(__lowercase, __lowercase, __lowercase, __lowercase ) lowercase__ = dict(preprocessor(images=__lowercase, return_tensors=__lowercase ) ) lowercase__ = inputs.pop("pixel_values" ) return inputs else: raise ValueError( "Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor." )
224
1
'''simple docstring''' from abc import ABC, abstractmethod from typing import List, Optional class A ( lowerCAmelCase_ ): def __init__( self ) -> Optional[int]: '''simple docstring''' self.test() def A__ ( self ) -> int: '''simple docstring''' lowercase__ = 0 lowercase__ = False while not completed: if counter == 1: self.reset() lowercase__ = self.advance() if not self.does_advance(__lowerCAmelCase ): raise Exception( """Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.""" ) lowercase__ , lowercase__ , lowercase__ = self.update(__lowerCAmelCase ) counter += 1 if counter > 10_000: raise Exception("""update() does not fulfill the constraint.""" ) if self.remaining() != 0: raise Exception("""Custom Constraint is not defined correctly.""" ) @abstractmethod def A__ ( self ) -> Union[str, Any]: '''simple docstring''' raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def A__ ( self , lowerCamelCase__ ) -> Tuple: '''simple docstring''' raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def A__ ( self , lowerCamelCase__ ) -> Dict: '''simple docstring''' raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def A__ ( self ) -> str: '''simple docstring''' raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def A__ ( self ) -> List[str]: '''simple docstring''' raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def A__ ( self , lowerCamelCase__=False ) -> Optional[int]: '''simple docstring''' raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class A ( lowerCAmelCase_ ): def __init__( self , lowerCamelCase__ ) -> Union[str, Any]: '''simple docstring''' super(__lowerCAmelCase , self ).__init__() if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or len(__lowerCAmelCase ) == 0: raise ValueError(F'''`token_ids` has to be a non-empty list, but is {token_ids}.''' ) if any((not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or token_id < 0) for token_id in token_ids ): raise ValueError(F'''Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.''' ) lowercase__ = token_ids lowercase__ = len(self.token_ids ) lowercase__ = -1 # the index of the currently fulfilled step lowercase__ = False def A__ ( self ) -> str: '''simple docstring''' if self.completed: return None return self.token_ids[self.fulfilled_idx + 1] def A__ ( self , lowerCamelCase__ ) -> Tuple: '''simple docstring''' if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(__lowerCAmelCase )}''' ) if self.completed: return False return token_id == self.token_ids[self.fulfilled_idx + 1] def A__ ( self , lowerCamelCase__ ) -> Optional[Any]: '''simple docstring''' if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(__lowerCAmelCase )}''' ) lowercase__ = False lowercase__ = False lowercase__ = False if self.does_advance(__lowerCAmelCase ): self.fulfilled_idx += 1 lowercase__ = True if self.fulfilled_idx == (self.seqlen - 1): lowercase__ = True lowercase__ = completed else: # failed to make progress. lowercase__ = True self.reset() return stepped, completed, reset def A__ ( self ) -> Optional[int]: '''simple docstring''' lowercase__ = False lowercase__ = 0 def A__ ( self ) -> int: '''simple docstring''' return self.seqlen - (self.fulfilled_idx + 1) def A__ ( self , lowerCamelCase__=False ) -> Optional[Any]: '''simple docstring''' lowercase__ = PhrasalConstraint(self.token_ids ) if stateful: lowercase__ = self.seqlen lowercase__ = self.fulfilled_idx lowercase__ = self.completed return new_constraint class A : def __init__( self , lowerCamelCase__ , lowerCamelCase__=True ) -> Optional[int]: '''simple docstring''' lowercase__ = max([len(__lowerCAmelCase ) for one in nested_token_ids] ) lowercase__ = {} for token_ids in nested_token_ids: lowercase__ = root for tidx, token_id in enumerate(__lowerCAmelCase ): if token_id not in level: lowercase__ = {} lowercase__ = level[token_id] if no_subsets and self.has_subsets(__lowerCAmelCase , __lowerCAmelCase ): raise ValueError( """Each list in `nested_token_ids` can't be a complete subset of another list, but is""" F''' {nested_token_ids}.''' ) lowercase__ = root def A__ ( self , lowerCamelCase__ ) -> List[Any]: '''simple docstring''' lowercase__ = self.trie for current_token in current_seq: lowercase__ = start[current_token] lowercase__ = list(start.keys() ) return next_tokens def A__ ( self , lowerCamelCase__ ) -> Any: '''simple docstring''' lowercase__ = self.next_tokens(__lowerCAmelCase ) return len(__lowerCAmelCase ) == 0 def A__ ( self , lowerCamelCase__ ) -> Optional[int]: '''simple docstring''' lowercase__ = list(root.values() ) if len(__lowerCAmelCase ) == 0: return 1 else: return sum([self.count_leaves(__lowerCAmelCase ) for nn in next_nodes] ) def A__ ( self , lowerCamelCase__ , lowerCamelCase__ ) -> Dict: '''simple docstring''' lowercase__ = self.count_leaves(__lowerCAmelCase ) return len(__lowerCAmelCase ) != leaf_count class A ( lowerCAmelCase_ ): def __init__( self , lowerCamelCase__ ) -> Union[str, Any]: '''simple docstring''' super(__lowerCAmelCase , self ).__init__() if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or len(__lowerCAmelCase ) == 0: raise ValueError(F'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.''' ) if any(not isinstance(__lowerCAmelCase , __lowerCAmelCase ) for token_ids in nested_token_ids ): raise ValueError(F'''`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.''' ) if any( any((not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or token_id < 0) for token_id in token_ids ) for token_ids in nested_token_ids ): raise ValueError( F'''Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.''' ) lowercase__ = DisjunctiveTrie(__lowerCAmelCase ) lowercase__ = nested_token_ids lowercase__ = self.trie.max_height lowercase__ = [] lowercase__ = False def A__ ( self ) -> Tuple: '''simple docstring''' lowercase__ = self.trie.next_tokens(self.current_seq ) if len(__lowerCAmelCase ) == 0: return None else: return token_list def A__ ( self , lowerCamelCase__ ) -> Optional[Any]: '''simple docstring''' if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(__lowerCAmelCase )}''' ) lowercase__ = self.trie.next_tokens(self.current_seq ) return token_id in next_tokens def A__ ( self , lowerCamelCase__ ) -> int: '''simple docstring''' if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(__lowerCAmelCase )}''' ) lowercase__ = False lowercase__ = False lowercase__ = False if self.does_advance(__lowerCAmelCase ): self.current_seq.append(__lowerCAmelCase ) lowercase__ = True else: lowercase__ = True self.reset() lowercase__ = self.trie.reached_leaf(self.current_seq ) lowercase__ = completed return stepped, completed, reset def A__ ( self ) -> Optional[Any]: '''simple docstring''' lowercase__ = False lowercase__ = [] def A__ ( self ) -> Dict: '''simple docstring''' if self.completed: # since this can be completed without reaching max height return 0 else: return self.seqlen - len(self.current_seq ) def A__ ( self , lowerCamelCase__=False ) -> Optional[Any]: '''simple docstring''' lowercase__ = DisjunctiveConstraint(self.token_ids ) if stateful: lowercase__ = self.seqlen lowercase__ = self.current_seq lowercase__ = self.completed return new_constraint class A : def __init__( self , lowerCamelCase__ ) -> Tuple: '''simple docstring''' lowercase__ = constraints # max # of steps required to fulfill a given constraint lowercase__ = max([c.seqlen for c in constraints] ) lowercase__ = len(__lowerCAmelCase ) lowercase__ = False self.init_state() def A__ ( self ) -> int: '''simple docstring''' lowercase__ = [] lowercase__ = None lowercase__ = [constraint.copy(stateful=__lowerCAmelCase ) for constraint in self.constraints] def A__ ( self ) -> Optional[Any]: '''simple docstring''' lowercase__ = 0 if self.inprogress_constraint: # extra points for having a constraint mid-fulfilled add += self.max_seqlen - self.inprogress_constraint.remaining() return (len(self.complete_constraints ) * self.max_seqlen) + add def A__ ( self ) -> Any: '''simple docstring''' lowercase__ = [] if self.inprogress_constraint is None: for constraint in self.pending_constraints: # "pending" == "unfulfilled yet" lowercase__ = constraint.advance() if isinstance(__lowerCAmelCase , __lowerCAmelCase ): token_list.append(__lowerCAmelCase ) elif isinstance(__lowerCAmelCase , __lowerCAmelCase ): token_list.extend(__lowerCAmelCase ) else: lowercase__ = self.inprogress_constraint.advance() if isinstance(__lowerCAmelCase , __lowerCAmelCase ): token_list.append(__lowerCAmelCase ) elif isinstance(__lowerCAmelCase , __lowerCAmelCase ): token_list.extend(__lowerCAmelCase ) if len(__lowerCAmelCase ) == 0: return None else: return token_list def A__ ( self , lowerCamelCase__ ) -> Dict: '''simple docstring''' self.init_state() if token_ids is not None: for token in token_ids: # completes or steps **one** constraint lowercase__ , lowercase__ = self.add(__lowerCAmelCase ) # the entire list of constraints are fulfilled if self.completed: break def A__ ( self , lowerCamelCase__ ) -> int: '''simple docstring''' if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise ValueError(F'''`token_id` should be an `int`, but is `{token_id}`.''' ) lowercase__ , lowercase__ = False, False if self.completed: lowercase__ = True lowercase__ = False return complete, stepped if self.inprogress_constraint is not None: # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current # job, simply update the state lowercase__ , lowercase__ , lowercase__ = self.inprogress_constraint.update(__lowerCAmelCase ) if reset: # 1. If the next token breaks the progress, then we must restart. # e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books". # But that doesn't mean we self.init_state(), since we only reset the state for this particular # constraint, not the full list of constraints. self.pending_constraints.append(self.inprogress_constraint.copy(stateful=__lowerCAmelCase ) ) lowercase__ = None if complete: # 2. If the next token completes the constraint, move it to completed list, set # inprogress to None. If there are no pending constraints either, then this full list of constraints # is complete. self.complete_constraints.append(self.inprogress_constraint ) lowercase__ = None if len(self.pending_constraints ) == 0: # we're done! lowercase__ = True else: # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list # of constraints? for cidx, pending_constraint in enumerate(self.pending_constraints ): if pending_constraint.does_advance(__lowerCAmelCase ): lowercase__ , lowercase__ , lowercase__ = pending_constraint.update(__lowerCAmelCase ) if not stepped: raise Exception( """`constraint.update(token_id)` is not yielding incremental progress, """ """even though `constraint.does_advance(token_id)` is true.""" ) if complete: self.complete_constraints.append(__lowerCAmelCase ) lowercase__ = None if not complete and stepped: lowercase__ = pending_constraint if complete or stepped: # If we made any progress at all, then it's at least not a "pending constraint". lowercase__ = ( self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :] ) if len(self.pending_constraints ) == 0 and self.inprogress_constraint is None: # If there's no longer any pending after this and no inprogress either, then we must be # complete. lowercase__ = True break # prevent accidentally stepping through multiple constraints with just one token. return complete, stepped def A__ ( self , lowerCamelCase__=True ) -> List[Any]: '''simple docstring''' lowercase__ = ConstraintListState(self.constraints ) # we actually never though self.constraints objects # throughout this process. So it's at initialization state. if stateful: lowercase__ = [ constraint.copy(stateful=__lowerCAmelCase ) for constraint in self.complete_constraints ] if self.inprogress_constraint is not None: lowercase__ = self.inprogress_constraint.copy(stateful=__lowerCAmelCase ) lowercase__ = [constraint.copy() for constraint in self.pending_constraints] return new_state
164
"""simple docstring""" import requests UpperCAmelCase__ = """""" # <-- Put your OpenWeatherMap appid here! UpperCAmelCase__ = """https://api.openweathermap.org/data/2.5/""" def __UpperCAmelCase ( lowercase = "Chicago" ,lowercase = APPID ): """simple docstring""" return requests.get(URL_BASE + """weather""" ,params=locals() ).json() def __UpperCAmelCase ( lowercase = "Kolkata, India" ,lowercase = APPID ): """simple docstring""" return requests.get(URL_BASE + """forecast""" ,params=locals() ).json() def __UpperCAmelCase ( lowercase = 55.68 ,lowercase = 12.57 ,lowercase = APPID ): """simple docstring""" return requests.get(URL_BASE + """onecall""" ,params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: UpperCAmelCase__ = input("""Enter a location:""").strip() if location: pprint(current_weather(location)) else: break
289
0
import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print("""Googling.....""") lowerCamelCase_ : Any = """https://www.google.com/search?q=""" + """ """.join(sys.argv[1:]) lowerCamelCase_ : Any = requests.get(url, headers={"""UserAgent""": UserAgent().random}) # res.raise_for_status() with open("""project1a.html""", """wb""") as out_file: # only for knowing the class for data in res.iter_content(1_00_00): out_file.write(data) lowerCamelCase_ : Optional[int] = BeautifulSoup(res.text, """html.parser""") lowerCamelCase_ : List[Any] = list(soup.select(""".eZt8xd"""))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get("""href""")) else: webbrowser.open(F"""https://google.com{link.get('href')}""")
223
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ : Optional[int] = logging.get_logger(__name__) lowerCamelCase_ : Optional[int] = {"""ctrl""": """https://huggingface.co/ctrl/resolve/main/config.json"""} class _UpperCamelCase ( _A ): '''simple docstring''' __UpperCamelCase : int = """ctrl""" __UpperCamelCase : Dict = ["""past_key_values"""] __UpperCamelCase : List[str] = { """max_position_embeddings""": """n_positions""", """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : Dict , snake_case_ : Any=24_6534 , snake_case_ : Dict=256 , snake_case_ : str=1280 , snake_case_ : Optional[int]=8192 , snake_case_ : Union[str, Any]=48 , snake_case_ : Any=16 , snake_case_ : Optional[int]=0.1 , snake_case_ : Any=0.1 , snake_case_ : Any=1e-6 , snake_case_ : Optional[Any]=0.02 , snake_case_ : Optional[int]=True , **snake_case_ : Union[str, Any] , ): UpperCamelCase_: Union[str, Any] = vocab_size UpperCamelCase_: Union[str, Any] = n_positions UpperCamelCase_: Optional[int] = n_embd UpperCamelCase_: int = n_layer UpperCamelCase_: str = n_head UpperCamelCase_: Optional[int] = dff UpperCamelCase_: Optional[Any] = resid_pdrop UpperCamelCase_: Union[str, Any] = embd_pdrop UpperCamelCase_: List[str] = layer_norm_epsilon UpperCamelCase_: Optional[Any] = initializer_range UpperCamelCase_: Optional[Any] = use_cache super().__init__(**snake_case_ )
223
1
"""simple docstring""" from torch import nn class __UpperCamelCase ( nn.Module ): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Optional[int]: super().__init__() a : Optional[Any] = class_size a : Any = embed_size # self.mlp1 = nn.Linear(embed_size, embed_size) # self.mlp2 = (nn.Linear(embed_size, class_size)) a : Optional[Any] = nn.Linear(lowerCAmelCase__ , lowerCAmelCase__ ) def __a ( self , lowerCAmelCase__ ) -> str: # hidden_state = nn.functional.relu(self.mlp1(hidden_state)) # hidden_state = self.mlp2(hidden_state) a : List[Any] = self.mlp(lowerCAmelCase__ ) return logits
105
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> int: while second != 0: __lowerCamelCase = first & second first ^= second __lowerCamelCase = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() __UpperCAmelCase =int(input("Enter the first number: ").strip()) __UpperCAmelCase =int(input("Enter the second number: ").strip()) print(f'{add(first, second) = }')
67
0
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __UpperCamelCase ( unittest.TestCase ): def __init__( self , __a , __a=7 , __a=3 , __a=18 , __a=30 , __a=400 , __a=True , __a=None , __a=True , ): '''simple docstring''' __a : List[Any] = size if size is not None else {'height': 18, 'width': 18} __a : int = parent __a : Dict = batch_size __a : Optional[int] = num_channels __a : List[Any] = image_size __a : Tuple = min_resolution __a : str = max_resolution __a : str = do_resize __a : Optional[Any] = size __a : str = apply_ocr def __UpperCAmelCase ( self ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class __UpperCamelCase ( lowerCAmelCase_ , unittest.TestCase ): A_ = LayoutLMvaImageProcessor if is_pytesseract_available() else None def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = LayoutLMvaImageProcessingTester(self ) @property def __UpperCAmelCase ( self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__a , 'do_resize' ) ) self.assertTrue(hasattr(__a , 'size' ) ) self.assertTrue(hasattr(__a , 'apply_ocr' ) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 18, 'width': 18} ) __a : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) def __UpperCAmelCase ( self ): '''simple docstring''' pass def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __a : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a ) for image in image_inputs: self.assertIsInstance(__a , Image.Image ) # Test not batched input __a : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , __a ) self.assertIsInstance(encoding.boxes , __a ) # Test batched __a : Any = 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.size['height'], self.image_processor_tester.size['width'], ) , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __a : Union[str, Any] = 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 __a : Optional[Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched __a : Tuple = 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.size['height'], self.image_processor_tester.size['width'], ) , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __a : List[str] = 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 __a : List[Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched __a : List[str] = 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.size['height'], self.image_processor_tester.size['width'], ) , ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : List[str] = LayoutLMvaImageProcessor() from datasets import load_dataset __a : str = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test' ) __a : Tuple = Image.open(ds[0]['file'] ).convert('RGB' ) __a : Optional[Any] = image_processing(__a , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 __a : Optional[Any] = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 __a : Union[str, Any] = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , __a ) self.assertListEqual(encoding.boxes , __a ) # with apply_OCR = False __a : List[Any] = LayoutLMvaImageProcessor(apply_ocr=__a ) __a : List[Any] = image_processing(__a , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
294
'''simple docstring''' from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig __lowercase : List[Any] = { 'susnato/ernie-m-base_pytorch': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json', 'susnato/ernie-m-large_pytorch': 'https://huggingface.co/susnato/ernie-m-large_pytorch/blob/main/config.json', } class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "ernie_m" A_ = {"dropout": "classifier_dropout", "num_classes": "num_labels"} def __init__( self , __a = 25_0002 , __a = 768 , __a = 12 , __a = 12 , __a = 3072 , __a = "gelu" , __a = 0.1 , __a = 0.1 , __a = 514 , __a = 0.02 , __a = 1 , __a = 1E-0_5 , __a=None , __a=False , __a=0.0 , **__a , ): '''simple docstring''' super().__init__(pad_token_id=__a , **__a ) __a : int = vocab_size __a : Dict = hidden_size __a : str = num_hidden_layers __a : Dict = num_attention_heads __a : List[str] = intermediate_size __a : Union[str, Any] = hidden_act __a : List[Any] = hidden_dropout_prob __a : str = attention_probs_dropout_prob __a : Any = max_position_embeddings __a : int = initializer_range __a : Dict = layer_norm_eps __a : int = classifier_dropout __a : Dict = is_decoder __a : int = act_dropout
294
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class A_ : '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = XGLMConfig SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} SCREAMING_SNAKE_CASE__ : Optional[Any] = """gelu""" def __init__( self , lowercase_ , lowercase_=14 , lowercase_=7 , lowercase_=True , lowercase_=True , lowercase_=True , lowercase_=99 , lowercase_=32 , lowercase_=2 , lowercase_=4 , lowercase_=37 , lowercase_="gelu" , lowercase_=0.1 , lowercase_=0.1 , lowercase_=512 , lowercase_=0.02 , ): """simple docstring""" UpperCAmelCase_ : Optional[int] = parent UpperCAmelCase_ : Tuple = batch_size UpperCAmelCase_ : Optional[int] = seq_length UpperCAmelCase_ : Union[str, Any] = is_training UpperCAmelCase_ : List[Any] = use_input_mask UpperCAmelCase_ : Tuple = use_labels UpperCAmelCase_ : List[Any] = vocab_size UpperCAmelCase_ : Union[str, Any] = d_model UpperCAmelCase_ : Optional[int] = num_hidden_layers UpperCAmelCase_ : List[Any] = num_attention_heads UpperCAmelCase_ : List[Any] = ffn_dim UpperCAmelCase_ : int = activation_function UpperCAmelCase_ : List[str] = activation_dropout UpperCAmelCase_ : List[Any] = attention_dropout UpperCAmelCase_ : List[str] = max_position_embeddings UpperCAmelCase_ : Optional[Any] = initializer_range UpperCAmelCase_ : Optional[Any] = None UpperCAmelCase_ : Dict = 0 UpperCAmelCase_ : List[str] = 2 UpperCAmelCase_ : Tuple = 1 def UpperCamelCase__ ( self ): """simple docstring""" return XGLMConfig.from_pretrained("facebook/xglm-564M" ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Union[str, Any] = tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) , clip_value_min=0 , clip_value_max=3 ) UpperCAmelCase_ : Optional[int] = None if self.use_input_mask: UpperCAmelCase_ : str = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase_ : Union[str, Any] = self.get_config() UpperCAmelCase_ : List[Any] = floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, ) def UpperCamelCase__ ( self ): """simple docstring""" return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=lowercase_ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=lowercase_ , ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : List[Any] = self.prepare_config_and_inputs() ( ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ) : Any = config_and_inputs UpperCAmelCase_ : List[str] = { "input_ids": input_ids, "head_mask": head_mask, } return config, inputs_dict @require_tf class A_ (lowercase__ ,lowercase__ ,unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () SCREAMING_SNAKE_CASE__ : Tuple = (TFXGLMForCausalLM,) if is_tf_available() else () SCREAMING_SNAKE_CASE__ : List[str] = ( {"""feature-extraction""": TFXGLMModel, """text-generation""": TFXGLMForCausalLM} if is_tf_available() else {} ) SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = False def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : str = TFXGLMModelTester(self ) UpperCAmelCase_ : Dict = ConfigTester(self , config_class=lowercase_ , n_embd=37 ) def UpperCamelCase__ ( self ): """simple docstring""" self.config_tester.run_common_tests() @slow def UpperCamelCase__ ( self ): """simple docstring""" for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : Union[str, Any] = TFXGLMModel.from_pretrained(lowercase_ ) self.assertIsNotNone(lowercase_ ) @unittest.skip(reason="Currently, model embeddings are going to undergo a major refactor." ) def UpperCamelCase__ ( self ): """simple docstring""" super().test_resize_token_embeddings() @require_tf class A_ (unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase__ ( self , lowercase_=True ): """simple docstring""" UpperCAmelCase_ : List[Any] = TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M" ) UpperCAmelCase_ : Union[str, Any] = tf.convert_to_tensor([[2, 268, 9865]] , dtype=tf.intaa ) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off UpperCAmelCase_ : Tuple = [2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581] # fmt: on UpperCAmelCase_ : List[str] = model.generate(lowercase_ , do_sample=lowercase_ , num_beams=1 ) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , lowercase_ ) @slow def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Any = XGLMTokenizer.from_pretrained("facebook/xglm-564M" ) UpperCAmelCase_ : Any = TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M" ) tf.random.set_seed(0 ) UpperCAmelCase_ : Optional[Any] = tokenizer("Today is a nice day and" , return_tensors="tf" ) UpperCAmelCase_ : Optional[Any] = tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(":/CPU:0" ): UpperCAmelCase_ : List[Any] = model.generate(lowercase_ , do_sample=lowercase_ , seed=[7, 0] ) UpperCAmelCase_ : Dict = tokenizer.decode(output_ids[0] , skip_special_tokens=lowercase_ ) UpperCAmelCase_ : Dict = ( "Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due" ) self.assertEqual(lowercase_ , lowercase_ ) @slow def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Any = TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M" ) UpperCAmelCase_ : Tuple = XGLMTokenizer.from_pretrained("facebook/xglm-564M" ) UpperCAmelCase_ : Any = "left" # use different length sentences to test batching UpperCAmelCase_ : List[str] = [ "This is an extremelly long sentence that only exists to test the ability of the model to cope with " "left-padding, such as in batched generation. The output for the sequence below should be the same " "regardless of whether left padding is applied or not. When", "Hello, my dog is a little", ] UpperCAmelCase_ : List[Any] = tokenizer(lowercase_ , return_tensors="tf" , padding=lowercase_ ) UpperCAmelCase_ : Optional[int] = inputs["input_ids"] UpperCAmelCase_ : Union[str, Any] = model.generate(input_ids=lowercase_ , attention_mask=inputs["attention_mask"] , max_new_tokens=12 ) UpperCAmelCase_ : Optional[int] = tokenizer(sentences[0] , return_tensors="tf" ).input_ids UpperCAmelCase_ : Optional[Any] = model.generate(input_ids=lowercase_ , max_new_tokens=12 ) UpperCAmelCase_ : List[str] = tokenizer(sentences[1] , return_tensors="tf" ).input_ids UpperCAmelCase_ : List[Any] = model.generate(input_ids=lowercase_ , max_new_tokens=12 ) UpperCAmelCase_ : Optional[int] = tokenizer.batch_decode(lowercase_ , skip_special_tokens=lowercase_ ) UpperCAmelCase_ : List[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=lowercase_ ) UpperCAmelCase_ : List[Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=lowercase_ ) UpperCAmelCase_ : Tuple = [ "This is an extremelly long sentence that only exists to test the ability of the model to cope with " "left-padding, such as in batched generation. The output for the sequence below should be the same " "regardless of whether left padding is applied or not. When left padding is applied, the sequence will be " "a single", "Hello, my dog is a little bit of a shy one, but he is very friendly", ] self.assertListEqual(lowercase_ , lowercase_ ) self.assertListEqual(lowercase_ , [non_padded_sentence, padded_sentence] )
61
import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging _lowerCamelCase : Optional[Any] = logging.get_logger(__name__) _lowerCamelCase : Dict = {"vocab_file": "vocab.txt"} _lowerCamelCase : List[str] = { "vocab_file": { "facebook/esm2_t6_8M_UR50D": "https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt", "facebook/esm2_t12_35M_UR50D": "https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt", }, } _lowerCamelCase : List[Any] = { "facebook/esm2_t6_8M_UR50D": 1_0_2_4, "facebook/esm2_t12_35M_UR50D": 1_0_2_4, } def a__ ( UpperCAmelCase : List[str] ) -> Any: with open(UpperCAmelCase , '''r''' ) as f: UpperCAmelCase : Dict = f.read().splitlines() return [l.strip() for l in lines] class __UpperCAmelCase ( lowerCamelCase__ ): UpperCamelCase = VOCAB_FILES_NAMES UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase = ["""input_ids""", """attention_mask"""] def __init__( self : Any, __A : Dict, __A : List[Any]="<unk>", __A : List[str]="<cls>", __A : Any="<pad>", __A : Union[str, Any]="<mask>", __A : int="<eos>", **__A : Tuple, ): super().__init__(**__A ) UpperCAmelCase : Tuple = load_vocab_file(__A ) UpperCAmelCase : List[Any] = dict(enumerate(self.all_tokens ) ) UpperCAmelCase : str = {tok: ind for ind, tok in enumerate(self.all_tokens )} UpperCAmelCase : Union[str, Any] = unk_token UpperCAmelCase : Optional[Any] = cls_token UpperCAmelCase : Optional[int] = pad_token UpperCAmelCase : Optional[int] = mask_token UpperCAmelCase : List[str] = eos_token UpperCAmelCase : Optional[Any] = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __magic_name__ ( self : Tuple, __A : int ): return self._id_to_token.get(__A, self.unk_token ) def __magic_name__ ( self : List[Any], __A : str ): return self._token_to_id.get(__A, self._token_to_id.get(self.unk_token ) ) def __magic_name__ ( self : Any, __A : Optional[Any], **__A : Union[str, Any] ): return text.split() def __magic_name__ ( self : Optional[int], __A : Dict=False ): return len(self._id_to_token ) def __magic_name__ ( self : int ): return {token: i for i, token in enumerate(self.all_tokens )} def __magic_name__ ( self : Tuple, __A : str ): return self._token_to_id.get(__A, self._token_to_id.get(self.unk_token ) ) def __magic_name__ ( self : Any, __A : int ): return self._id_to_token.get(__A, self.unk_token ) def __magic_name__ ( self : Union[str, Any], __A : List[int], __A : Optional[List[int]] = None ): UpperCAmelCase : Optional[int] = [self.cls_token_id] UpperCAmelCase : Optional[int] = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('''Cannot tokenize multiple sequences when EOS token is not set!''' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __magic_name__ ( self : Any, __A : List, __A : Optional[List] = None, __A : bool = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] UpperCAmelCase : Dict = [1] + ([0] * len(__A )) + [1] if token_ids_a is not None: mask += [0] * len(__A ) + [1] return mask def __magic_name__ ( self : Optional[int], __A : List[Any], __A : Dict ): UpperCAmelCase : Union[str, Any] = os.path.join(__A, (filename_prefix + '''-''' if filename_prefix else '''''') + '''vocab.txt''' ) with open(__A, '''w''' ) as f: f.write('''\n'''.join(self.all_tokens ) ) return (vocab_file,) @property def __magic_name__ ( self : Dict ): return self.get_vocab_size(with_added_tokens=__A ) def __magic_name__ ( self : Optional[int], __A : Union[List[str], List[AddedToken]], __A : bool = False ): return super()._add_tokens(__A, special_tokens=__A )
336
0
'''simple docstring''' import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging snake_case_ : List[Any] = logging.get_logger(__name__) snake_case_ : str = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'} # See all BART models at https://huggingface.co/models?filter=bart snake_case_ : Union[str, Any] = { 'vocab_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/vocab.json', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/vocab.json', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json', }, 'merges_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/merges.txt', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/merges.txt', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt', }, } snake_case_ : Any = { 'facebook/bart-base': 1024, 'facebook/bart-large': 1024, 'facebook/bart-large-mnli': 1024, 'facebook/bart-large-cnn': 1024, 'facebook/bart-large-xsum': 1024, 'yjernite/bart_eli5': 1024, } @lru_cache() def A__ ( ): _UpperCamelCase : str = ( list(range(ord('!' ) , ord('~' ) + 1 ) ) + list(range(ord('¡' ) , ord('¬' ) + 1 ) ) + list(range(ord('®' ) , ord('ÿ' ) + 1 ) ) ) _UpperCamelCase : Any = bs[:] _UpperCamelCase : Union[str, Any] = 0 for b in range(2**8 ): if b not in bs: bs.append(UpperCAmelCase_ ) cs.append(2**8 + n ) n += 1 _UpperCamelCase : Any = [chr(UpperCAmelCase_ ) for n in cs] return dict(zip(UpperCAmelCase_ , UpperCAmelCase_ ) ) def A__ ( UpperCAmelCase_ ): _UpperCamelCase : Tuple = set() _UpperCamelCase : Dict = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _UpperCamelCase : Any = char return pairs class lowercase__ ( lowercase ): lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["""input_ids""", """attention_mask"""] def __init__( self : Optional[int] ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Optional[Any]="replace" ,lowerCamelCase__ : str="<s>" ,lowerCamelCase__ : str="</s>" ,lowerCamelCase__ : str="</s>" ,lowerCamelCase__ : Any="<s>" ,lowerCamelCase__ : Tuple="<unk>" ,lowerCamelCase__ : List[str]="<pad>" ,lowerCamelCase__ : Optional[Any]="<mask>" ,lowerCamelCase__ : Tuple=False ,**lowerCamelCase__ : List[str] ,): '''simple docstring''' _UpperCamelCase : Dict = AddedToken(lowerCamelCase__ ,lstrip=lowerCamelCase__ ,rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ ,lowerCamelCase__ ) else bos_token _UpperCamelCase : Tuple = AddedToken(lowerCamelCase__ ,lstrip=lowerCamelCase__ ,rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ ,lowerCamelCase__ ) else eos_token _UpperCamelCase : Optional[int] = AddedToken(lowerCamelCase__ ,lstrip=lowerCamelCase__ ,rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ ,lowerCamelCase__ ) else sep_token _UpperCamelCase : Tuple = AddedToken(lowerCamelCase__ ,lstrip=lowerCamelCase__ ,rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ ,lowerCamelCase__ ) else cls_token _UpperCamelCase : Union[str, Any] = AddedToken(lowerCamelCase__ ,lstrip=lowerCamelCase__ ,rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ ,lowerCamelCase__ ) else unk_token _UpperCamelCase : List[str] = AddedToken(lowerCamelCase__ ,lstrip=lowerCamelCase__ ,rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ ,lowerCamelCase__ ) else pad_token # 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 super().__init__( errors=lowerCamelCase__ ,bos_token=lowerCamelCase__ ,eos_token=lowerCamelCase__ ,unk_token=lowerCamelCase__ ,sep_token=lowerCamelCase__ ,cls_token=lowerCamelCase__ ,pad_token=lowerCamelCase__ ,mask_token=lowerCamelCase__ ,add_prefix_space=lowerCamelCase__ ,**lowerCamelCase__ ,) with open(lowerCamelCase__ ,encoding='utf-8' ) as vocab_handle: _UpperCamelCase : List[str] = json.load(lowerCamelCase__ ) _UpperCamelCase : Union[str, Any] = {v: k for k, v in self.encoder.items()} _UpperCamelCase : Optional[Any] = errors # how to handle errors in decoding _UpperCamelCase : Tuple = bytes_to_unicode() _UpperCamelCase : List[str] = {v: k for k, v in self.byte_encoder.items()} with open(lowerCamelCase__ ,encoding='utf-8' ) as merges_handle: _UpperCamelCase : Dict = merges_handle.read().split('\n' )[1:-1] _UpperCamelCase : str = [tuple(merge.split() ) for merge in bpe_merges] _UpperCamelCase : Dict = dict(zip(lowerCamelCase__ ,range(len(lowerCamelCase__ ) ) ) ) _UpperCamelCase : Tuple = {} _UpperCamelCase : List[Any] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions _UpperCamelCase : Any = re.compile(R'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' ) @property def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' return len(self.encoder ) def UpperCamelCase_ ( self : str ): '''simple docstring''' return dict(self.encoder ,**self.added_tokens_encoder ) def UpperCamelCase_ ( self : str ,lowerCamelCase__ : Any ): '''simple docstring''' if token in self.cache: return self.cache[token] _UpperCamelCase : Dict = tuple(lowerCamelCase__ ) _UpperCamelCase : List[str] = get_pairs(lowerCamelCase__ ) if not pairs: return token while True: _UpperCamelCase : List[str] = min(lowerCamelCase__ ,key=lambda lowerCamelCase__ : self.bpe_ranks.get(lowerCamelCase__ ,float('inf' ) ) ) if bigram not in self.bpe_ranks: break _UpperCamelCase , _UpperCamelCase : int = bigram _UpperCamelCase : Optional[int] = [] _UpperCamelCase : Dict = 0 while i < len(lowerCamelCase__ ): try: _UpperCamelCase : int = word.index(lowerCamelCase__ ,lowerCamelCase__ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) _UpperCamelCase : Dict = j if word[i] == first and i < len(lowerCamelCase__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _UpperCamelCase : int = tuple(lowerCamelCase__ ) _UpperCamelCase : Union[str, Any] = new_word if len(lowerCamelCase__ ) == 1: break else: _UpperCamelCase : Any = get_pairs(lowerCamelCase__ ) _UpperCamelCase : int = ' '.join(lowerCamelCase__ ) _UpperCamelCase : List[Any] = word return word def UpperCamelCase_ ( self : List[str] ,lowerCamelCase__ : Optional[Any] ): '''simple docstring''' _UpperCamelCase : int = [] for token in re.findall(self.pat ,lowerCamelCase__ ): _UpperCamelCase : int = ''.join( self.byte_encoder[b] for b in token.encode('utf-8' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(lowerCamelCase__ ).split(' ' ) ) return bpe_tokens def UpperCamelCase_ ( self : List[Any] ,lowerCamelCase__ : List[Any] ): '''simple docstring''' return self.encoder.get(lowerCamelCase__ ,self.encoder.get(self.unk_token ) ) def UpperCamelCase_ ( self : Optional[Any] ,lowerCamelCase__ : int ): '''simple docstring''' return self.decoder.get(lowerCamelCase__ ) def UpperCamelCase_ ( self : List[Any] ,lowerCamelCase__ : Any ): '''simple docstring''' _UpperCamelCase : Dict = ''.join(lowerCamelCase__ ) _UpperCamelCase : Dict = bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8' ,errors=self.errors ) return text def UpperCamelCase_ ( self : Optional[Any] ,lowerCamelCase__ : str ,lowerCamelCase__ : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(lowerCamelCase__ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return _UpperCamelCase : List[Any] = os.path.join( lowerCamelCase__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) _UpperCamelCase : Union[str, Any] = os.path.join( lowerCamelCase__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(lowerCamelCase__ ,'w' ,encoding='utf-8' ) as f: f.write(json.dumps(self.encoder ,indent=2 ,sort_keys=lowerCamelCase__ ,ensure_ascii=lowerCamelCase__ ) + '\n' ) _UpperCamelCase : Optional[Any] = 0 with open(lowerCamelCase__ ,'w' ,encoding='utf-8' ) as writer: writer.write('#version: 0.2\n' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() ,key=lambda lowerCamelCase__ : kv[1] ): if index != token_index: logger.warning( F'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.' ' Please check that the tokenizer is not corrupted!' ) _UpperCamelCase : int = token_index writer.write(' '.join(lowerCamelCase__ ) + '\n' ) index += 1 return vocab_file, merge_file def UpperCamelCase_ ( self : Any ,lowerCamelCase__ : List[int] ,lowerCamelCase__ : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _UpperCamelCase : Optional[Any] = [self.cls_token_id] _UpperCamelCase : str = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase_ ( self : List[str] ,lowerCamelCase__ : List[int] ,lowerCamelCase__ : Optional[List[int]] = None ,lowerCamelCase__ : bool = False ): '''simple docstring''' 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 : Tuple ,lowerCamelCase__ : List[int] ,lowerCamelCase__ : Optional[List[int]] = None ): '''simple docstring''' _UpperCamelCase : Tuple = [self.sep_token_id] _UpperCamelCase : Dict = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def UpperCamelCase_ ( self : Any ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Tuple=False ,**lowerCamelCase__ : Optional[int] ): '''simple docstring''' _UpperCamelCase : Tuple = kwargs.pop('add_prefix_space' ,self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(lowerCamelCase__ ) > 0 and not text[0].isspace()): _UpperCamelCase : List[str] = ' ' + text return (text, kwargs)
236
'''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 snake_case_ : List[str] = '\\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' snake_case_ : Tuple = '\\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' snake_case_ : str = '\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' snake_case_ : str = '\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' snake_case_ : List[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 lowercase__ ( datasets.Metric ): def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' 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 UpperCamelCase_ ( self : str ,lowerCamelCase__ : Dict ,lowerCamelCase__ : Dict ,lowerCamelCase__ : List[Any]=[1, 10, 100] ,lowerCamelCase__ : int=4 ,lowerCamelCase__ : List[Any]=3.0 ): '''simple docstring''' 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=lowerCamelCase__ ) as executor: _UpperCamelCase : Optional[int] = [] _UpperCamelCase : Optional[int] = Counter() _UpperCamelCase : int = 0 _UpperCamelCase : Dict = defaultdict(lowerCamelCase__ ) for task_id, (candidates, test_case) in enumerate(zip(lowerCamelCase__ ,lowerCamelCase__ ) ): for candidate in candidates: _UpperCamelCase : int = candidate + '\n' + test_case _UpperCamelCase : Optional[Any] = (test_program, timeout, task_id, completion_id[task_id]) _UpperCamelCase : Dict = executor.submit(lowerCamelCase__ ,*lowerCamelCase__ ) futures.append(lowerCamelCase__ ) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(lowerCamelCase__ ): _UpperCamelCase : Dict = future.result() results[result["task_id"]].append((result['completion_id'], result) ) _UpperCamelCase , _UpperCamelCase : List[str] = [], [] for result in results.values(): result.sort() _UpperCamelCase : Optional[Any] = [r[1]['passed'] for r in result] total.append(len(lowerCamelCase__ ) ) correct.append(sum(lowerCamelCase__ ) ) _UpperCamelCase : List[str] = np.array(lowerCamelCase__ ) _UpperCamelCase : List[Any] = np.array(lowerCamelCase__ ) _UpperCamelCase : Tuple = k _UpperCamelCase : Tuple = {F'pass@{k}': estimate_pass_at_k(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ).mean() for k in ks if (total >= k).all()} return pass_at_k, results def A__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): def estimator(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) -> 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(UpperCAmelCase_ , UpperCAmelCase_ ): _UpperCamelCase : int = itertools.repeat(UpperCAmelCase_ , len(UpperCAmelCase_ ) ) else: assert len(UpperCAmelCase_ ) == len(UpperCAmelCase_ ) _UpperCamelCase : Optional[Any] = iter(UpperCAmelCase_ ) return np.array([estimator(int(UpperCAmelCase_ ) , int(UpperCAmelCase_ ) , UpperCAmelCase_ ) for n, c in zip(UpperCAmelCase_ , UpperCAmelCase_ )] )
236
1
"""simple docstring""" import inspect import unittest from transformers import ConvNextConfig 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, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCamelCase__ : """simple docstring""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[Any]=1_3 , SCREAMING_SNAKE_CASE_ : str=3_2 , SCREAMING_SNAKE_CASE_ : List[Any]=3 , SCREAMING_SNAKE_CASE_ : List[Any]=4 , SCREAMING_SNAKE_CASE_ : List[Any]=[1_0, 2_0, 3_0, 4_0] , SCREAMING_SNAKE_CASE_ : List[Any]=[2, 2, 3, 2] , SCREAMING_SNAKE_CASE_ : str=True , SCREAMING_SNAKE_CASE_ : str=True , SCREAMING_SNAKE_CASE_ : Tuple=3_7 , SCREAMING_SNAKE_CASE_ : int="gelu" , SCREAMING_SNAKE_CASE_ : Union[str, Any]=1_0 , SCREAMING_SNAKE_CASE_ : str=0.02 , SCREAMING_SNAKE_CASE_ : Tuple=["stage2", "stage3", "stage4"] , SCREAMING_SNAKE_CASE_ : List[Any]=[2, 3, 4] , SCREAMING_SNAKE_CASE_ : Optional[Any]=None , ): lowerCAmelCase_ : Tuple = parent lowerCAmelCase_ : int = batch_size lowerCAmelCase_ : List[str] = image_size lowerCAmelCase_ : List[Any] = num_channels lowerCAmelCase_ : Tuple = num_stages lowerCAmelCase_ : Optional[int] = hidden_sizes lowerCAmelCase_ : int = depths lowerCAmelCase_ : Tuple = is_training lowerCAmelCase_ : Optional[Any] = use_labels lowerCAmelCase_ : List[str] = intermediate_size lowerCAmelCase_ : Dict = hidden_act lowerCAmelCase_ : Dict = num_labels lowerCAmelCase_ : Optional[int] = initializer_range lowerCAmelCase_ : Optional[Any] = out_features lowerCAmelCase_ : Optional[Any] = out_indices lowerCAmelCase_ : Optional[int] = scope def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): lowerCAmelCase_ : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase_ : Optional[Any] = None if self.use_labels: lowerCAmelCase_ : Optional[Any] = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase_ : Dict = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ ( self : Dict ): return ConvNextConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Any ): lowerCAmelCase_ : Tuple = ConvNextModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCAmelCase_ : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def SCREAMING_SNAKE_CASE__ ( self : Tuple , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Dict ): lowerCAmelCase_ : Optional[int] = ConvNextForImageClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCAmelCase_ : str = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] ): lowerCAmelCase_ : int = ConvNextBackbone(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCAmelCase_ : Optional[int] = model(SCREAMING_SNAKE_CASE_ ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # 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 lowerCAmelCase_ : List[str] = None lowerCAmelCase_ : Any = ConvNextBackbone(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCAmelCase_ : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): lowerCAmelCase_ : Union[str, Any] = self.prepare_config_and_inputs() lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ : Tuple = config_and_inputs lowerCAmelCase_ : Any = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class UpperCamelCase__ ( lowercase_, lowercase_, unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = ( ( ConvNextModel, ConvNextForImageClassification, ConvNextBackbone, ) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE = ( {"""feature-extraction""": ConvNextModel, """image-classification""": ConvNextForImageClassification} if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False def SCREAMING_SNAKE_CASE__ ( self : int ): lowerCAmelCase_ : List[str] = ConvNextModelTester(self ) lowerCAmelCase_ : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): 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 SCREAMING_SNAKE_CASE__ ( self : Tuple ): return @unittest.skip(reason='ConvNext does not use inputs_embeds' ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): pass @unittest.skip(reason='ConvNext does not support input and output embeddings' ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): pass @unittest.skip(reason='ConvNext does not use feedforward chunking' ) def SCREAMING_SNAKE_CASE__ ( self : str ): pass def SCREAMING_SNAKE_CASE__ ( self : Tuple ): lowerCAmelCase_ ,lowerCAmelCase_ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase_ : Any = model_class(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase_ : List[str] = [*signature.parameters.keys()] lowerCAmelCase_ : Tuple = ['pixel_values'] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): lowerCAmelCase_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): lowerCAmelCase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*SCREAMING_SNAKE_CASE_ ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): def check_hidden_states_output(SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : int ): lowerCAmelCase_ : int = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() with torch.no_grad(): lowerCAmelCase_ : Union[str, Any] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) lowerCAmelCase_ : Any = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCAmelCase_ : int = self.model_tester.num_stages self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) lowerCAmelCase_ ,lowerCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase_ : str = True check_hidden_states_output(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase_ : Dict = True check_hidden_states_output(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def SCREAMING_SNAKE_CASE__ ( self : int ): lowerCAmelCase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_ ) @slow def SCREAMING_SNAKE_CASE__ ( self : Any ): for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase_ : Optional[Any] = ConvNextModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase_ ( ) -> List[str]: """simple docstring""" lowerCAmelCase_ : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" @cached_property def SCREAMING_SNAKE_CASE__ ( self : int ): return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224' ) if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): lowerCAmelCase_ : Optional[Any] = ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224' ).to(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : Union[str, Any] = self.default_image_processor lowerCAmelCase_ : Union[str, Any] = prepare_img() lowerCAmelCase_ : Any = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='pt' ).to(SCREAMING_SNAKE_CASE_ ) # forward pass with torch.no_grad(): lowerCAmelCase_ : Any = model(**SCREAMING_SNAKE_CASE_ ) # verify the logits lowerCAmelCase_ : Optional[Any] = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : Optional[int] = torch.tensor([-0.02_60, -0.47_39, 0.19_11] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) ) @require_torch class UpperCamelCase__ ( unittest.TestCase, lowercase_ ): """simple docstring""" _SCREAMING_SNAKE_CASE = (ConvNextBackbone,) if is_torch_available() else () _SCREAMING_SNAKE_CASE = ConvNextConfig _SCREAMING_SNAKE_CASE = False def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): lowerCAmelCase_ : List[str] = ConvNextModelTester(self )
224
"""simple docstring""" from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig 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 TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCamelCase__ : """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[Any]=3 , SCREAMING_SNAKE_CASE_ : Any=3_2 , SCREAMING_SNAKE_CASE_ : int=3 , SCREAMING_SNAKE_CASE_ : Optional[Any]=1_0 , SCREAMING_SNAKE_CASE_ : Dict=[1_0, 2_0, 3_0, 4_0] , SCREAMING_SNAKE_CASE_ : int=[1, 1, 2, 1] , SCREAMING_SNAKE_CASE_ : int=True , SCREAMING_SNAKE_CASE_ : Optional[Any]=True , SCREAMING_SNAKE_CASE_ : int="relu" , SCREAMING_SNAKE_CASE_ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE_ : List[str]=None , ): lowerCAmelCase_ : Optional[int] = parent lowerCAmelCase_ : Union[str, Any] = batch_size lowerCAmelCase_ : Optional[int] = image_size lowerCAmelCase_ : Optional[int] = num_channels lowerCAmelCase_ : Any = embeddings_size lowerCAmelCase_ : Dict = hidden_sizes lowerCAmelCase_ : Any = depths lowerCAmelCase_ : Optional[int] = is_training lowerCAmelCase_ : int = use_labels lowerCAmelCase_ : List[Any] = hidden_act lowerCAmelCase_ : Dict = num_labels lowerCAmelCase_ : Optional[int] = scope lowerCAmelCase_ : Tuple = len(SCREAMING_SNAKE_CASE_ ) def SCREAMING_SNAKE_CASE__ ( self : Any ): lowerCAmelCase_ : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase_ : Union[str, Any] = None if self.use_labels: lowerCAmelCase_ : int = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase_ : List[str] = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ ( self : str ): return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE__ ( self : Any , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : int ): lowerCAmelCase_ : List[Any] = TFRegNetModel(config=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : List[Any] = model(SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def SCREAMING_SNAKE_CASE__ ( self : List[str] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[Any] ): lowerCAmelCase_ : int = self.num_labels lowerCAmelCase_ : int = TFRegNetForImageClassification(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : Dict = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): lowerCAmelCase_ : str = self.prepare_config_and_inputs() lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ : Tuple = config_and_inputs lowerCAmelCase_ : Optional[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class UpperCamelCase__ ( lowercase_, lowercase_, unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () _SCREAMING_SNAKE_CASE = ( {"""feature-extraction""": TFRegNetModel, """image-classification""": TFRegNetForImageClassification} if is_tf_available() else {} ) _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): lowerCAmelCase_ : List[Any] = TFRegNetModelTester(self ) lowerCAmelCase_ : Tuple = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): return @unittest.skip(reason='RegNet does not use inputs_embeds' ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) @slow def SCREAMING_SNAKE_CASE__ ( self : Tuple ): super().test_keras_fit() @unittest.skip(reason='RegNet does not support input and output embeddings' ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): pass def SCREAMING_SNAKE_CASE__ ( self : int ): lowerCAmelCase_ ,lowerCAmelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase_ : int = model_class(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : Dict = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase_ : List[Any] = [*signature.parameters.keys()] lowerCAmelCase_ : Any = ['pixel_values'] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) def SCREAMING_SNAKE_CASE__ ( self : Any ): lowerCAmelCase_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): def check_hidden_states_output(SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Tuple ): lowerCAmelCase_ : List[Any] = model_class(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : Union[str, Any] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , training=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : List[str] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCAmelCase_ : Union[str, Any] = self.model_tester.num_stages self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) lowerCAmelCase_ ,lowerCAmelCase_ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase_ : Optional[int] = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: lowerCAmelCase_ : str = layer_type lowerCAmelCase_ : List[str] = True check_hidden_states_output(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase_ : List[str] = True check_hidden_states_output(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): lowerCAmelCase_ ,lowerCAmelCase_ : int = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : str={} ): lowerCAmelCase_ : Optional[Any] = model(SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : List[Any] = model(SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).to_tuple() def recursive_check(SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ): if isinstance(SCREAMING_SNAKE_CASE_ , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): recursive_check(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) , msg=( 'Tuple and dict output are not equal. Difference:' F" {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}" ) , ) recursive_check(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for model_class in self.all_model_classes: lowerCAmelCase_ : Union[str, Any] = model_class(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : List[Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : Union[str, Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) check_equivalence(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : Optional[int] = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : str = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) check_equivalence(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : Tuple = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : int = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) check_equivalence(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , {'output_hidden_states': True} ) lowerCAmelCase_ : List[Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : Any = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) check_equivalence(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , {'output_hidden_states': True} ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): lowerCAmelCase_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_ ) @slow def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase_ : int = TFRegNetModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCamelCase_ ( ) -> List[str]: """simple docstring""" lowerCAmelCase_ : Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" @cached_property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): lowerCAmelCase_ : int = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) lowerCAmelCase_ : Tuple = self.default_image_processor lowerCAmelCase_ : Dict = prepare_img() lowerCAmelCase_ : Union[str, Any] = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='tf' ) # forward pass lowerCAmelCase_ : List[str] = model(**SCREAMING_SNAKE_CASE_ , training=SCREAMING_SNAKE_CASE_ ) # verify the logits lowerCAmelCase_ : Optional[Any] = tf.TensorShape((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : List[Any] = tf.constant([-0.41_80, -1.50_51, -3.48_36] ) tf.debugging.assert_near(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 )
224
1
"""simple docstring""" import json import os import shutil import warnings from argparse import ArgumentParser, Namespace from pathlib import Path from typing import List from ..utils import logging from . import BaseTransformersCLICommand try: from cookiecutter.main import cookiecutter A__ : Any = True except ImportError: A__ : Optional[Any] = False A__ : List[str] = logging.get_logger(__name__) # pylint: disable=invalid-name def _snake_case ( lowerCamelCase__ : Namespace ) -> Dict: return AddNewModelCommand(args.testing , args.testing_file , path=args.path ) class lowercase__ ( snake_case__ ): @staticmethod def UpperCAmelCase__ ( snake_case__ : List[str] ): lowerCamelCase_ : Any =parser.add_parser("add-new-model" ) add_new_model_parser.add_argument("--testing" , action="store_true" , help="If in testing mode." ) add_new_model_parser.add_argument("--testing_file" , type=_a , help="Configuration file on which to run." ) add_new_model_parser.add_argument( "--path" , type=_a , help="Path to cookiecutter. Should only be used for testing purposes." ) add_new_model_parser.set_defaults(func=_a ) def __init__( self : Union[str, Any] , snake_case__ : Optional[int] , snake_case__ : Optional[Any] , snake_case__ : List[str]=None , *snake_case__ : List[Any] ): lowerCamelCase_ : Dict =testing lowerCamelCase_ : Tuple =testing_file lowerCamelCase_ : int =path def UpperCAmelCase__ ( self : Optional[Any] ): warnings.warn( "The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. " "It is not actively maintained anymore, so might give a result that won't pass all tests and quality " "checks, you should use `transformers-cli add-new-model-like` instead." ) if not _has_cookiecutter: raise ImportError( "Model creation dependencies are required to use the `add_new_model` command. Install them by running " "the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n" ) # Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory lowerCamelCase_ : Any =[directory for directory in os.listdir() if "cookiecutter-template-" == directory[:22]] if len(_a ) > 0: raise ValueError( "Several directories starting with `cookiecutter-template-` in current working directory. " "Please clean your directory by removing all folders starting with `cookiecutter-template-` or " "change your working directory." ) lowerCamelCase_ : Tuple =( Path(_a ).parent.parent.parent.parent if self._path is None else Path(self._path ).parent.parent ) lowerCamelCase_ : List[Any] =path_to_transformer_root / "templates" / "adding_a_new_model" # Execute cookiecutter if not self._testing: cookiecutter(str(_a ) ) else: with open(self._testing_file , "r" ) as configuration_file: lowerCamelCase_ : int =json.load(_a ) cookiecutter( str(path_to_cookiecutter if self._path is None else self._path ) , no_input=_a , extra_context=_a , ) lowerCamelCase_ : Optional[Any] =[directory for directory in os.listdir() if "cookiecutter-template-" in directory[:22]][0] # Retrieve configuration with open(directory + "/configuration.json" , "r" ) as configuration_file: lowerCamelCase_ : Any =json.load(_a ) lowerCamelCase_ : Tuple =configuration["lowercase_modelname"] lowerCamelCase_ : Optional[Any] =configuration["generate_tensorflow_pytorch_and_flax"] os.remove(F"""{directory}/configuration.json""" ) lowerCamelCase_ : List[Any] ="PyTorch" in generate_tensorflow_pytorch_and_flax lowerCamelCase_ : int ="TensorFlow" in generate_tensorflow_pytorch_and_flax lowerCamelCase_ : List[Any] ="Flax" in generate_tensorflow_pytorch_and_flax lowerCamelCase_ : Tuple =F"""{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}""" os.makedirs(_a , exist_ok=_a ) os.makedirs(F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}""" , exist_ok=_a ) # Tests require submodules as they have parent imports with open(F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py""" , "w" ): pass shutil.move( F"""{directory}/__init__.py""" , F"""{model_dir}/__init__.py""" , ) shutil.move( F"""{directory}/configuration_{lowercase_model_name}.py""" , F"""{model_dir}/configuration_{lowercase_model_name}.py""" , ) def remove_copy_lines(snake_case__ : Any ): with open(_a , "r" ) as f: lowerCamelCase_ : int =f.readlines() with open(_a , "w" ) as f: for line in lines: if "# Copied from transformers." not in line: f.write(_a ) if output_pytorch: if not self._testing: remove_copy_lines(F"""{directory}/modeling_{lowercase_model_name}.py""" ) shutil.move( F"""{directory}/modeling_{lowercase_model_name}.py""" , F"""{model_dir}/modeling_{lowercase_model_name}.py""" , ) shutil.move( F"""{directory}/test_modeling_{lowercase_model_name}.py""" , F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py""" , ) else: os.remove(F"""{directory}/modeling_{lowercase_model_name}.py""" ) os.remove(F"""{directory}/test_modeling_{lowercase_model_name}.py""" ) if output_tensorflow: if not self._testing: remove_copy_lines(F"""{directory}/modeling_tf_{lowercase_model_name}.py""" ) shutil.move( F"""{directory}/modeling_tf_{lowercase_model_name}.py""" , F"""{model_dir}/modeling_tf_{lowercase_model_name}.py""" , ) shutil.move( F"""{directory}/test_modeling_tf_{lowercase_model_name}.py""" , F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py""" , ) else: os.remove(F"""{directory}/modeling_tf_{lowercase_model_name}.py""" ) os.remove(F"""{directory}/test_modeling_tf_{lowercase_model_name}.py""" ) if output_flax: if not self._testing: remove_copy_lines(F"""{directory}/modeling_flax_{lowercase_model_name}.py""" ) shutil.move( F"""{directory}/modeling_flax_{lowercase_model_name}.py""" , F"""{model_dir}/modeling_flax_{lowercase_model_name}.py""" , ) shutil.move( F"""{directory}/test_modeling_flax_{lowercase_model_name}.py""" , F"""{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py""" , ) else: os.remove(F"""{directory}/modeling_flax_{lowercase_model_name}.py""" ) os.remove(F"""{directory}/test_modeling_flax_{lowercase_model_name}.py""" ) shutil.move( F"""{directory}/{lowercase_model_name}.md""" , F"""{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md""" , ) shutil.move( F"""{directory}/tokenization_{lowercase_model_name}.py""" , F"""{model_dir}/tokenization_{lowercase_model_name}.py""" , ) shutil.move( F"""{directory}/tokenization_fast_{lowercase_model_name}.py""" , F"""{model_dir}/tokenization_{lowercase_model_name}_fast.py""" , ) from os import fdopen, remove from shutil import copymode, move from tempfile import mkstemp def replace(snake_case__ : Union[str, Any] , snake_case__ : int , snake_case__ : Union[str, Any] ): # Create temp file lowerCamelCase_ : List[str] =mkstemp() lowerCamelCase_ : Tuple =False with fdopen(_a , "w" ) as new_file: with open(_a ) as old_file: for line in old_file: new_file.write(_a ) if line_to_copy_below in line: lowerCamelCase_ : str =True for line_to_copy in lines_to_copy: new_file.write(_a ) if not line_found: raise ValueError(F"""Line {line_to_copy_below} was not found in file.""" ) # Copy the file permissions from the old file to the new file copymode(_a , _a ) # Remove original file remove(_a ) # Move new file move(_a , _a ) def skip_units(snake_case__ : List[str] ): return ( ("generating PyTorch" in line and not output_pytorch) or ("generating TensorFlow" in line and not output_tensorflow) or ("generating Flax" in line and not output_flax) ) def replace_in_files(snake_case__ : Optional[Any] ): with open(_a ) as datafile: lowerCamelCase_ : Tuple =[] lowerCamelCase_ : str =False lowerCamelCase_ : Tuple =False for line in datafile: if "# To replace in: " in line and "##" not in line: lowerCamelCase_ : int =line.split("\"" )[1] lowerCamelCase_ : Optional[Any] =skip_units(_a ) elif "# Below: " in line and "##" not in line: lowerCamelCase_ : Any =line.split("\"" )[1] lowerCamelCase_ : str =skip_units(_a ) elif "# End." in line and "##" not in line: if not skip_file and not skip_snippet: replace(_a , _a , _a ) lowerCamelCase_ : Optional[Any] =[] elif "# Replace with" in line and "##" not in line: lowerCamelCase_ : Dict =[] elif "##" not in line: lines_to_copy.append(_a ) remove(_a ) replace_in_files(F"""{directory}/to_replace_{lowercase_model_name}.py""" ) os.rmdir(_a )
369
"""simple docstring""" import darl # noqa import gym import tqdm from diffusers.experimental import ValueGuidedRLPipeline A__ : int = { 'n_samples': 64, 'horizon': 32, 'num_inference_steps': 20, 'n_guide_steps': 2, # can set to 0 for faster sampling, does not use value network 'scale_grad_by_std': True, 'scale': 0.1, 'eta': 0.0, 't_grad_cutoff': 2, 'device': 'cpu', } if __name__ == "__main__": A__ : str = 'hopper-medium-v2' A__ : Dict = gym.make(env_name) A__ : List[Any] = ValueGuidedRLPipeline.from_pretrained( 'bglick13/hopper-medium-v2-value-function-hor32', env=env, ) env.seed(0) A__ : Dict = env.reset() A__ : Optional[int] = 0 A__ : str = 0 A__ : List[Any] = 1_000 A__ : Tuple = [obs.copy()] try: for t in tqdm.tqdm(range(T)): # call the policy A__ : Union[str, Any] = pipeline(obs, planning_horizon=32) # execute action in environment A__ , A__ , A__ , A__ : Any = env.step(denorm_actions) A__ : List[Any] = env.get_normalized_score(total_reward) # update return total_reward += reward total_score += score print( f'Step: {t}, Reward: {reward}, Total Reward: {total_reward}, Score: {score}, Total Score:' f' {total_score}' ) # save observations for rendering rollout.append(next_observation.copy()) A__ : Optional[Any] = next_observation except KeyboardInterrupt: pass print(f'Total reward: {total_reward}')
209
0
'''simple docstring''' import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def UpperCAmelCase_ ( __lowerCamelCase : Tuple ,__lowerCamelCase : List[str] ,__lowerCamelCase : List[Any] ): # Construct model if gpta_config_file == "": lowercase_ :Optional[int] = GPTaConfig() else: lowercase_ :List[str] = GPTaConfig.from_json_file(__lowerCamelCase ) lowercase_ :Dict = GPTaModel(__lowerCamelCase ) # Load weights from numpy load_tf_weights_in_gpta(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) # Save pytorch-model lowercase_ :Tuple = pytorch_dump_folder_path + "/" + WEIGHTS_NAME lowercase_ :int = pytorch_dump_folder_path + "/" + CONFIG_NAME print(F'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() ,__lowerCamelCase ) print(F'Save configuration file to {pytorch_config_dump_path}' ) with open(__lowerCamelCase ,"w" ,encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": lowerCAmelCase : List[Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--gpt2_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--gpt2_config_file''', default='''''', type=str, help=( '''An optional config json file corresponding to the pre-trained OpenAI model. \n''' '''This specifies the model architecture.''' ), ) lowerCAmelCase : Optional[int] =parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
223
'''simple docstring''' import math def UpperCAmelCase_ ( __lowerCamelCase : int ): lowercase_ :Dict = [] lowercase_ :List[Any] = 2 lowercase_ :Optional[Any] = int(math.sqrt(__lowerCamelCase ) ) # Size of every segment lowercase_ :Optional[Any] = [True] * (end + 1) lowercase_ :Dict = [] while start <= end: if temp[start] is True: in_prime.append(__lowerCamelCase ) for i in range(start * start ,end + 1 ,__lowerCamelCase ): lowercase_ :List[str] = False start += 1 prime += in_prime lowercase_ :Dict = end + 1 lowercase_ :Dict = min(2 * end ,__lowerCamelCase ) while low <= n: lowercase_ :Any = [True] * (high - low + 1) for each in in_prime: lowercase_ :List[Any] = math.floor(low / each ) * each if t < low: t += each for j in range(__lowerCamelCase ,high + 1 ,__lowerCamelCase ): lowercase_ :str = False for j in range(len(__lowerCamelCase ) ): if temp[j] is True: prime.append(j + low ) lowercase_ :Dict = high + 1 lowercase_ :Dict = min(high + end ,__lowerCamelCase ) return prime print(sieve(10**6))
223
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor lowercase : List[str] = logging.get_logger(__name__) class __UpperCAmelCase ( _lowerCamelCase ): def __init__( self , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" warnings.warn( 'The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use LayoutLMv2ImageProcessor instead.' , lowerCAmelCase_ , ) super().__init__(*lowerCAmelCase_ , **lowerCAmelCase_ )
160
'''simple docstring''' import random from .binary_exp_mod import bin_exp_mod def SCREAMING_SNAKE_CASE__ ( __A , __A=1_000 ) -> str: if n < 2: return False if n % 2 == 0: return n == 2 # this means n is odd _snake_case = n - 1 _snake_case = 0 while d % 2 == 0: d /= 2 exp += 1 # n - 1=d*(2**exp) _snake_case = 0 while count < prec: _snake_case = random.randint(2 , n - 1 ) _snake_case = bin_exp_mod(__A , __A , __A ) if b != 1: _snake_case = True for _ in range(__A ): if b == n - 1: _snake_case = False break _snake_case = b * b b %= n if flag: return False count += 1 return True if __name__ == "__main__": lowercase : Optional[int] = abs(int(input("Enter bound : ").strip())) print("Here's the list of primes:") print(", ".join(str(i) for i in range(n + 1) if is_prime_big(i)))
160
1
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig _snake_case = logging.get_logger(__name__) # General docstring _snake_case = 'MobileNetV1Config' # Base docstring _snake_case = 'google/mobilenet_v1_1.0_224' _snake_case = [1, 1024, 7, 7] # Image classification docstring _snake_case = 'google/mobilenet_v1_1.0_224' _snake_case = 'tabby, tabby cat' _snake_case = [ 'google/mobilenet_v1_1.0_224', 'google/mobilenet_v1_0.75_192', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=None ): '''simple docstring''' _a : Optional[int] = {} if isinstance(UpperCamelCase__ , UpperCamelCase__ ): _a : Dict = model.mobilenet_va else: _a : Optional[Any] = model _a : int = """MobilenetV1/Conv2d_0/""" _a : Any = backbone.conv_stem.convolution.weight _a : str = backbone.conv_stem.normalization.bias _a : Any = backbone.conv_stem.normalization.weight _a : Any = backbone.conv_stem.normalization.running_mean _a : int = backbone.conv_stem.normalization.running_var for i in range(1_3 ): _a : int = i + 1 _a : Optional[int] = i * 2 _a : Optional[Any] = backbone.layer[pt_index] _a : List[str] = F"""MobilenetV1/Conv2d_{tf_index}_depthwise/""" _a : Any = pointer.convolution.weight _a : Dict = pointer.normalization.bias _a : Tuple = pointer.normalization.weight _a : Optional[Any] = pointer.normalization.running_mean _a : int = pointer.normalization.running_var _a : Optional[int] = backbone.layer[pt_index + 1] _a : Optional[Any] = F"""MobilenetV1/Conv2d_{tf_index}_pointwise/""" _a : Optional[int] = pointer.convolution.weight _a : str = pointer.normalization.bias _a : Optional[Any] = pointer.normalization.weight _a : Any = pointer.normalization.running_mean _a : Union[str, Any] = pointer.normalization.running_var if isinstance(UpperCamelCase__ , UpperCamelCase__ ): _a : Optional[int] = """MobilenetV1/Logits/Conv2d_1c_1x1/""" _a : Any = model.classifier.weight _a : Union[str, Any] = model.classifier.bias return tf_to_pt_map def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' try: import numpy as np import tensorflow as tf except ImportError: logger.error( """Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see """ """https://www.tensorflow.org/install/ for installation instructions.""" ) raise # Load weights from TF model _a : List[str] = tf.train.list_variables(UpperCamelCase__ ) _a : List[Any] = {} for name, shape in init_vars: logger.info(F"""Loading TF weight {name} with shape {shape}""" ) _a : str = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) _a : int = array # Build TF to PyTorch weights loading map _a : Optional[Any] = _build_tf_to_pytorch_map(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) for name, pointer in tf_to_pt_map.items(): logger.info(F"""Importing {name}""" ) if name not in tf_weights: logger.info(F"""{name} not in tf pre-trained weights, skipping""" ) continue _a : Optional[int] = tf_weights[name] if "depthwise_weights" in name: logger.info("""Transposing depthwise""" ) _a : Tuple = np.transpose(UpperCamelCase__ , (2, 3, 0, 1) ) elif "weights" in name: logger.info("""Transposing""" ) if len(pointer.shape ) == 2: # copying into linear layer _a : List[Any] = array.squeeze().transpose() else: _a : List[str] = np.transpose(UpperCamelCase__ , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(F"""Pointer shape {pointer.shape} and array shape {array.shape} mismatched""" ) logger.info(F"""Initialize PyTorch weight {name} {array.shape}""" ) _a : Optional[Any] = torch.from_numpy(UpperCamelCase__ ) tf_weights.pop(UpperCamelCase__ , UpperCamelCase__ ) tf_weights.pop(name + """/RMSProp""" , UpperCamelCase__ ) tf_weights.pop(name + """/RMSProp_1""" , UpperCamelCase__ ) tf_weights.pop(name + """/ExponentialMovingAverage""" , UpperCamelCase__ ) logger.info(F"""Weights not copied to PyTorch model: {', '.join(tf_weights.keys() )}""" ) return model def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' _a , _a : Optional[Any] = features.shape[-2:] _a , _a : Dict = conv_layer.stride _a , _a : Dict = conv_layer.kernel_size if in_height % stride_height == 0: _a : Optional[Any] = max(kernel_height - stride_height , 0 ) else: _a : Optional[int] = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: _a : Any = max(kernel_width - stride_width , 0 ) else: _a : int = max(kernel_width - (in_width % stride_width) , 0 ) _a : str = pad_along_width // 2 _a : Union[str, Any] = pad_along_width - pad_left _a : Optional[int] = pad_along_height // 2 _a : List[Any] = pad_along_height - pad_top _a : Optional[Any] = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(UpperCamelCase__ , UpperCamelCase__ , """constant""" , 0.0 ) class UpperCamelCase ( nn.Module ): def __init__( self : Optional[Any] , UpperCAmelCase__ : MobileNetVaConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] = 1 , UpperCAmelCase__ : Optional[int] = 1 , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Optional[bool] = True , UpperCAmelCase__ : Optional[bool or str] = True , ) -> None: super().__init__() _a : Any = config if in_channels % groups != 0: raise ValueError(f"""Input channels ({in_channels}) are not divisible by {groups} groups.""" ) if out_channels % groups != 0: raise ValueError(f"""Output channels ({out_channels}) are not divisible by {groups} groups.""" ) _a : Dict = 0 if config.tf_padding else int((kernel_size - 1) / 2 ) _a : List[Any] = nn.Convad( in_channels=UpperCAmelCase__ , out_channels=UpperCAmelCase__ , kernel_size=UpperCAmelCase__ , stride=UpperCAmelCase__ , padding=UpperCAmelCase__ , groups=UpperCAmelCase__ , bias=UpperCAmelCase__ , padding_mode="""zeros""" , ) if use_normalization: _a : int = nn.BatchNormad( num_features=UpperCAmelCase__ , eps=config.layer_norm_eps , momentum=0.9_9_9_7 , affine=UpperCAmelCase__ , track_running_stats=UpperCAmelCase__ , ) else: _a : int = None if use_activation: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): _a : Optional[int] = ACTaFN[use_activation] elif isinstance(config.hidden_act , UpperCAmelCase__ ): _a : int = ACTaFN[config.hidden_act] else: _a : str = config.hidden_act else: _a : Union[str, Any] = None def _lowercase ( self : Optional[int] , UpperCAmelCase__ : torch.Tensor ) -> torch.Tensor: if self.config.tf_padding: _a : List[str] = apply_tf_padding(UpperCAmelCase__ , self.convolution ) _a : List[str] = self.convolution(UpperCAmelCase__ ) if self.normalization is not None: _a : Optional[int] = self.normalization(UpperCAmelCase__ ) if self.activation is not None: _a : Dict = self.activation(UpperCAmelCase__ ) return features class UpperCamelCase ( snake_case_ ): UpperCamelCase : Dict = MobileNetVaConfig UpperCamelCase : Optional[Any] = load_tf_weights_in_mobilenet_va UpperCamelCase : Dict = '''mobilenet_v1''' UpperCamelCase : Any = '''pixel_values''' UpperCamelCase : str = False def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Union[nn.Linear, nn.Convad] ) -> None: if isinstance(UpperCAmelCase__ , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(UpperCAmelCase__ , nn.BatchNormad ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) _snake_case = r'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' _snake_case = r'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`MobileNetV1ImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( '''The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.''' , snake_case_ , ) class UpperCamelCase ( snake_case_ ): def __init__( self : Any , UpperCAmelCase__ : MobileNetVaConfig , UpperCAmelCase__ : bool = True ) -> Optional[int]: super().__init__(UpperCAmelCase__ ) _a : List[Any] = config _a : Any = 32 _a : Optional[Any] = max(int(depth * config.depth_multiplier ) , config.min_depth ) _a : Optional[Any] = MobileNetVaConvLayer( UpperCAmelCase__ , in_channels=config.num_channels , out_channels=UpperCAmelCase__ , kernel_size=3 , stride=2 , ) _a : int = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] _a : List[Any] = nn.ModuleList() for i in range(13 ): _a : List[Any] = out_channels if strides[i] == 2 or i == 0: depth *= 2 _a : Union[str, Any] = max(int(depth * config.depth_multiplier ) , config.min_depth ) self.layer.append( MobileNetVaConvLayer( UpperCAmelCase__ , in_channels=UpperCAmelCase__ , out_channels=UpperCAmelCase__ , kernel_size=3 , stride=strides[i] , groups=UpperCAmelCase__ , ) ) self.layer.append( MobileNetVaConvLayer( UpperCAmelCase__ , in_channels=UpperCAmelCase__ , out_channels=UpperCAmelCase__ , kernel_size=1 , ) ) _a : Dict = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def _lowercase ( self : List[Any] , UpperCAmelCase__ : Dict ) -> Any: raise NotImplementedError @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def _lowercase ( self : Any , UpperCAmelCase__ : Optional[torch.Tensor] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> Union[tuple, BaseModelOutputWithPoolingAndNoAttention]: _a : Union[str, Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _a : Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError("""You have to specify pixel_values""" ) _a : Tuple = self.conv_stem(UpperCAmelCase__ ) _a : Tuple = () if output_hidden_states else None for i, layer_module in enumerate(self.layer ): _a : Optional[int] = layer_module(UpperCAmelCase__ ) if output_hidden_states: _a : int = all_hidden_states + (hidden_states,) _a : int = hidden_states if self.pooler is not None: _a : Tuple = torch.flatten(self.pooler(UpperCAmelCase__ ) , start_dim=1 ) else: _a : str = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None ) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=UpperCAmelCase__ , pooler_output=UpperCAmelCase__ , hidden_states=UpperCAmelCase__ , ) @add_start_docstrings( ''' MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. ''' , snake_case_ , ) class UpperCamelCase ( snake_case_ ): def __init__( self : List[Any] , UpperCAmelCase__ : MobileNetVaConfig ) -> None: super().__init__(UpperCAmelCase__ ) _a : int = config.num_labels _a : List[Any] = MobileNetVaModel(UpperCAmelCase__ ) _a : Union[str, Any] = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head _a : Optional[int] = nn.Dropout(config.classifier_dropout_prob , inplace=UpperCAmelCase__ ) _a : Tuple = nn.Linear(UpperCAmelCase__ , config.num_labels ) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def _lowercase ( self : Union[str, Any] , UpperCAmelCase__ : Optional[torch.Tensor] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[torch.Tensor] = None , UpperCAmelCase__ : Optional[bool] = None , ) -> Union[tuple, ImageClassifierOutputWithNoAttention]: _a : Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict _a : Any = self.mobilenet_va(UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ ) _a : Optional[int] = outputs.pooler_output if return_dict else outputs[1] _a : List[Any] = self.classifier(self.dropout(UpperCAmelCase__ ) ) _a : List[Any] = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: _a : str = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): _a : str = """single_label_classification""" else: _a : Union[str, Any] = """multi_label_classification""" if self.config.problem_type == "regression": _a : Optional[Any] = MSELoss() if self.num_labels == 1: _a : Optional[int] = loss_fct(logits.squeeze() , labels.squeeze() ) else: _a : Optional[int] = loss_fct(UpperCAmelCase__ , UpperCAmelCase__ ) elif self.config.problem_type == "single_label_classification": _a : Optional[Any] = CrossEntropyLoss() _a : List[Any] = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": _a : Any = BCEWithLogitsLoss() _a : Union[str, Any] = loss_fct(UpperCAmelCase__ , UpperCAmelCase__ ) if not return_dict: _a : str = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=UpperCAmelCase__ , logits=UpperCAmelCase__ , hidden_states=outputs.hidden_states , )
294
"""simple docstring""" import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = {'vocab_file': 'vocab.json'} _snake_case = { 'vocab_file': { 'mgp-str': 'https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json', } } _snake_case = {'mgp-str': 27} class UpperCamelCase ( snake_case_ ): UpperCamelCase : List[str] = VOCAB_FILES_NAMES UpperCamelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : Optional[int] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[Any]="[GO]" , UpperCAmelCase__ : Tuple="[GO]" , UpperCAmelCase__ : Optional[int]="[s]" , UpperCAmelCase__ : int="[GO]" , **UpperCAmelCase__ : Dict ) -> int: super().__init__( unk_token=UpperCAmelCase__ , bos_token=UpperCAmelCase__ , eos_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , **UpperCAmelCase__ , ) with open(UpperCAmelCase__ , encoding="""utf-8""" ) as vocab_handle: _a : int = json.load(UpperCAmelCase__ ) _a : Optional[int] = {v: k for k, v in self.vocab.items()} @property def _lowercase ( self : Dict ) -> Union[str, Any]: return len(self.vocab ) def _lowercase ( self : Union[str, Any] ) -> str: return dict(self.vocab , **self.added_tokens_encoder ) def _lowercase ( self : Dict , UpperCAmelCase__ : str ) -> Union[str, Any]: _a : Tuple = [] for s in text: char_tokens.extend(UpperCAmelCase__ ) return char_tokens def _lowercase ( self : List[Any] , UpperCAmelCase__ : str ) -> Dict: return self.vocab.get(UpperCAmelCase__ , self.vocab.get(self.unk_token ) ) def _lowercase ( self : Optional[int] , UpperCAmelCase__ : Tuple ) -> List[Any]: return self.decoder.get(UpperCAmelCase__ ) def _lowercase ( self : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(UpperCAmelCase__ ): logger.error("""Vocabulary path ({}) should be a directory""".format(UpperCAmelCase__ ) ) return _a : Tuple = os.path.join( UpperCAmelCase__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) with open(UpperCAmelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) + """\n""" ) return (vocab_file,)
294
1
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType lowercase__ :Dict = logging.get_logger(__name__) lowercase__ :List[str] = { "microsoft/deberta-v2-xlarge": "https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json", "microsoft/deberta-v2-xxlarge": "https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json", "microsoft/deberta-v2-xlarge-mnli": ( "https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json" ), "microsoft/deberta-v2-xxlarge-mnli": ( "https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json" ), } class lowercase ( SCREAMING_SNAKE_CASE__ ): lowercase_ : Tuple ='''deberta-v2''' def __init__( self ,A__=1_2_8_1_0_0 ,A__=1_5_3_6 ,A__=2_4 ,A__=2_4 ,A__=6_1_4_4 ,A__="gelu" ,A__=0.1 ,A__=0.1 ,A__=5_1_2 ,A__=0 ,A__=0.02 ,A__=1E-7 ,A__=False ,A__=-1 ,A__=0 ,A__=True ,A__=None ,A__=0 ,A__="gelu" ,**A__ ,): super().__init__(**A__) lowercase = hidden_size lowercase = num_hidden_layers lowercase = num_attention_heads lowercase = intermediate_size lowercase = hidden_act lowercase = hidden_dropout_prob lowercase = attention_probs_dropout_prob lowercase = max_position_embeddings lowercase = type_vocab_size lowercase = initializer_range lowercase = relative_attention lowercase = max_relative_positions lowercase = pad_token_id lowercase = position_biased_input # Backwards compatibility if type(A__) == str: lowercase = [x.strip() for x in pos_att_type.lower().split('''|''')] lowercase = pos_att_type lowercase = vocab_size lowercase = layer_norm_eps lowercase = kwargs.get('''pooler_hidden_size''' ,A__) lowercase = pooler_dropout lowercase = pooler_hidden_act class lowercase ( SCREAMING_SNAKE_CASE__ ): @property def A__ ( self): if self.task == "multiple-choice": lowercase = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: lowercase = {0: '''batch''', 1: '''sequence'''} if self._config.type_vocab_size > 0: return OrderedDict( [('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis)]) else: return OrderedDict([('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis)]) @property def A__ ( self): return 1_2 def A__ ( self ,A__ ,A__ = -1 ,A__ = -1 ,A__ = -1 ,A__ = False ,A__ = None ,A__ = 3 ,A__ = 4_0 ,A__ = 4_0 ,A__ = None ,): lowercase = super().generate_dummy_inputs(preprocessor=A__ ,framework=A__) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
97
import os from typing import BinaryIO, Optional, Union import numpy as np import pyarrow.parquet as pq from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config from ..features.features import FeatureType, _visit from ..formatting import query_table from ..packaged_modules import _PACKAGED_DATASETS_MODULES from ..packaged_modules.parquet.parquet import Parquet from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' lowercase = np.inf def set_batch_size(lowerCAmelCase__ ) -> None: nonlocal batch_size if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): lowercase = min(lowerCAmelCase__ , config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS ) elif isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): lowercase = min(lowerCAmelCase__ , config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS ) elif isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and feature.dtype == "binary": lowercase = min(lowerCAmelCase__ , config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS ) _visit(lowerCAmelCase__ , lowerCAmelCase__ ) return None if batch_size is np.inf else batch_size class lowercase ( SCREAMING_SNAKE_CASE__ ): def __init__( self ,A__ ,A__ = None ,A__ = None ,A__ = None ,A__ = False ,A__ = False ,A__ = None ,**A__ ,): super().__init__( A__ ,split=A__ ,features=A__ ,cache_dir=A__ ,keep_in_memory=A__ ,streaming=A__ ,num_proc=A__ ,**A__ ,) lowercase = path_or_paths if isinstance(A__ ,A__) else {self.split: path_or_paths} lowercase = _PACKAGED_DATASETS_MODULES['''parquet'''][1] lowercase = Parquet( cache_dir=A__ ,data_files=A__ ,features=A__ ,hash=A__ ,**A__ ,) def A__ ( self): # Build iterable dataset if self.streaming: lowercase = self.builder.as_streaming_dataset(split=self.split) # Build regular (map-style) dataset else: lowercase = None lowercase = None lowercase = None lowercase = None self.builder.download_and_prepare( download_config=A__ ,download_mode=A__ ,verification_mode=A__ ,base_path=A__ ,num_proc=self.num_proc ,) lowercase = self.builder.as_dataset( split=self.split ,verification_mode=A__ ,in_memory=self.keep_in_memory) return dataset class lowercase : def __init__( self ,A__ ,A__ ,A__ = None ,**A__ ,): lowercase = dataset lowercase = path_or_buf lowercase = batch_size or get_writer_batch_size(dataset.features) lowercase = parquet_writer_kwargs def A__ ( self): lowercase = self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE if isinstance(self.path_or_buf ,(str, bytes, os.PathLike)): with open(self.path_or_buf ,'''wb+''') as buffer: lowercase = self._write(file_obj=A__ ,batch_size=A__ ,**self.parquet_writer_kwargs) else: lowercase = self._write(file_obj=self.path_or_buf ,batch_size=A__ ,**self.parquet_writer_kwargs) return written def A__ ( self ,A__ ,A__ ,**A__): lowercase = 0 lowercase = parquet_writer_kwargs.pop('''path_or_buf''' ,A__) lowercase = self.dataset.features.arrow_schema lowercase = pq.ParquetWriter(A__ ,schema=A__ ,**A__) for offset in logging.tqdm( range(0 ,len(self.dataset) ,A__) ,unit='''ba''' ,disable=not logging.is_progress_bar_enabled() ,desc='''Creating parquet from Arrow format''' ,): lowercase = query_table( table=self.dataset._data ,key=slice(A__ ,offset + batch_size) ,indices=self.dataset._indices if self.dataset._indices is not None else None ,) writer.write_table(A__) written += batch.nbytes writer.close() return written
97
1
import inspect import unittest from transformers import RegNetConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import RegNetForImageClassification, RegNetModel from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __lowerCAmelCase : def __init__( self: List[str] , _lowerCAmelCase: Tuple , _lowerCAmelCase: Optional[int]=3 , _lowerCAmelCase: Any=32 , _lowerCAmelCase: Tuple=3 , _lowerCAmelCase: Union[str, Any]=10 , _lowerCAmelCase: Optional[int]=[10, 20, 30, 40] , _lowerCAmelCase: int=[1, 1, 2, 1] , _lowerCAmelCase: Union[str, Any]=True , _lowerCAmelCase: str=True , _lowerCAmelCase: Dict="relu" , _lowerCAmelCase: Union[str, Any]=3 , _lowerCAmelCase: List[Any]=None , ): lowercase :int = parent lowercase :Tuple = batch_size lowercase :List[str] = image_size lowercase :Optional[int] = num_channels lowercase :Optional[int] = embeddings_size lowercase :Union[str, Any] = hidden_sizes lowercase :List[str] = depths lowercase :Union[str, Any] = is_training lowercase :List[Any] = use_labels lowercase :Optional[int] = hidden_act lowercase :str = num_labels lowercase :List[Any] = scope lowercase :List[Any] = len(_lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self: List[Any] ): lowercase :Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase :List[Any] = None if self.use_labels: lowercase :List[str] = ids_tensor([self.batch_size] , self.num_labels ) lowercase :int = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE ( self: Tuple ): return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE ( self: Dict , _lowerCAmelCase: str , _lowerCAmelCase: Optional[Any] , _lowerCAmelCase: Tuple ): lowercase :Optional[int] = RegNetModel(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() lowercase :Optional[int] = model(_lowerCAmelCase ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def SCREAMING_SNAKE_CASE ( self: Any , _lowerCAmelCase: Optional[int] , _lowerCAmelCase: Any , _lowerCAmelCase: Optional[int] ): lowercase :Any = self.num_labels lowercase :str = RegNetForImageClassification(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() lowercase :List[str] = model(_lowerCAmelCase , labels=_lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self: Tuple ): lowercase :Optional[int] = self.prepare_config_and_inputs() lowercase , lowercase , lowercase :Union[str, Any] = config_and_inputs lowercase :int = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase): _a = (RegNetModel, RegNetForImageClassification) if is_torch_available() else () _a = ( {'''feature-extraction''': RegNetModel, '''image-classification''': RegNetForImageClassification} if is_torch_available() else {} ) _a = False _a = False _a = False _a = False def SCREAMING_SNAKE_CASE ( self: List[Any] ): lowercase :Tuple = RegNetModelTester(self ) lowercase :Any = ConfigTester(self , config_class=_lowerCAmelCase , has_text_modality=_lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self: List[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 SCREAMING_SNAKE_CASE ( self: List[Any] ): return @unittest.skip(reason="RegNet does not use inputs_embeds" ) def SCREAMING_SNAKE_CASE ( self: List[Any] ): pass @unittest.skip(reason="RegNet does not support input and output embeddings" ) def SCREAMING_SNAKE_CASE ( self: Any ): pass def SCREAMING_SNAKE_CASE ( self: Dict ): lowercase , lowercase :Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase :List[str] = model_class(_lowerCAmelCase ) lowercase :Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase :Optional[int] = [*signature.parameters.keys()] lowercase :List[str] = ["pixel_values"] self.assertListEqual(arg_names[:1] , _lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self: Optional[Any] ): lowercase :Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self: List[Any] ): lowercase , lowercase :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase :Optional[Any] = model_class(config=_lowerCAmelCase ) for name, module in model.named_modules(): if isinstance(_lowerCAmelCase , (nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ) , msg=F"Parameter {name} of model {model_class} seems not properly initialized" , ) self.assertTrue( torch.all(module.bias == 0 ) , msg=F"Parameter {name} of model {model_class} seems not properly initialized" , ) def SCREAMING_SNAKE_CASE ( self: Any ): def check_hidden_states_output(_lowerCAmelCase: Union[str, Any] , _lowerCAmelCase: Union[str, Any] , _lowerCAmelCase: Dict ): lowercase :List[str] = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() with torch.no_grad(): lowercase :Optional[int] = model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) ) lowercase :Tuple = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowercase :Optional[Any] = self.model_tester.num_stages self.assertEqual(len(_lowerCAmelCase ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) lowercase , lowercase :Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() lowercase :str = ["basic", "bottleneck"] for model_class in self.all_model_classes: for layer_type in layers_type: lowercase :str = layer_type lowercase :Union[str, Any] = True check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase :Optional[Any] = True check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self: Dict ): lowercase :List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase ) @slow def SCREAMING_SNAKE_CASE ( self: Tuple ): for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase :int = RegNetModel.from_pretrained(_lowerCAmelCase ) self.assertIsNotNone(_lowerCAmelCase ) def UpperCAmelCase__ ( ): lowercase :Optional[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class __lowerCAmelCase ( unittest.TestCase): @cached_property def SCREAMING_SNAKE_CASE ( self: List[str] ): return ( AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE ( self: Dict ): lowercase :Union[str, Any] = RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(_lowerCAmelCase ) lowercase :int = self.default_image_processor lowercase :List[str] = prepare_img() lowercase :int = image_processor(images=_lowerCAmelCase , return_tensors="pt" ).to(_lowerCAmelCase ) # forward pass with torch.no_grad(): lowercase :Optional[int] = model(**_lowerCAmelCase ) # verify the logits lowercase :str = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape , _lowerCAmelCase ) lowercase :Dict = torch.tensor([-0.41_80, -1.50_51, -3.48_36] ).to(_lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCAmelCase , atol=1e-4 ) )
236
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType _UpperCAmelCase : Tuple = logging.get_logger(__name__) _UpperCAmelCase : Dict = { "openai/whisper-base": "https://huggingface.co/openai/whisper-base/resolve/main/config.json", } # fmt: off _UpperCAmelCase : Union[str, Any] = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 357, 366, 438, 532, 685, 705, 796, 930, 1058, 1220, 1267, 1279, 1303, 1343, 1377, 1391, 1635, 1782, 1875, 2162, 2361, 2488, 3467, 4008, 4211, 4600, 4808, 5299, 5855, 6329, 7203, 9609, 9959, 10563, 10786, 11420, 11709, 11907, 13163, 13697, 13700, 14808, 15306, 16410, 16791, 17992, 19203, 19510, 20724, 22305, 22935, 27007, 30109, 30420, 33409, 34949, 40283, 40493, 40549, 47282, 49146, 50257, 50359, 50360, 50361 ] _UpperCAmelCase : List[Any] = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 359, 503, 522, 542, 873, 893, 902, 918, 922, 931, 1350, 1853, 1982, 2460, 2627, 3246, 3253, 3268, 3536, 3846, 3961, 4183, 4667, 6585, 6647, 7273, 9061, 9383, 10428, 10929, 11938, 12033, 12331, 12562, 13793, 14157, 14635, 15265, 15618, 16553, 16604, 18362, 18956, 20075, 21675, 22520, 26130, 26161, 26435, 28279, 29464, 31650, 32302, 32470, 36865, 42863, 47425, 49870, 50254, 50258, 50360, 50361, 50362 ] class __lowerCAmelCase ( lowerCAmelCase): _a = '''whisper''' _a = ['''past_key_values'''] _a = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self: int , _lowerCAmelCase: str=5_18_65 , _lowerCAmelCase: str=80 , _lowerCAmelCase: int=6 , _lowerCAmelCase: Tuple=4 , _lowerCAmelCase: Union[str, Any]=6 , _lowerCAmelCase: List[Any]=4 , _lowerCAmelCase: Any=15_36 , _lowerCAmelCase: Union[str, Any]=15_36 , _lowerCAmelCase: str=0.0 , _lowerCAmelCase: str=0.0 , _lowerCAmelCase: List[Any]=5_02_57 , _lowerCAmelCase: Optional[Any]=True , _lowerCAmelCase: Tuple=True , _lowerCAmelCase: str="gelu" , _lowerCAmelCase: Dict=2_56 , _lowerCAmelCase: Union[str, Any]=0.0 , _lowerCAmelCase: Any=0.0 , _lowerCAmelCase: Dict=0.0 , _lowerCAmelCase: Union[str, Any]=0.02 , _lowerCAmelCase: Any=False , _lowerCAmelCase: List[str]=15_00 , _lowerCAmelCase: Tuple=4_48 , _lowerCAmelCase: Optional[Any]=5_02_56 , _lowerCAmelCase: Dict=5_02_56 , _lowerCAmelCase: List[Any]=5_02_56 , _lowerCAmelCase: Union[str, Any]=None , _lowerCAmelCase: str=[2_20, 5_02_56] , _lowerCAmelCase: Optional[int]=False , _lowerCAmelCase: Optional[int]=2_56 , _lowerCAmelCase: int=False , _lowerCAmelCase: Dict=0.05 , _lowerCAmelCase: Optional[Any]=10 , _lowerCAmelCase: List[str]=2 , _lowerCAmelCase: Tuple=0.0 , _lowerCAmelCase: str=10 , _lowerCAmelCase: Union[str, Any]=0 , _lowerCAmelCase: List[Any]=7 , **_lowerCAmelCase: Union[str, Any] , ): lowercase :Optional[Any] = vocab_size lowercase :Optional[int] = num_mel_bins lowercase :Union[str, Any] = d_model lowercase :List[Any] = encoder_layers lowercase :Optional[Any] = encoder_attention_heads lowercase :Union[str, Any] = decoder_layers lowercase :List[str] = decoder_attention_heads lowercase :Optional[int] = decoder_ffn_dim lowercase :List[Any] = encoder_ffn_dim lowercase :Optional[Any] = dropout lowercase :Tuple = attention_dropout lowercase :Tuple = activation_dropout lowercase :Optional[Any] = activation_function lowercase :Any = init_std lowercase :Optional[int] = encoder_layerdrop lowercase :Optional[int] = decoder_layerdrop lowercase :str = use_cache lowercase :Optional[Any] = encoder_layers lowercase :List[Any] = scale_embedding # scale factor will be sqrt(d_model) if True lowercase :Any = max_source_positions lowercase :Optional[Any] = max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. lowercase :int = classifier_proj_size lowercase :List[str] = use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 lowercase :Tuple = apply_spec_augment lowercase :int = mask_time_prob lowercase :Union[str, Any] = mask_time_length lowercase :Dict = mask_time_min_masks lowercase :Tuple = mask_feature_prob lowercase :List[Any] = mask_feature_length lowercase :List[Any] = mask_feature_min_masks lowercase :Any = median_filter_width super().__init__( pad_token_id=_lowerCAmelCase , bos_token_id=_lowerCAmelCase , eos_token_id=_lowerCAmelCase , is_encoder_decoder=_lowerCAmelCase , decoder_start_token_id=_lowerCAmelCase , suppress_tokens=_lowerCAmelCase , begin_suppress_tokens=_lowerCAmelCase , **_lowerCAmelCase , ) class __lowerCAmelCase ( lowerCAmelCase): @property def SCREAMING_SNAKE_CASE ( self: str ): lowercase :Tuple = OrderedDict( [ ("input_features", {0: "batch", 1: "feature_size", 2: "encoder_sequence"}), ] ) if self.use_past: lowercase :List[Any] = {0: "batch"} else: lowercase :str = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(_lowerCAmelCase , direction="inputs" ) return common_inputs def SCREAMING_SNAKE_CASE ( self: Dict , _lowerCAmelCase: Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , _lowerCAmelCase: int = -1 , _lowerCAmelCase: int = -1 , _lowerCAmelCase: bool = False , _lowerCAmelCase: Optional["TensorType"] = None , _lowerCAmelCase: int = 2_20_50 , _lowerCAmelCase: float = 5.0 , _lowerCAmelCase: int = 2_20 , ): lowercase :List[str] = OrderedDict() lowercase :str = OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=_lowerCAmelCase , framework=_lowerCAmelCase , sampling_rate=_lowerCAmelCase , time_duration=_lowerCAmelCase , frequency=_lowerCAmelCase , ) lowercase :Optional[Any] = encoder_inputs["input_features"].shape[2] lowercase :List[str] = encoder_sequence_length // 2 if self.use_past else seq_length lowercase :Dict = super().generate_dummy_inputs( preprocessor.tokenizer , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) lowercase :str = encoder_inputs.pop("input_features" ) lowercase :Optional[int] = decoder_inputs.pop("decoder_input_ids" ) if "past_key_values" in decoder_inputs: lowercase :List[str] = decoder_inputs.pop("past_key_values" ) return dummy_inputs @property def SCREAMING_SNAKE_CASE ( self: str ): return 1e-3
236
1
'''simple docstring''' from __future__ import annotations lowerCamelCase__ = "#" class lowerCAmelCase__ : def __init__( self : Tuple ) ->Optional[int]: '''simple docstring''' _UpperCAmelCase : Union[str, Any] = {} def lowerCAmelCase__ ( self : Tuple , lowerCamelCase__ : str ) ->str: '''simple docstring''' _UpperCAmelCase : Tuple = self._trie for char in text: if char not in trie: _UpperCAmelCase : Tuple = {} _UpperCAmelCase : str = trie[char] _UpperCAmelCase : List[Any] = True def lowerCAmelCase__ ( self : Optional[Any] , lowerCamelCase__ : str ) ->Dict: '''simple docstring''' _UpperCAmelCase : Optional[int] = self._trie for char in prefix: if char in trie: _UpperCAmelCase : str = trie[char] else: return [] return self._elements(a_ ) def lowerCAmelCase__ ( self : int , lowerCamelCase__ : dict ) ->List[str]: '''simple docstring''' _UpperCAmelCase : Dict = [] for c, v in d.items(): _UpperCAmelCase : List[Any] = [" "] if c == END else [(c + s) for s in self._elements(a_ )] result.extend(a_ ) return tuple(a_ ) lowerCamelCase__ = Trie() lowerCamelCase__ = ("depart", "detergent", "daring", "dog", "deer", "deal") for word in words: trie.insert_word(word) def __lowerCAmelCase (__lowerCAmelCase ): _UpperCAmelCase : Optional[Any] = trie.find_word(_UpperCamelCase ) return tuple(string + word for word in suffixes ) def __lowerCAmelCase (): print(autocomplete_using_trie("de" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
359
'''simple docstring''' import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def __lowerCAmelCase (__lowerCAmelCase ): if is_torch_version("<" , "2.0.0" ) or not hasattr(__lowerCAmelCase , "_dynamo" ): return False return isinstance(__lowerCAmelCase , torch._dynamo.eval_frame.OptimizedModule ) def __lowerCAmelCase (__lowerCAmelCase , __lowerCAmelCase = True ): _UpperCAmelCase : Any = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) _UpperCAmelCase : Dict = is_compiled_module(__lowerCAmelCase ) if is_compiled: _UpperCAmelCase : Optional[int] = model _UpperCAmelCase : Any = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(__lowerCAmelCase , __lowerCAmelCase ): _UpperCAmelCase : Any = model.module if not keep_fpaa_wrapper: _UpperCAmelCase : List[Any] = getattr(__lowerCAmelCase , "forward" ) _UpperCAmelCase : Dict = model.__dict__.pop("_original_forward" , __lowerCAmelCase ) if original_forward is not None: while hasattr(__lowerCAmelCase , "__wrapped__" ): _UpperCAmelCase : Optional[int] = forward.__wrapped__ if forward == original_forward: break _UpperCAmelCase : Dict = forward if getattr(__lowerCAmelCase , "_converted_to_transformer_engine" , __lowerCAmelCase ): convert_model(__lowerCAmelCase , to_transformer_engine=__lowerCAmelCase ) if is_compiled: _UpperCAmelCase : int = model _UpperCAmelCase : str = compiled_model return model def __lowerCAmelCase (): PartialState().wait_for_everyone() def __lowerCAmelCase (__lowerCAmelCase , __lowerCAmelCase ): if PartialState().distributed_type == DistributedType.TPU: xm.save(__lowerCAmelCase , __lowerCAmelCase ) elif PartialState().local_process_index == 0: torch.save(__lowerCAmelCase , __lowerCAmelCase ) @contextmanager def __lowerCAmelCase (**__lowerCAmelCase ): for key, value in kwargs.items(): _UpperCAmelCase : str = str(__lowerCAmelCase ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def __lowerCAmelCase (__lowerCAmelCase ): if not hasattr(__lowerCAmelCase , "__qualname__" ) and not hasattr(__lowerCAmelCase , "__name__" ): _UpperCAmelCase : List[str] = getattr(__lowerCAmelCase , "__class__" , __lowerCAmelCase ) if hasattr(__lowerCAmelCase , "__qualname__" ): return obj.__qualname__ if hasattr(__lowerCAmelCase , "__name__" ): return obj.__name__ return str(__lowerCAmelCase ) def __lowerCAmelCase (__lowerCAmelCase , __lowerCAmelCase ): for key, value in source.items(): if isinstance(__lowerCAmelCase , __lowerCAmelCase ): _UpperCAmelCase : Any = destination.setdefault(__lowerCAmelCase , {} ) merge_dicts(__lowerCAmelCase , __lowerCAmelCase ) else: _UpperCAmelCase : Optional[int] = value return destination def __lowerCAmelCase (__lowerCAmelCase = None ): if port is None: _UpperCAmelCase : Tuple = 29_500 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(("localhost", port) ) == 0
322
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { "microsoft/trocr-base-handwritten": ( "https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json" ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class UpperCAmelCase_ ( a): lowerCamelCase__ = 'trocr' lowerCamelCase__ = ['past_key_values'] lowerCamelCase__ = { 'num_attention_heads': 'decoder_attention_heads', 'hidden_size': 'd_model', 'num_hidden_layers': 'decoder_layers', } def __init__( self, __a=5_0265, __a=1024, __a=12, __a=16, __a=4096, __a="gelu", __a=512, __a=0.1, __a=0.0, __a=0.0, __a=2, __a=0.02, __a=0.0, __a=True, __a=False, __a=True, __a=True, __a=1, __a=0, __a=2, **__a, ): '''simple docstring''' _lowerCAmelCase : List[Any] = vocab_size _lowerCAmelCase : Dict = d_model _lowerCAmelCase : str = decoder_layers _lowerCAmelCase : Dict = decoder_attention_heads _lowerCAmelCase : int = decoder_ffn_dim _lowerCAmelCase : int = activation_function _lowerCAmelCase : str = max_position_embeddings _lowerCAmelCase : Optional[Any] = dropout _lowerCAmelCase : str = attention_dropout _lowerCAmelCase : str = activation_dropout _lowerCAmelCase : List[Any] = init_std _lowerCAmelCase : Optional[Any] = decoder_layerdrop _lowerCAmelCase : Optional[int] = use_cache _lowerCAmelCase : str = scale_embedding _lowerCAmelCase : Optional[int] = use_learned_position_embeddings _lowerCAmelCase : Optional[Any] = layernorm_embedding super().__init__( pad_token_id=__a, bos_token_id=__a, eos_token_id=__a, decoder_start_token_id=__a, **__a, )
36
import itertools import random import unittest import numpy as np from transformers import is_speech_available from transformers.testing_utils import require_torch, require_torchaudio from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import SpeechaTextFeatureExtractor _a = random.Random() def lowerCAmelCase__(__snake_case ,__snake_case=1.0 ,__snake_case=None ,__snake_case=None ) -> List[Any]: '''simple docstring''' if rng is None: lowerCamelCase__ = global_rng lowerCamelCase__ = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class __A ( unittest.TestCase ): '''simple docstring''' def __init__( self , __lowerCAmelCase , __lowerCAmelCase=7 , __lowerCAmelCase=4_0_0 , __lowerCAmelCase=2_0_0_0 , __lowerCAmelCase=2_4 , __lowerCAmelCase=2_4 , __lowerCAmelCase=0.0 , __lowerCAmelCase=1_6_0_0_0 , __lowerCAmelCase=True , __lowerCAmelCase=True , ): '''simple docstring''' lowerCamelCase__ = parent lowerCamelCase__ = batch_size lowerCamelCase__ = min_seq_length lowerCamelCase__ = max_seq_length lowerCamelCase__ = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) lowerCamelCase__ = feature_size lowerCamelCase__ = num_mel_bins lowerCamelCase__ = padding_value lowerCamelCase__ = sampling_rate lowerCamelCase__ = return_attention_mask lowerCamelCase__ = do_normalize def __lowerCamelCase ( self ): '''simple docstring''' return { "feature_size": self.feature_size, "num_mel_bins": self.num_mel_bins, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def __lowerCamelCase ( self , __lowerCAmelCase=False , __lowerCAmelCase=False ): '''simple docstring''' def _flatten(__lowerCAmelCase ): return list(itertools.chain(*__lowerCAmelCase ) ) if equal_length: lowerCamelCase__ = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size lowerCamelCase__ = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: lowerCamelCase__ = [np.asarray(__lowerCAmelCase ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __A ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase_ = SpeechaTextFeatureExtractor if is_speech_available() else None def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = SpeechaTextFeatureExtractionTester(self ) def __lowerCamelCase ( self , __lowerCAmelCase ): '''simple docstring''' self.assertTrue(np.all(np.mean(__lowerCAmelCase , axis=0 ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__lowerCAmelCase , axis=0 ) - 1 ) < 1E-3 ) ) def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 lowerCamelCase__ = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] lowerCamelCase__ = [np.asarray(__lowerCAmelCase ) for speech_input in speech_inputs] # Test feature size lowerCamelCase__ = feature_extractor(__lowerCAmelCase , padding=__lowerCAmelCase , return_tensors='''np''' ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size ) # Test not batched input lowerCamelCase__ = feature_extractor(speech_inputs[0] , return_tensors='''np''' ).input_features lowerCamelCase__ = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' ).input_features self.assertTrue(np.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) ) # Test batched lowerCamelCase__ = feature_extractor(__lowerCAmelCase , return_tensors='''np''' ).input_features lowerCamelCase__ = feature_extractor(__lowerCAmelCase , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__lowerCAmelCase , __lowerCAmelCase ): self.assertTrue(np.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. lowerCamelCase__ = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] lowerCamelCase__ = np.asarray(__lowerCAmelCase ) lowerCamelCase__ = feature_extractor(__lowerCAmelCase , return_tensors='''np''' ).input_features lowerCamelCase__ = feature_extractor(__lowerCAmelCase , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__lowerCAmelCase , __lowerCAmelCase ): self.assertTrue(np.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1E-3 ) ) def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCamelCase__ = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] lowerCamelCase__ = ['''longest''', '''max_length''', '''do_not_pad'''] lowerCamelCase__ = [None, 1_6, None] for max_length, padding in zip(__lowerCAmelCase , __lowerCAmelCase ): lowerCamelCase__ = feature_extractor( __lowerCAmelCase , padding=__lowerCAmelCase , max_length=__lowerCAmelCase , return_attention_mask=__lowerCAmelCase ) lowerCamelCase__ = inputs.input_features lowerCamelCase__ = inputs.attention_mask lowerCamelCase__ = [np.sum(__lowerCAmelCase ) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] ) def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCamelCase__ = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] lowerCamelCase__ = ['''longest''', '''max_length''', '''do_not_pad'''] lowerCamelCase__ = [None, 1_6, None] for max_length, padding in zip(__lowerCAmelCase , __lowerCAmelCase ): lowerCamelCase__ = feature_extractor( __lowerCAmelCase , max_length=__lowerCAmelCase , padding=__lowerCAmelCase , return_tensors='''np''' , return_attention_mask=__lowerCAmelCase ) lowerCamelCase__ = inputs.input_features lowerCamelCase__ = inputs.attention_mask lowerCamelCase__ = [np.sum(__lowerCAmelCase ) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] ) self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] ) self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1E-6 ) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] ) def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCamelCase__ = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] lowerCamelCase__ = feature_extractor( __lowerCAmelCase , padding='''max_length''' , max_length=4 , truncation=__lowerCAmelCase , return_tensors='''np''' , return_attention_mask=__lowerCAmelCase , ) lowerCamelCase__ = inputs.input_features lowerCamelCase__ = inputs.attention_mask lowerCamelCase__ = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1] ) self._check_zero_mean_unit_variance(input_features[2] ) def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCamelCase__ = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] lowerCamelCase__ = feature_extractor( __lowerCAmelCase , padding='''longest''' , max_length=4 , truncation=__lowerCAmelCase , return_tensors='''np''' , return_attention_mask=__lowerCAmelCase , ) lowerCamelCase__ = inputs.input_features lowerCamelCase__ = inputs.attention_mask lowerCamelCase__ = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape , (3, 4, 2_4) ) lowerCamelCase__ = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] lowerCamelCase__ = feature_extractor( __lowerCAmelCase , padding='''longest''' , max_length=1_6 , truncation=__lowerCAmelCase , return_tensors='''np''' , return_attention_mask=__lowerCAmelCase , ) lowerCamelCase__ = inputs.input_features lowerCamelCase__ = inputs.attention_mask lowerCamelCase__ = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape , (3, 6, 2_4) ) def __lowerCamelCase ( self ): '''simple docstring''' import torch lowerCamelCase__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCamelCase__ = np.random.rand(1_0_0 , 3_2 ).astype(np.floataa ) lowerCamelCase__ = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: lowerCamelCase__ = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) lowerCamelCase__ = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def __lowerCamelCase ( self , __lowerCAmelCase ): '''simple docstring''' from datasets import load_dataset lowerCamelCase__ = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech lowerCamelCase__ = ds.sort('''id''' ).select(range(__lowerCAmelCase ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = np.array([ -1.5745, -1.7713, -1.7020, -1.6069, -1.2250, -1.1105, -0.9072, -0.8241, -1.2310, -0.8098, -0.3320, -0.4101, -0.7985, -0.4996, -0.8213, -0.9128, -1.0420, -1.1286, -1.0440, -0.7999, -0.8405, -1.2275, -1.5443, -1.4625, ] ) # fmt: on lowerCamelCase__ = self._load_datasamples(1 ) lowerCamelCase__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCamelCase__ = feature_extractor(__lowerCAmelCase , return_tensors='''pt''' ).input_features self.assertEquals(input_features.shape , (1, 5_8_4, 2_4) ) self.assertTrue(np.allclose(input_features[0, 0, :3_0] , __lowerCAmelCase , atol=1E-4 ) )
209
0
from pathlib import Path import numpy as np from PIL import Image def _a ( SCREAMING_SNAKE_CASE_ : np.ndarray ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.29_89 * r + 0.58_70 * g + 0.11_40 * b def _a ( SCREAMING_SNAKE_CASE_ : np.ndarray ): """simple docstring""" return (gray > 1_27) & (gray <= 2_55) def _a ( SCREAMING_SNAKE_CASE_ : np.ndarray , SCREAMING_SNAKE_CASE_ : np.ndarray ): """simple docstring""" __lowerCAmelCase = np.zeros_like(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image __lowerCAmelCase = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): __lowerCAmelCase = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() __lowerCAmelCase = int(summation > 0 ) return output if __name__ == "__main__": # read original image UpperCamelCase__ = Path(__file__).resolve().parent / """image_data""" / """lena.jpg""" UpperCamelCase__ = np.array(Image.open(lena_path)) # kernel to be applied UpperCamelCase__ = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) UpperCamelCase__ = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image UpperCamelCase__ = Image.fromarray(output).convert("""RGB""") pil_img.save("""result_dilation.png""")
352
import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": UpperCamelCase__ = argparse.ArgumentParser() parser.add_argument( """--checkpoint_path""", default=None, type=str, required=True, help="""Path to the checkpoint to convert.""" ) parser.add_argument( """--original_config_file""", type=str, required=True, help="""The YAML config file corresponding to the original architecture.""", ) parser.add_argument( """--num_in_channels""", default=None, type=int, help="""The number of input channels. If `None` number of input channels will be automatically inferred.""", ) parser.add_argument( """--image_size""", default=512, type=int, help=( """The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2""" """ Base. Use 768 for Stable Diffusion v2.""" ), ) parser.add_argument( """--extract_ema""", action="""store_true""", help=( """Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights""" """ or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield""" """ higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.""" ), ) parser.add_argument( """--upcast_attention""", action="""store_true""", help=( """Whether the attention computation should always be upcasted. This is necessary when running stable""" """ diffusion 2.1.""" ), ) parser.add_argument( """--from_safetensors""", action="""store_true""", help="""If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.""", ) parser.add_argument( """--to_safetensors""", action="""store_true""", help="""Whether to store pipeline in safetensors format or not.""", ) parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the output model.""") parser.add_argument("""--device""", type=str, help="""Device to use (e.g. cpu, cuda:0, cuda:1, etc.)""") def _a ( SCREAMING_SNAKE_CASE_ : List[Any] ): if string == "True": return True elif string == "False": return False else: raise ValueError(F"""could not parse string as bool {string}""" ) parser.add_argument( """--use_linear_projection""", help="""Override for use linear projection""", required=False, type=parse_bool ) parser.add_argument("""--cross_attention_dim""", help="""Override for cross attention_dim""", required=False, type=int) UpperCamelCase__ = parser.parse_args() UpperCamelCase__ = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
102
0
"""simple docstring""" class __lowercase : '''simple docstring''' def __init__( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): __a : Any = name __a : str = value __a : Dict = weight def __repr__( self ): return f"""{self.__class__.__name__}({self.name}, {self.value}, {self.weight})""" def _lowerCamelCase ( self ): return self.value def _lowerCamelCase ( self ): return self.name def _lowerCamelCase ( self ): return self.weight def _lowerCamelCase ( self ): return self.value / self.weight def __A ( a_ :List[str] , a_ :Dict , a_ :str) -> List[str]: __a : Optional[int] = [] for i in range(len(a_)): menu.append(Things(name[i] , value[i] , weight[i])) return menu def __A ( a_ :List[Any] , a_ :Tuple , a_ :List[str]) -> Optional[int]: __a : Tuple = sorted(a_ , key=a_ , reverse=a_) __a : Optional[Any] = [] __a , __a : List[Any] = 0.0, 0.0 for i in range(len(a_)): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i]) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def __A ( ) -> int: pass if __name__ == "__main__": import doctest doctest.testmod()
160
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A = { '''configuration_ctrl''': ['''CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CTRLConfig'''], '''tokenization_ctrl''': ['''CTRLTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A = [ '''CTRL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CTRLForSequenceClassification''', '''CTRLLMHeadModel''', '''CTRLModel''', '''CTRLPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A = [ '''TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFCTRLForSequenceClassification''', '''TFCTRLLMHeadModel''', '''TFCTRLModel''', '''TFCTRLPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig from .tokenization_ctrl import CTRLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ctrl import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, CTRLPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_ctrl import ( TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, TFCTRLForSequenceClassification, TFCTRLLMHeadModel, TFCTRLModel, TFCTRLPreTrainedModel, ) else: import sys A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
160
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _lowerCamelCase = { 'vocab_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt' ), 'squeezebert/squeezebert-mnli': 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt', 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli': ( 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json' ), }, } _lowerCamelCase = { 'squeezebert/squeezebert-uncased': 5_12, 'squeezebert/squeezebert-mnli': 5_12, 'squeezebert/squeezebert-mnli-headless': 5_12, } _lowerCamelCase = { 'squeezebert/squeezebert-uncased': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli-headless': {'do_lower_case': True}, } class a ( _A ): '''simple docstring''' lowerCAmelCase : int = VOCAB_FILES_NAMES lowerCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase : List[Any] = PRETRAINED_INIT_CONFIGURATION lowerCAmelCase : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase : List[Any] = SqueezeBertTokenizer def __init__( self : List[Any] , __snake_case : Any=None , __snake_case : List[str]=None , __snake_case : List[Any]=True , __snake_case : Union[str, Any]="[UNK]" , __snake_case : List[str]="[SEP]" , __snake_case : Dict="[PAD]" , __snake_case : Any="[CLS]" , __snake_case : Dict="[MASK]" , __snake_case : str=True , __snake_case : List[str]=None , **__snake_case : Optional[int] , ): super().__init__( __snake_case , tokenizer_file=__snake_case , do_lower_case=__snake_case , unk_token=__snake_case , sep_token=__snake_case , pad_token=__snake_case , cls_token=__snake_case , mask_token=__snake_case , tokenize_chinese_chars=__snake_case , strip_accents=__snake_case , **__snake_case , ) UpperCAmelCase_ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __snake_case ) != do_lower_case or normalizer_state.get('''strip_accents''' , __snake_case ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __snake_case ) != tokenize_chinese_chars ): UpperCAmelCase_ = getattr(__snake_case , normalizer_state.pop('''type''' ) ) UpperCAmelCase_ = do_lower_case UpperCAmelCase_ = strip_accents UpperCAmelCase_ = tokenize_chinese_chars UpperCAmelCase_ = normalizer_class(**__snake_case ) UpperCAmelCase_ = do_lower_case def lowerCamelCase_ ( self : int , __snake_case : Dict , __snake_case : List[Any]=None ): UpperCAmelCase_ = [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 lowerCamelCase_ ( self : List[str] , __snake_case : List[int] , __snake_case : Optional[List[int]] = None ): UpperCAmelCase_ = [self.sep_token_id] UpperCAmelCase_ = [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 lowerCamelCase_ ( self : Optional[int] , __snake_case : str , __snake_case : Optional[str] = None ): UpperCAmelCase_ = self._tokenizer.model.save(__snake_case , name=__snake_case ) return tuple(__snake_case )
177
def SCREAMING_SNAKE_CASE ( __UpperCamelCase : Optional[Any] ) -> Union[str, Any]: UpperCAmelCase_ = len(__UpperCamelCase ) while cur > 1: # Find the maximum number in arr UpperCAmelCase_ = arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi UpperCAmelCase_ = arr[mi::-1] + arr[mi + 1 : len(__UpperCamelCase )] # Reverse whole list UpperCAmelCase_ = arr[cur - 1 :: -1] + arr[cur : len(__UpperCamelCase )] cur -= 1 return arr if __name__ == "__main__": _lowerCamelCase = input('Enter numbers separated by a comma:\n').strip() _lowerCamelCase = [int(item) for item in user_input.split(',')] print(pancake_sort(unsorted))
177
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __snake_case = { '''configuration_owlvit''': [ '''OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OwlViTConfig''', '''OwlViTOnnxConfig''', '''OwlViTTextConfig''', '''OwlViTVisionConfig''', ], '''processing_owlvit''': ['''OwlViTProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ['''OwlViTFeatureExtractor'''] __snake_case = ['''OwlViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ '''OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OwlViTModel''', '''OwlViTPreTrainedModel''', '''OwlViTTextModel''', '''OwlViTVisionModel''', '''OwlViTForObjectDetection''', ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys __snake_case = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
97
'''simple docstring''' from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def a ( __a ) -> bool: '''simple docstring''' UpperCamelCase__ :int = int(number**0.5 ) return number == sq * sq def a ( __a , __a , __a , __a , __a , __a ) -> tuple[int, int]: '''simple docstring''' UpperCamelCase__ :int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den UpperCamelCase__ :int = x_den * y_den * z_den UpperCamelCase__ :int = gcd(__a , __a ) top //= hcf bottom //= hcf return top, bottom def a ( __a = 35 ) -> int: '''simple docstring''' UpperCamelCase__ :set = set() UpperCamelCase__ :int UpperCamelCase__ :Fraction = Fraction(0 ) UpperCamelCase__ :tuple[int, int] for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 UpperCamelCase__ :int = x_num * y_den + x_den * y_num UpperCamelCase__ :Any = x_den * y_den UpperCamelCase__ :Tuple = gcd(__a , __a ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase__ :Tuple = add_three( __a , __a , __a , __a , __a , __a ) unique_s.add(__a ) # n=2 UpperCamelCase__ :List[str] = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) UpperCamelCase__ :Dict = x_den * x_den * y_den * y_den if is_sq(__a ) and is_sq(__a ): UpperCamelCase__ :Any = int(sqrt(__a ) ) UpperCamelCase__ :Optional[int] = int(sqrt(__a ) ) UpperCamelCase__ :int = gcd(__a , __a ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase__ :Tuple = add_three( __a , __a , __a , __a , __a , __a ) unique_s.add(__a ) # n=-1 UpperCamelCase__ :Tuple = x_num * y_num UpperCamelCase__ :Union[str, Any] = x_den * y_num + x_num * y_den UpperCamelCase__ :List[str] = gcd(__a , __a ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase__ :Union[str, Any] = add_three( __a , __a , __a , __a , __a , __a ) unique_s.add(__a ) # n=2 UpperCamelCase__ :Optional[Any] = x_num * x_num * y_num * y_num UpperCamelCase__ :Tuple = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(__a ) and is_sq(__a ): UpperCamelCase__ :str = int(sqrt(__a ) ) UpperCamelCase__ :Any = int(sqrt(__a ) ) UpperCamelCase__ :Dict = gcd(__a , __a ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCamelCase__ :int = add_three( __a , __a , __a , __a , __a , __a ) unique_s.add(__a ) for num, den in unique_s: total += Fraction(__a , __a ) return total.denominator + total.numerator if __name__ == "__main__": print(F"""{solution() = }""")
97
1
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
36
import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def lowerCAmelCase__ ( _a : str ): snake_case_ : str = FileLock(str(tmpdir / "foo.lock" ) ) snake_case_ : Optional[Any] = FileLock(str(tmpdir / "foo.lock" ) ) snake_case_ : Any = 0.01 with locka.acquire(): with pytest.raises(_a ): snake_case_ : Optional[int] = time.time() locka.acquire(_a ) assert time.time() - _start > timeout def lowerCAmelCase__ ( _a : Union[str, Any] ): snake_case_ : List[str] = "a" * 10_00 + ".lock" snake_case_ : Optional[int] = FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith(".lock" ) assert not locka._lock_file.endswith(_a ) assert len(os.path.basename(locka._lock_file ) ) <= 2_55 snake_case_ : int = FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(_a ): locka.acquire(0 )
36
1
'''simple docstring''' import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging UpperCamelCase__: Tuple = logging.get_logger(__name__) UpperCamelCase__: Optional[Any] = "▁" UpperCamelCase__: Tuple = { "vocab_file": "vocab.json", "spm_file": "sentencepiece.bpe.model", "tokenizer_config_file": "tokenizer_config.json", } UpperCamelCase__: Any = { "vocab_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json", }, "spm_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model", }, "tokenizer_config_file": { "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json", "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json", }, } UpperCamelCase__: Dict = { "facebook/m2m100_418M": 1024, } # fmt: off UpperCamelCase__: str = { "m2m100": ["af", "am", "ar", "ast", "az", "ba", "be", "bg", "bn", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "en", "es", "et", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "he", "hi", "hr", "ht", "hu", "hy", "id", "ig", "ilo", "is", "it", "ja", "jv", "ka", "kk", "km", "kn", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my", "ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi", "wo", "xh", "yi", "yo", "zh", "zu"], "wmt21": ["en", "ha", "is", "ja", "cs", "ru", "zh", "de"] } class SCREAMING_SNAKE_CASE( A__ ): """simple docstring""" lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = ["""input_ids""", """attention_mask"""] lowerCamelCase__ = [] lowerCamelCase__ = [] def __init__( self : Dict , __snake_case : Any , __snake_case : Tuple , __snake_case : Any=None , __snake_case : Any=None , __snake_case : Optional[int]="<s>" , __snake_case : List[Any]="</s>" , __snake_case : Optional[int]="</s>" , __snake_case : Dict="<pad>" , __snake_case : str="<unk>" , __snake_case : int="m2m100" , __snake_case : Optional[Dict[str, Any]] = None , __snake_case : int=8 , **__snake_case : Optional[Any] , ) -> None: UpperCAmelCase : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs UpperCAmelCase : Tuple = language_codes UpperCAmelCase : Union[str, Any] = FAIRSEQ_LANGUAGE_CODES[language_codes] UpperCAmelCase : Union[str, Any] = {lang_code: F"""__{lang_code}__""" for lang_code in fairseq_language_code} UpperCAmelCase : List[Any] = kwargs.get('''additional_special_tokens''' , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(__snake_case ) for lang_code in fairseq_language_code if self.get_lang_token(__snake_case ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__snake_case , tgt_lang=__snake_case , bos_token=__snake_case , eos_token=__snake_case , sep_token=__snake_case , unk_token=__snake_case , pad_token=__snake_case , language_codes=__snake_case , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=__snake_case , **__snake_case , ) UpperCAmelCase : Any = vocab_file UpperCAmelCase : List[Any] = load_json(__snake_case ) UpperCAmelCase : Any = {v: k for k, v in self.encoder.items()} UpperCAmelCase : Tuple = spm_file UpperCAmelCase : Tuple = load_spm(__snake_case , self.sp_model_kwargs ) UpperCAmelCase : Optional[Any] = len(self.encoder ) UpperCAmelCase : Union[str, Any] = { self.get_lang_token(__snake_case ): self.encoder_size + i for i, lang_code in enumerate(__snake_case ) } UpperCAmelCase : Optional[Any] = {lang_code: self.encoder_size + i for i, lang_code in enumerate(__snake_case )} UpperCAmelCase : List[Any] = {v: k for k, v in self.lang_token_to_id.items()} UpperCAmelCase : Union[str, Any] = src_lang if src_lang is not None else '''en''' UpperCAmelCase : Union[str, Any] = tgt_lang UpperCAmelCase : List[str] = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) UpperCAmelCase : Optional[int] = num_madeup_words @property def A ( self : int ) -> int: return len(self.encoder ) + len(self.lang_token_to_id ) @property def A ( self : List[str] ) -> str: return self._src_lang @src_lang.setter def A ( self : str , __snake_case : str ) -> None: UpperCAmelCase : Union[str, Any] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def A ( self : List[str] , __snake_case : str ) -> List[str]: return self.sp_model.encode(__snake_case , out_type=__snake_case ) def A ( self : str , __snake_case : Tuple ) -> Tuple: if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(__snake_case , self.encoder[self.unk_token] ) def A ( self : Any , __snake_case : int ) -> str: if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(__snake_case , self.unk_token ) def A ( self : Optional[Any] , __snake_case : Tuple ) -> Tuple: UpperCAmelCase : Optional[int] = [] UpperCAmelCase : Dict = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__snake_case ) + token UpperCAmelCase : Optional[Any] = [] else: current_sub_tokens.append(__snake_case ) out_string += self.sp_model.decode(__snake_case ) return out_string.strip() def A ( self : Dict , __snake_case : List[int] , __snake_case : Optional[List[int]] = None , __snake_case : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__snake_case , token_ids_a=__snake_case , already_has_special_tokens=__snake_case ) UpperCAmelCase : Optional[Any] = [1] * len(self.prefix_tokens ) UpperCAmelCase : Union[str, Any] = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__snake_case )) + suffix_ones return prefix_ones + ([0] * len(__snake_case )) + ([0] * len(__snake_case )) + suffix_ones def A ( self : Tuple , __snake_case : List[int] , __snake_case : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def A ( self : Optional[Any] ) -> Dict: UpperCAmelCase : Optional[int] = {self.convert_ids_to_tokens(__snake_case ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[Any] ) -> Dict: UpperCAmelCase : List[Any] = self.__dict__.copy() UpperCAmelCase : int = None return state def __setstate__( self : List[Any] , __snake_case : Dict ) -> None: UpperCAmelCase : Optional[int] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): UpperCAmelCase : Optional[int] = {} UpperCAmelCase : Optional[Any] = load_spm(self.spm_file , self.sp_model_kwargs ) def A ( self : int , __snake_case : str , __snake_case : Optional[str] = None ) -> Tuple[str]: UpperCAmelCase : Optional[Any] = Path(__snake_case ) if not save_dir.is_dir(): raise OSError(F"""{save_directory} should be a directory""" ) UpperCAmelCase : List[Any] = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''vocab_file'''] ) UpperCAmelCase : Optional[int] = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''spm_file'''] ) save_json(self.encoder , __snake_case ) if os.path.abspath(self.spm_file ) != os.path.abspath(__snake_case ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __snake_case ) elif not os.path.isfile(self.spm_file ): with open(__snake_case , '''wb''' ) as fi: UpperCAmelCase : Dict = self.sp_model.serialized_model_proto() fi.write(__snake_case ) return (str(__snake_case ), str(__snake_case )) def A ( self : int , __snake_case : List[str] , __snake_case : str = "en" , __snake_case : Optional[List[str]] = None , __snake_case : str = "ro" , **__snake_case : Optional[int] , ) -> BatchEncoding: UpperCAmelCase : List[Any] = src_lang UpperCAmelCase : List[Any] = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(__snake_case , __snake_case , **__snake_case ) def A ( self : int , __snake_case : Any , __snake_case : Optional[str] , __snake_case : Optional[str] , **__snake_case : Any ) -> Optional[int]: if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) UpperCAmelCase : Union[str, Any] = src_lang UpperCAmelCase : Dict = self(__snake_case , add_special_tokens=__snake_case , **__snake_case ) UpperCAmelCase : Any = self.get_lang_id(__snake_case ) UpperCAmelCase : Dict = tgt_lang_id return inputs def A ( self : str ) -> int: self.set_src_lang_special_tokens(self.src_lang ) def A ( self : Any ) -> int: self.set_tgt_lang_special_tokens(self.tgt_lang ) def A ( self : Any , __snake_case : str ) -> None: UpperCAmelCase : Dict = self.get_lang_token(__snake_case ) UpperCAmelCase : str = self.lang_token_to_id[lang_token] UpperCAmelCase : Any = [self.cur_lang_id] UpperCAmelCase : str = [self.eos_token_id] def A ( self : Dict , __snake_case : str ) -> None: UpperCAmelCase : Union[str, Any] = self.get_lang_token(__snake_case ) UpperCAmelCase : str = self.lang_token_to_id[lang_token] UpperCAmelCase : Optional[int] = [self.cur_lang_id] UpperCAmelCase : int = [self.eos_token_id] def A ( self : Optional[Any] , __snake_case : str ) -> str: return self.lang_code_to_token[lang] def A ( self : Any , __snake_case : str ) -> int: UpperCAmelCase : Any = self.get_lang_token(__snake_case ) return self.lang_token_to_id[lang_token] def snake_case_ ( _lowerCAmelCase : str , _lowerCAmelCase : Dict[str, Any] ) -> sentencepiece.SentencePieceProcessor: UpperCAmelCase : Any = sentencepiece.SentencePieceProcessor(**_lowerCAmelCase ) spm.Load(str(_lowerCAmelCase ) ) return spm def snake_case_ ( _lowerCAmelCase : str ) -> Union[Dict, List]: with open(_lowerCAmelCase , '''r''' ) as f: return json.load(_lowerCAmelCase ) def snake_case_ ( _lowerCAmelCase : List[str] , _lowerCAmelCase : str ) -> None: with open(_lowerCAmelCase , '''w''' ) as f: json.dump(_lowerCAmelCase , _lowerCAmelCase , indent=2 )
23
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 ( SCREAMING_SNAKE_CASE : Optional[int] ) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase: Union[str, Any] = int(SCREAMING_SNAKE_CASE ) __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase: List[str] = 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 ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : str=3_00 ) -> int: """simple docstring""" return f''' <div> {prefix} <progress value=\'{value}\' max=\'{total}\' style=\'width:{width}px; height:20px; vertical-align: middle;\'></progress> {label} </div> ''' def _a ( SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase: List[str] = '<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: __lowerCAmelCase: List[Any] = f'''{elt:.6f}''' if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else str(SCREAMING_SNAKE_CASE ) html_code += f''' <td>{elt}</td>\n''' html_code += " </tr>\n" html_code += " </tbody>\n</table><p>" return html_code class A_ : _lowercase : str = 5 _lowercase : str = 0.2 def __init__( self : Union[str, Any] , UpperCAmelCase : int , UpperCAmelCase : Optional[str] = None , UpperCAmelCase : bool = True , UpperCAmelCase : Optional["NotebookTrainingTracker"] = None , UpperCAmelCase : int = 3_0_0 , ) -> List[Any]: __lowerCAmelCase: List[str] = total __lowerCAmelCase: Optional[int] = '' if prefix is None else prefix __lowerCAmelCase: int = leave __lowerCAmelCase: List[str] = parent __lowerCAmelCase: Optional[Any] = width __lowerCAmelCase: List[str] = None __lowerCAmelCase: Dict = None __lowerCAmelCase: List[str] = None def UpperCAmelCase ( self : Union[str, Any] , UpperCAmelCase : int , UpperCAmelCase : bool = False , UpperCAmelCase : str = None ) -> Optional[int]: __lowerCAmelCase: int = value if comment is not None: __lowerCAmelCase: Any = comment if self.last_value is None: __lowerCAmelCase: List[Any] = time.time() __lowerCAmelCase: Any = value __lowerCAmelCase: List[str] = None __lowerCAmelCase: Dict = self.warmup __lowerCAmelCase: List[str] = 1 self.update_bar(UpperCAmelCase ) 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 __lowerCAmelCase: Union[str, Any] = time.time() __lowerCAmelCase: 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: __lowerCAmelCase: Dict = self.elapsed_time / (value - self.start_value) else: __lowerCAmelCase: int = None if value >= self.total: __lowerCAmelCase: Any = self.total __lowerCAmelCase: str = None if not self.leave: self.close() elif self.average_time_per_item is not None: __lowerCAmelCase: List[str] = self.average_time_per_item * (self.total - value) self.update_bar(UpperCAmelCase ) __lowerCAmelCase: Tuple = value __lowerCAmelCase: int = current_time if self.average_time_per_item is None: __lowerCAmelCase: Optional[int] = 1 else: __lowerCAmelCase: Optional[Any] = max(int(self.update_every / self.average_time_per_item ) , 1 ) def UpperCAmelCase ( self : int , UpperCAmelCase : Any , UpperCAmelCase : List[Any]=None ) -> Union[str, Any]: __lowerCAmelCase: int = ' ' * (len(str(self.total ) ) - len(str(UpperCAmelCase ) )) + str(UpperCAmelCase ) if self.elapsed_time is None: __lowerCAmelCase: Dict = F'''[{spaced_value}/{self.total} : < :''' elif self.predicted_remaining is None: __lowerCAmelCase: str = F'''[{spaced_value}/{self.total} {format_time(self.elapsed_time )}''' else: __lowerCAmelCase: 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 : Any ) -> Optional[Any]: __lowerCAmelCase: Any = 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: __lowerCAmelCase: Tuple = disp.display(disp.HTML(self.html_code ) , display_id=UpperCAmelCase ) else: self.output.update(disp.HTML(self.html_code ) ) def UpperCAmelCase ( self : str ) -> Optional[Any]: if self.parent is None and self.output is not None: self.output.update(disp.HTML('' ) ) class A_ ( snake_case__ ): def __init__( self : Tuple , UpperCAmelCase : Dict , UpperCAmelCase : List[Any]=None ) -> Any: super().__init__(UpperCAmelCase ) __lowerCAmelCase: Tuple = None if column_names is None else [column_names] __lowerCAmelCase: Union[str, Any] = None def UpperCAmelCase ( self : Union[str, Any] ) -> Any: __lowerCAmelCase: str = 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: __lowerCAmelCase: Optional[Any] = disp.display(disp.HTML(self.html_code ) , display_id=UpperCAmelCase ) else: self.output.update(disp.HTML(self.html_code ) ) def UpperCAmelCase ( self : Tuple , UpperCAmelCase : List[Any] ) -> Dict: if self.inner_table is None: __lowerCAmelCase: List[str] = [list(values.keys() ), list(values.values() )] else: __lowerCAmelCase: Any = 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(UpperCAmelCase ) __lowerCAmelCase: List[Any] = columns self.inner_table.append([values[c] for c in columns] ) def UpperCAmelCase ( self : Dict , UpperCAmelCase : int , UpperCAmelCase : List[Any]=None , UpperCAmelCase : List[str]=3_0_0 ) -> List[Any]: __lowerCAmelCase: Union[str, Any] = NotebookProgressBar(UpperCAmelCase , prefix=UpperCAmelCase , parent=self , width=UpperCAmelCase ) return self.child_bar def UpperCAmelCase ( self : Optional[int] ) -> Optional[int]: __lowerCAmelCase: Tuple = None self.display() class A_ ( snake_case__ ): def __init__( self : Any ) -> List[str]: __lowerCAmelCase: int = None __lowerCAmelCase: Optional[int] = None __lowerCAmelCase: str = False def UpperCAmelCase ( self : Tuple , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : Optional[int] , UpperCAmelCase : Any , **UpperCAmelCase : Tuple ) -> str: __lowerCAmelCase: Tuple = 'Epoch' if args.evaluation_strategy == IntervalStrategy.EPOCH else 'Step' __lowerCAmelCase: Optional[int] = 0 __lowerCAmelCase: Any = 0 __lowerCAmelCase: Tuple = [self.first_column] + ['Training Loss'] if args.evaluation_strategy != IntervalStrategy.NO: column_names.append('Validation Loss' ) __lowerCAmelCase: List[Any] = NotebookTrainingTracker(state.max_steps , UpperCAmelCase ) def UpperCAmelCase ( self : Optional[int] , UpperCAmelCase : Tuple , UpperCAmelCase : Any , UpperCAmelCase : Optional[Any] , **UpperCAmelCase : Union[str, Any] ) -> Any: __lowerCAmelCase: Union[str, Any] = 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 , ) __lowerCAmelCase: Any = False def UpperCAmelCase ( self : List[Any] , UpperCAmelCase : str , UpperCAmelCase : Optional[int] , UpperCAmelCase : Optional[Any] , UpperCAmelCase : int=None , **UpperCAmelCase : Dict ) -> List[Any]: if not has_length(UpperCAmelCase ): return if self.prediction_bar is None: if self.training_tracker is not None: __lowerCAmelCase: int = self.training_tracker.add_child(len(UpperCAmelCase ) ) else: __lowerCAmelCase: List[str] = NotebookProgressBar(len(UpperCAmelCase ) ) self.prediction_bar.update(1 ) else: self.prediction_bar.update(self.prediction_bar.value + 1 ) def UpperCAmelCase ( self : Union[str, Any] , UpperCAmelCase : Dict , UpperCAmelCase : Dict , UpperCAmelCase : Optional[Any] , **UpperCAmelCase : int ) -> Union[str, Any]: if self.prediction_bar is not None: self.prediction_bar.close() __lowerCAmelCase: Any = None def UpperCAmelCase ( self : str , UpperCAmelCase : Tuple , UpperCAmelCase : Optional[Any] , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : int=None , **UpperCAmelCase : Optional[Any] ) -> Optional[Any]: # Only for when there is no evaluation if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs: __lowerCAmelCase: Union[str, Any] = {'Training Loss': logs['loss']} # First column is necessarily Step sine we're not in epoch eval strategy __lowerCAmelCase: Dict = state.global_step self.training_tracker.write_line(UpperCAmelCase ) def UpperCAmelCase ( self : int , UpperCAmelCase : List[Any] , UpperCAmelCase : List[str] , UpperCAmelCase : Optional[int] , UpperCAmelCase : Tuple=None , **UpperCAmelCase : int ) -> List[str]: if self.training_tracker is not None: __lowerCAmelCase: Dict = {'Training Loss': 'No log', 'Validation Loss': 'No log'} for log in reversed(state.log_history ): if "loss" in log: __lowerCAmelCase: List[str] = log['loss'] break if self.first_column == "Epoch": __lowerCAmelCase: int = int(state.epoch ) else: __lowerCAmelCase: Tuple = state.global_step __lowerCAmelCase: Optional[int] = 'eval' for k in metrics: if k.endswith('_loss' ): __lowerCAmelCase: Union[str, Any] = re.sub(R'\_loss$' , '' , UpperCAmelCase ) __lowerCAmelCase: Optional[Any] = metrics.pop('total_flos' , UpperCAmelCase ) __lowerCAmelCase: str = metrics.pop('epoch' , UpperCAmelCase ) __lowerCAmelCase: int = metrics.pop(F'''{metric_key_prefix}_runtime''' , UpperCAmelCase ) __lowerCAmelCase: List[Any] = metrics.pop(F'''{metric_key_prefix}_samples_per_second''' , UpperCAmelCase ) __lowerCAmelCase: List[str] = metrics.pop(F'''{metric_key_prefix}_steps_per_second''' , UpperCAmelCase ) __lowerCAmelCase: Tuple = metrics.pop(F'''{metric_key_prefix}_jit_compilation_time''' , UpperCAmelCase ) for k, v in metrics.items(): if k == F'''{metric_key_prefix}_loss''': __lowerCAmelCase: Tuple = v else: __lowerCAmelCase: int = k.split('_' ) __lowerCAmelCase: List[Any] = ' '.join([part.capitalize() for part in splits[1:]] ) __lowerCAmelCase: List[Any] = v self.training_tracker.write_line(UpperCAmelCase ) self.training_tracker.remove_child() __lowerCAmelCase: List[str] = None # Evaluation takes a long time so we should force the next update. __lowerCAmelCase: str = True def UpperCAmelCase ( self : int , UpperCAmelCase : int , UpperCAmelCase : Tuple , UpperCAmelCase : Optional[int] , **UpperCAmelCase : Optional[int] ) -> Optional[int]: self.training_tracker.update( state.global_step , comment=F'''Epoch {int(state.epoch )}/{state.num_train_epochs}''' , force_update=UpperCAmelCase ) __lowerCAmelCase: Union[str, Any] = None
322
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) _lowercase : int = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : str = ["""NllbTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Dict = ["""NllbTokenizerFast"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys _lowercase : List[str] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
91
'''simple docstring''' import flax.linen as nn import jax.numpy as jnp from .attention_flax import FlaxTransformeraDModel from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD class UpperCamelCase__( nn.Module ): __magic_name__ : int __magic_name__ : int __magic_name__ : float = 0.0 __magic_name__ : int = 1 __magic_name__ : int = 1 __magic_name__ : bool = True __magic_name__ : bool = False __magic_name__ : bool = False __magic_name__ : bool = False __magic_name__ : jnp.dtype = jnp.floataa def a__( self : str )-> Dict: """simple docstring""" UpperCAmelCase = [] UpperCAmelCase = [] for i in range(self.num_layers ): UpperCAmelCase = self.in_channels if i == 0 else self.out_channels UpperCAmelCase = FlaxResnetBlockaD( in_channels=lowerCAmelCase , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(lowerCAmelCase ) UpperCAmelCase = FlaxTransformeraDModel( in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(lowerCAmelCase ) UpperCAmelCase = resnets UpperCAmelCase = attentions if self.add_downsample: UpperCAmelCase = FlaxDownsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self : List[Any] , lowerCAmelCase : Any , lowerCAmelCase : int , lowerCAmelCase : Dict , lowerCAmelCase : List[str]=True )-> Optional[int]: """simple docstring""" UpperCAmelCase = () for resnet, attn in zip(self.resnets , self.attentions ): UpperCAmelCase = resnet(lowerCAmelCase , lowerCAmelCase , deterministic=lowerCAmelCase ) UpperCAmelCase = attn(lowerCAmelCase , lowerCAmelCase , deterministic=lowerCAmelCase ) output_states += (hidden_states,) if self.add_downsample: UpperCAmelCase = self.downsamplers_a(lowerCAmelCase ) output_states += (hidden_states,) return hidden_states, output_states class UpperCamelCase__( nn.Module ): __magic_name__ : int __magic_name__ : int __magic_name__ : float = 0.0 __magic_name__ : int = 1 __magic_name__ : bool = True __magic_name__ : jnp.dtype = jnp.floataa def a__( self : List[str] )-> Any: """simple docstring""" UpperCAmelCase = [] for i in range(self.num_layers ): UpperCAmelCase = self.in_channels if i == 0 else self.out_channels UpperCAmelCase = FlaxResnetBlockaD( in_channels=lowerCAmelCase , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(lowerCAmelCase ) UpperCAmelCase = resnets if self.add_downsample: UpperCAmelCase = FlaxDownsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self : List[str] , lowerCAmelCase : Tuple , lowerCAmelCase : Dict , lowerCAmelCase : List[str]=True )-> Optional[int]: """simple docstring""" UpperCAmelCase = () for resnet in self.resnets: UpperCAmelCase = resnet(lowerCAmelCase , lowerCAmelCase , deterministic=lowerCAmelCase ) output_states += (hidden_states,) if self.add_downsample: UpperCAmelCase = self.downsamplers_a(lowerCAmelCase ) output_states += (hidden_states,) return hidden_states, output_states class UpperCamelCase__( nn.Module ): __magic_name__ : int __magic_name__ : int __magic_name__ : int __magic_name__ : float = 0.0 __magic_name__ : int = 1 __magic_name__ : int = 1 __magic_name__ : bool = True __magic_name__ : bool = False __magic_name__ : bool = False __magic_name__ : bool = False __magic_name__ : jnp.dtype = jnp.floataa def a__( self : List[str] )-> Tuple: """simple docstring""" UpperCAmelCase = [] UpperCAmelCase = [] for i in range(self.num_layers ): UpperCAmelCase = self.in_channels if (i == self.num_layers - 1) else self.out_channels UpperCAmelCase = self.prev_output_channel if i == 0 else self.out_channels UpperCAmelCase = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(lowerCAmelCase ) UpperCAmelCase = FlaxTransformeraDModel( in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(lowerCAmelCase ) UpperCAmelCase = resnets UpperCAmelCase = attentions if self.add_upsample: UpperCAmelCase = FlaxUpsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self : Union[str, Any] , lowerCAmelCase : List[str] , lowerCAmelCase : Optional[int] , lowerCAmelCase : List[str] , lowerCAmelCase : Any , lowerCAmelCase : Union[str, Any]=True )-> Optional[int]: """simple docstring""" for resnet, attn in zip(self.resnets , self.attentions ): # pop res hidden states UpperCAmelCase = res_hidden_states_tuple[-1] UpperCAmelCase = res_hidden_states_tuple[:-1] UpperCAmelCase = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1 ) UpperCAmelCase = resnet(lowerCAmelCase , lowerCAmelCase , deterministic=lowerCAmelCase ) UpperCAmelCase = attn(lowerCAmelCase , lowerCAmelCase , deterministic=lowerCAmelCase ) if self.add_upsample: UpperCAmelCase = self.upsamplers_a(lowerCAmelCase ) return hidden_states class UpperCamelCase__( nn.Module ): __magic_name__ : int __magic_name__ : int __magic_name__ : int __magic_name__ : float = 0.0 __magic_name__ : int = 1 __magic_name__ : bool = True __magic_name__ : jnp.dtype = jnp.floataa def a__( self : Optional[int] )-> str: """simple docstring""" UpperCAmelCase = [] for i in range(self.num_layers ): UpperCAmelCase = self.in_channels if (i == self.num_layers - 1) else self.out_channels UpperCAmelCase = self.prev_output_channel if i == 0 else self.out_channels UpperCAmelCase = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(lowerCAmelCase ) UpperCAmelCase = resnets if self.add_upsample: UpperCAmelCase = FlaxUpsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self : Union[str, Any] , lowerCAmelCase : Dict , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Tuple , lowerCAmelCase : Dict=True )-> Tuple: """simple docstring""" for resnet in self.resnets: # pop res hidden states UpperCAmelCase = res_hidden_states_tuple[-1] UpperCAmelCase = res_hidden_states_tuple[:-1] UpperCAmelCase = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1 ) UpperCAmelCase = resnet(lowerCAmelCase , lowerCAmelCase , deterministic=lowerCAmelCase ) if self.add_upsample: UpperCAmelCase = self.upsamplers_a(lowerCAmelCase ) return hidden_states class UpperCamelCase__( nn.Module ): __magic_name__ : int __magic_name__ : float = 0.0 __magic_name__ : int = 1 __magic_name__ : int = 1 __magic_name__ : bool = False __magic_name__ : bool = False __magic_name__ : jnp.dtype = jnp.floataa def a__( self : int )-> Optional[int]: """simple docstring""" UpperCAmelCase = [ FlaxResnetBlockaD( in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , ) ] UpperCAmelCase = [] for _ in range(self.num_layers ): UpperCAmelCase = FlaxTransformeraDModel( in_channels=self.in_channels , n_heads=self.num_attention_heads , d_head=self.in_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(lowerCAmelCase ) UpperCAmelCase = FlaxResnetBlockaD( in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(lowerCAmelCase ) UpperCAmelCase = resnets UpperCAmelCase = attentions def __call__( self : Dict , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Tuple , lowerCAmelCase : Dict , lowerCAmelCase : Any=True )-> Union[str, Any]: """simple docstring""" UpperCAmelCase = self.resnets[0](lowerCAmelCase , lowerCAmelCase ) for attn, resnet in zip(self.attentions , self.resnets[1:] ): UpperCAmelCase = attn(lowerCAmelCase , lowerCAmelCase , deterministic=lowerCAmelCase ) UpperCAmelCase = resnet(lowerCAmelCase , lowerCAmelCase , deterministic=lowerCAmelCase ) return hidden_states
91
1
'''simple docstring''' import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def UpperCamelCase( UpperCAmelCase_ ): return sum(param.float().sum() if 'encoder.embeddings' not in key else 0 for key, param in state_dict.items() ) def UpperCamelCase( UpperCAmelCase_ , UpperCAmelCase_ ): UpperCAmelCase : int = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue UpperCAmelCase : Union[str, Any] = key.replace('heads.cmd.mim_head.cls.predictions' , 'mmm_image_head' ) UpperCAmelCase : List[Any] = key.replace('heads.cmd.mlm_head.cls.predictions' , 'mmm_text_head' ) UpperCAmelCase : str = key.replace('heads.cmd.itm_head.cls' , 'itm_head' ) UpperCAmelCase : Optional[Any] = key.replace('heads.cmd.itm_head.pooler' , 'itm_head.pooler' ) UpperCAmelCase : str = key.replace('heads.cmd.clip_head.logit_scale' , 'flava.logit_scale' ) UpperCAmelCase : List[str] = key.replace('heads.fairseq_mlm.cls.predictions' , 'mlm_head' ) UpperCAmelCase : Optional[Any] = key.replace('heads.imagenet.mim_head.cls.predictions' , 'mim_head' ) UpperCAmelCase : str = key.replace('mm_text_projection' , 'flava.text_to_mm_projection' ) UpperCAmelCase : str = key.replace('mm_image_projection' , 'flava.image_to_mm_projection' ) UpperCAmelCase : Any = key.replace('image_encoder.module' , 'flava.image_model' ) UpperCAmelCase : Tuple = key.replace('text_encoder.module' , 'flava.text_model' ) UpperCAmelCase : Any = key.replace('mm_encoder.module.encoder.cls_token' , 'flava.multimodal_model.cls_token' ) UpperCAmelCase : List[str] = key.replace('mm_encoder.module' , 'flava.multimodal_model' ) UpperCAmelCase : Any = key.replace('text_projection' , 'flava.text_projection' ) UpperCAmelCase : Optional[Any] = key.replace('image_projection' , 'flava.image_projection' ) UpperCAmelCase : Any = value.float() for key, value in codebook_state_dict.items(): UpperCAmelCase : Union[str, Any] = value return upgrade @torch.no_grad() def UpperCamelCase( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_=None ): if config_path is not None: UpperCAmelCase : Dict = FlavaConfig.from_pretrained(_snake_case ) else: UpperCAmelCase : Optional[Any] = FlavaConfig() UpperCAmelCase : List[Any] = FlavaForPreTraining(_snake_case ).eval() UpperCAmelCase : Union[str, Any] = convert_dalle_checkpoint(_snake_case , _snake_case , save_checkpoint=_snake_case ) if os.path.exists(_snake_case ): UpperCAmelCase : List[str] = torch.load(_snake_case , map_location='cpu' ) else: UpperCAmelCase : List[str] = torch.hub.load_state_dict_from_url(_snake_case , map_location='cpu' ) UpperCAmelCase : Any = upgrade_state_dict(_snake_case , _snake_case ) hf_model.load_state_dict(_snake_case ) UpperCAmelCase : int = hf_model.state_dict() UpperCAmelCase : Union[str, Any] = count_parameters(_snake_case ) UpperCAmelCase : List[Any] = count_parameters(_snake_case ) + count_parameters(_snake_case ) assert torch.allclose(_snake_case , _snake_case , atol=1E-3 ) hf_model.save_pretrained(_snake_case ) if __name__ == "__main__": lowercase__ = 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("--codebook_path", default=None, type=str, help="Path to flava codebook checkpoint") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") lowercase__ = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
151
"""simple docstring""" import numpy as np def lowercase ( _snake_case : int , _snake_case : Optional[Any] , _snake_case : Optional[int] , _snake_case : int , _snake_case : Union[str, Any] ) ->Dict: """simple docstring""" __snake_case : Union[str, Any] = int(np.ceil((x_end - xa) / h ) ) __snake_case : Dict = np.zeros((n + 1,) ) __snake_case : List[Any] = ya __snake_case : int = xa for k in range(_snake_case ): __snake_case : Any = f(_snake_case , y[k] ) __snake_case : List[Any] = f(x + 0.5 * h , y[k] + 0.5 * h * ka ) __snake_case : int = f(x + 0.5 * h , y[k] + 0.5 * h * ka ) __snake_case : Optional[int] = f(x + h , y[k] + h * ka ) __snake_case : Optional[int] = y[k] + (1 / 6) * h * (ka + 2 * ka + 2 * ka + ka) x += h return y if __name__ == "__main__": import doctest doctest.testmod()
102
0
"""simple docstring""" import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets __UpperCamelCase : Dict = datasets.logging.get_logger(__name__) __UpperCamelCase : Dict = "\\n@inproceedings{bleurt,\n title={BLEURT: Learning Robust Metrics for Text Generation},\n author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh},\n booktitle={ACL},\n year={2020},\n url={https://arxiv.org/abs/2004.04696}\n}\n" __UpperCamelCase : Tuple = "\\nBLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018)\nand then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune\nit for your specific application (the latter is expected to perform better).\n\nSee the project's README at https://github.com/google-research/bleurt#readme for more information.\n" __UpperCamelCase : Any = "\nBLEURT score.\n\nArgs:\n `predictions` (list of str): prediction/candidate sentences\n `references` (list of str): reference sentences\n `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None.\n\nReturns:\n 'scores': List of scores.\nExamples:\n\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> bleurt = datasets.load_metric(\"bleurt\")\n >>> results = bleurt.compute(predictions=predictions, references=references)\n >>> print([round(v, 2) for v in results[\"scores\"]])\n [1.03, 1.04]\n" __UpperCamelCase : Any = { "bleurt-tiny-128": "https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip", "bleurt-tiny-512": "https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip", "bleurt-base-128": "https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip", "bleurt-base-512": "https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip", "bleurt-large-128": "https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip", "bleurt-large-512": "https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip", "BLEURT-20-D3": "https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip", "BLEURT-20-D6": "https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip", "BLEURT-20-D12": "https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip", "BLEURT-20": "https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip", } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class __magic_name__ ( datasets.Metric): def UpperCAmelCase__ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/google-research/bleurt''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/google-research/bleurt'''] , reference_urls=['''https://github.com/google-research/bleurt''', '''https://arxiv.org/abs/2004.04696'''] , ) def UpperCAmelCase__ ( self : Optional[int] , lowerCamelCase__ : int ) -> Optional[int]: '''simple docstring''' if self.config_name == "default": logger.warning( '''Using default BLEURT-Base checkpoint for sequence maximum length 128. ''' '''You can use a bigger model for better results with e.g.: datasets.load_metric(\'bleurt\', \'bleurt-large-512\').''' ) UpperCamelCase__ : List[str] = '''bleurt-base-128''' if self.config_name.lower() in CHECKPOINT_URLS: UpperCamelCase__ : Tuple = self.config_name.lower() elif self.config_name.upper() in CHECKPOINT_URLS: UpperCamelCase__ : Union[str, Any] = self.config_name.upper() else: raise KeyError( F"{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}" ) # download the model checkpoint specified by self.config_name and set up the scorer UpperCamelCase__ : Dict = dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] ) UpperCamelCase__ : Any = score.BleurtScorer(os.path.join(lowerCamelCase__ , lowerCamelCase__ ) ) def UpperCAmelCase__ ( self : Union[str, Any] , lowerCamelCase__ : Tuple , lowerCamelCase__ : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' UpperCamelCase__ : Optional[int] = self.scorer.score(references=lowerCamelCase__ , candidates=lowerCamelCase__ ) return {"scores": scores}
367
import argparse import collections import torch from flax import traverse_util from tax import checkpoints from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def _a ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Tuple="attention" ): """simple docstring""" UpperCamelCase__ : List[Any] = params[F"{prefix}/layers_{i}/{layer_name}/key/kernel"] UpperCamelCase__ : Optional[Any] = params[F"{prefix}/layers_{i}/{layer_name}/out/kernel"] UpperCamelCase__ : Union[str, Any] = params[F"{prefix}/layers_{i}/{layer_name}/query/kernel"] UpperCamelCase__ : int = params[F"{prefix}/layers_{i}/{layer_name}/value/kernel"] return k, o, q, v def _a ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : Any=False ): """simple docstring""" if split_mlp_wi: UpperCamelCase__ : Optional[int] = params[F"{prefix}/layers_{i}/mlp/wi_0/kernel"] UpperCamelCase__ : int = params[F"{prefix}/layers_{i}/mlp/wi_1/kernel"] UpperCamelCase__ : Any = (wi_a, wi_a) else: UpperCamelCase__ : Union[str, Any] = params[F"{prefix}/layers_{i}/mlp/wi/kernel"] UpperCamelCase__ : Any = params[F"{prefix}/layers_{i}/mlp/wo/kernel"] return wi, wo def _a ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" return params[F"{prefix}/layers_{i}/{layer_name}/scale"] def _a ( SCREAMING_SNAKE_CASE : dict , *, SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : bool ): """simple docstring""" UpperCamelCase__ : List[Any] = traverse_util.flatten_dict(variables['''target'''] ) UpperCamelCase__ : List[str] = {'''/'''.join(SCREAMING_SNAKE_CASE ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi UpperCamelCase__ : List[Any] = '''encoder/layers_0/mlp/wi_0/kernel''' in old print('''Split MLP:''' , SCREAMING_SNAKE_CASE ) UpperCamelCase__ : Any = collections.OrderedDict() # Shared embeddings. UpperCamelCase__ : List[Any] = old['''token_embedder/embedding'''] # Encoder. for i in range(SCREAMING_SNAKE_CASE ): # Block i, layer 0 (Self Attention). UpperCamelCase__ : int = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , '''encoder''' , '''pre_attention_layer_norm''' ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ : Optional[Any] = tax_attention_lookup(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , '''encoder''' , '''attention''' ) UpperCamelCase__ : Tuple = layer_norm UpperCamelCase__ : Optional[int] = k.T UpperCamelCase__ : Any = o.T UpperCamelCase__ : Dict = q.T UpperCamelCase__ : List[str] = v.T # Block i, layer 1 (MLP). UpperCamelCase__ : Tuple = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , '''encoder''' , '''pre_mlp_layer_norm''' ) UpperCamelCase__ , UpperCamelCase__ : Dict = tax_mlp_lookup(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , '''encoder''' , SCREAMING_SNAKE_CASE ) UpperCamelCase__ : Union[str, Any] = layer_norm if split_mlp_wi: UpperCamelCase__ : Optional[int] = wi[0].T UpperCamelCase__ : Tuple = wi[1].T else: UpperCamelCase__ : List[Any] = wi.T UpperCamelCase__ : Optional[int] = wo.T UpperCamelCase__ : List[str] = old[ '''encoder/relpos_bias/rel_embedding''' ].T UpperCamelCase__ : str = old['''encoder/encoder_norm/scale'''] if not is_encoder_only: # Decoder. for i in range(SCREAMING_SNAKE_CASE ): # Block i, layer 0 (Self Attention). UpperCamelCase__ : List[Any] = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , '''decoder''' , '''pre_self_attention_layer_norm''' ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ : Dict = tax_attention_lookup(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , '''decoder''' , '''self_attention''' ) UpperCamelCase__ : Dict = layer_norm UpperCamelCase__ : Optional[Any] = k.T UpperCamelCase__ : Tuple = o.T UpperCamelCase__ : Any = q.T UpperCamelCase__ : Optional[Any] = v.T # Block i, layer 1 (Cross Attention). UpperCamelCase__ : Optional[Any] = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , '''decoder''' , '''pre_cross_attention_layer_norm''' ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ : Any = tax_attention_lookup(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , '''decoder''' , '''encoder_decoder_attention''' ) UpperCamelCase__ : Optional[int] = layer_norm UpperCamelCase__ : List[Any] = k.T UpperCamelCase__ : Optional[Any] = o.T UpperCamelCase__ : Dict = q.T UpperCamelCase__ : Any = v.T # Block i, layer 2 (MLP). UpperCamelCase__ : Union[str, Any] = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , '''decoder''' , '''pre_mlp_layer_norm''' ) UpperCamelCase__ , UpperCamelCase__ : Union[str, Any] = tax_mlp_lookup(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , '''decoder''' , SCREAMING_SNAKE_CASE ) UpperCamelCase__ : Optional[Any] = layer_norm if split_mlp_wi: UpperCamelCase__ : str = wi[0].T UpperCamelCase__ : Any = wi[1].T else: UpperCamelCase__ : Tuple = wi.T UpperCamelCase__ : Tuple = wo.T UpperCamelCase__ : Optional[int] = old['''decoder/decoder_norm/scale'''] UpperCamelCase__ : Any = old[ '''decoder/relpos_bias/rel_embedding''' ].T # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: UpperCamelCase__ : Dict = old['''decoder/logits_dense/kernel'''].T return new def _a ( SCREAMING_SNAKE_CASE : Tuple , SCREAMING_SNAKE_CASE : bool ): """simple docstring""" UpperCamelCase__ : Optional[int] = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: UpperCamelCase__ : Optional[Any] = state_dict['''shared.weight'''] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: UpperCamelCase__ : List[Any] = state_dict['''shared.weight'''] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('''Using shared word embeddings as lm_head.''' ) UpperCamelCase__ : List[str] = state_dict['''shared.weight'''] return state_dict def _a ( SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" UpperCamelCase__ : Tuple = checkpoints.load_tax_checkpoint(SCREAMING_SNAKE_CASE ) UpperCamelCase__ : Dict = convert_tax_to_pytorch(SCREAMING_SNAKE_CASE , num_layers=config.num_layers , is_encoder_only=SCREAMING_SNAKE_CASE ) UpperCamelCase__ : List[str] = make_state_dict(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) model.load_state_dict(SCREAMING_SNAKE_CASE , strict=SCREAMING_SNAKE_CASE ) def _a ( SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : bool = False ): """simple docstring""" UpperCamelCase__ : Tuple = TaConfig.from_json_file(SCREAMING_SNAKE_CASE ) print(F"Building PyTorch model from configuration: {config}" ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: UpperCamelCase__ : Any = TaEncoderModel(SCREAMING_SNAKE_CASE ) else: UpperCamelCase__ : Union[str, Any] = TaForConditionalGeneration(SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint load_tax_weights_in_ta(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) model.save_pretrained(SCREAMING_SNAKE_CASE ) # Verify that we can load the checkpoint. model.from_pretrained(SCREAMING_SNAKE_CASE ) print('''Done''' ) if __name__ == "__main__": __UpperCamelCase : Union[str, Any] = argparse.ArgumentParser(description="Converts a native T5X checkpoint into a PyTorch checkpoint.") # Required parameters parser.add_argument( "--t5x_checkpoint_path", default=None, type=str, required=True, help="Path to the T5X checkpoint." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.", ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--is_encoder_only", action="store_true", help="Check if the model is encoder-decoder model", default=False ) __UpperCamelCase : int = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only )
51
0
"""simple docstring""" def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , __UpperCAmelCase ) -> bool: lowercase__: int = len(__UpperCAmelCase ) + 1 lowercase__: List[Any] = len(__UpperCAmelCase ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. lowercase__: Dict = [[0 for i in range(__UpperCAmelCase )] for j in range(__UpperCAmelCase )] # since string of zero length match pattern of zero length lowercase__: Union[str, Any] = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1 , __UpperCAmelCase ): lowercase__: Union[str, Any] = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1 , __UpperCAmelCase ): lowercase__: Optional[Any] = dp[0][j - 2] if pattern[j - 1] == '''*''' else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1 , __UpperCAmelCase ): for j in range(1 , __UpperCAmelCase ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": lowercase__: int = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: lowercase__: List[str] = 1 elif pattern[j - 2] in (input_string[i - 1], "."): lowercase__: str = dp[i - 1][j] else: lowercase__: str = 0 else: lowercase__: Optional[Any] = 0 return bool(dp[-1][-1] ) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") __A = "aab" __A = "c*a*b" # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(f'''{input_string} matches the given pattern {pattern}''') else: print(f'''{input_string} does not match with the given pattern {pattern}''')
177
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING __A = logging.get_logger(__name__) __A = { "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json", } class UpperCAmelCase (_UpperCAmelCase ): """simple docstring""" _UpperCAmelCase :Dict = "deta" _UpperCAmelCase :Any = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , _UpperCAmelCase=None , _UpperCAmelCase=900 , _UpperCAmelCase=2048 , _UpperCAmelCase=6 , _UpperCAmelCase=2048 , _UpperCAmelCase=8 , _UpperCAmelCase=6 , _UpperCAmelCase=1024 , _UpperCAmelCase=8 , _UpperCAmelCase=0.0 , _UpperCAmelCase=True , _UpperCAmelCase="relu" , _UpperCAmelCase=256 , _UpperCAmelCase=0.1 , _UpperCAmelCase=0.0 , _UpperCAmelCase=0.0 , _UpperCAmelCase=0.02 , _UpperCAmelCase=1.0 , _UpperCAmelCase=True , _UpperCAmelCase=False , _UpperCAmelCase="sine" , _UpperCAmelCase=5 , _UpperCAmelCase=4 , _UpperCAmelCase=4 , _UpperCAmelCase=True , _UpperCAmelCase=300 , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=1 , _UpperCAmelCase=5 , _UpperCAmelCase=2 , _UpperCAmelCase=1 , _UpperCAmelCase=1 , _UpperCAmelCase=5 , _UpperCAmelCase=2 , _UpperCAmelCase=0.1 , _UpperCAmelCase=0.25 , **_UpperCAmelCase , ): if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) lowercase__: str = CONFIG_MAPPING['''resnet'''](out_features=['''stage2''', '''stage3''', '''stage4'''] ) else: if isinstance(_UpperCAmelCase , _UpperCAmelCase ): lowercase__: Tuple = backbone_config.pop('''model_type''' ) lowercase__: str = CONFIG_MAPPING[backbone_model_type] lowercase__: Optional[int] = config_class.from_dict(_UpperCAmelCase ) lowercase__: int = backbone_config lowercase__: Any = num_queries lowercase__: List[str] = max_position_embeddings lowercase__: Optional[Any] = d_model lowercase__: List[Any] = encoder_ffn_dim lowercase__: Tuple = encoder_layers lowercase__: Dict = encoder_attention_heads lowercase__: Any = decoder_ffn_dim lowercase__: Union[str, Any] = decoder_layers lowercase__: List[Any] = decoder_attention_heads lowercase__: int = dropout lowercase__: List[str] = attention_dropout lowercase__: Tuple = activation_dropout lowercase__: Tuple = activation_function lowercase__: int = init_std lowercase__: Optional[Any] = init_xavier_std lowercase__: Optional[Any] = encoder_layerdrop lowercase__: Optional[int] = auxiliary_loss lowercase__: Union[str, Any] = position_embedding_type # deformable attributes lowercase__: List[str] = num_feature_levels lowercase__: Optional[Any] = encoder_n_points lowercase__: int = decoder_n_points lowercase__: str = two_stage lowercase__: Optional[int] = two_stage_num_proposals lowercase__: Tuple = with_box_refine lowercase__: str = assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError('''If two_stage is True, with_box_refine must be True.''' ) # Hungarian matcher lowercase__: Union[str, Any] = class_cost lowercase__: Optional[int] = bbox_cost lowercase__: int = giou_cost # Loss coefficients lowercase__: Optional[int] = mask_loss_coefficient lowercase__: List[str] = dice_loss_coefficient lowercase__: str = bbox_loss_coefficient lowercase__: Union[str, Any] = giou_loss_coefficient lowercase__: Optional[int] = eos_coefficient lowercase__: str = focal_alpha super().__init__(is_encoder_decoder=_UpperCAmelCase , **_UpperCAmelCase ) @property def _snake_case ( self ): return self.encoder_attention_heads @property def _snake_case ( self ): return self.d_model def _snake_case ( self ): lowercase__: Union[str, Any] = copy.deepcopy(self.__dict__ ) lowercase__: Dict = self.backbone_config.to_dict() lowercase__: Union[str, Any] = self.__class__.model_type return output
177
1
"""simple docstring""" from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def lowercase__(A , A , A , A , A ) ->np.ndarray: """simple docstring""" lowercase__ : int= cva.getAffineTransform(A , A ) return cva.warpAffine(A , A , (rows, cols) ) if __name__ == "__main__": # read original image a : List[Any] = cva.imread( str(Path(__file__).resolve().parent.parent / """image_data""" / """lena.jpg""") ) # turn image in gray scale value a : Any = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape a , a : Tuple = gray_img.shape # set different points to rotate image a : str = np.array([[50, 50], [200, 50], [50, 200]], np.floataa) a : Union[str, Any] = np.array([[10, 100], [200, 50], [100, 250]], np.floataa) a : str = np.array([[50, 50], [150, 50], [120, 200]], np.floataa) a : int = np.array([[10, 100], [80, 50], [180, 250]], np.floataa) # add all rotated images in a list a : Optional[int] = [ gray_img, get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), ] # plot different image rotations a : Dict = plt.figure(1) a : Optional[int] = ["""Original""", """Rotation 1""", """Rotation 2""", """Rotation 3"""] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, """gray""") plt.title(titles[i]) plt.axis("""off""") plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
150
"""simple docstring""" import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py a : Any = """src/diffusers""" # Matches is_xxx_available() a : Optional[Any] = re.compile(r"""is\_([a-z_]*)_available\(\)""") # Matches from xxx import bla a : Dict = re.compile(r"""\s+from\s+\S*\s+import\s+([^\(\s].*)\n""") a : Dict = """ {0} = None """ a : List[Any] = """ class {0}(metaclass=DummyObject): _backends = {1} def __init__(self, *args, **kwargs): requires_backends(self, {1}) @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, {1}) @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, {1}) """ a : Any = """ def {0}(*args, **kwargs): requires_backends({0}, {1}) """ def lowercase__(A ) ->List[str]: """simple docstring""" lowercase__ : Optional[int]= _re_backend.findall(A ) if len(A ) == 0: return None return "_and_".join(A ) def lowercase__() ->int: """simple docstring""" with open(os.path.join(A , "__init__.py" ) , "r" , encoding="utf-8" , newline="\n" ) as f: lowercase__ : Union[str, Any]= f.readlines() # Get to the point we do the actual imports for type checking lowercase__ : List[Any]= 0 lowercase__ : List[Any]= {} # Go through the end of the file while line_index < len(A ): # If the line contains is_backend_available, we grab all objects associated with the `else` block lowercase__ : Optional[Any]= find_backend(lines[line_index] ) if backend is not None: while not lines[line_index].startswith("else:" ): line_index += 1 line_index += 1 lowercase__ : str= [] # Until we unindent, add backend objects to the list while line_index < len(A ) and len(lines[line_index] ) > 1: lowercase__ : List[str]= lines[line_index] lowercase__ : Any= _re_single_line_import.search(A ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(", " ) ) elif line.startswith(" " * 8 ): objects.append(line[8:-2] ) line_index += 1 if len(A ) > 0: lowercase__ : str= objects else: line_index += 1 return backend_specific_objects def lowercase__(A , A ) ->List[Any]: """simple docstring""" if name.isupper(): return DUMMY_CONSTANT.format(A ) elif name.islower(): return DUMMY_FUNCTION.format(A , A ) else: return DUMMY_CLASS.format(A , A ) def lowercase__(A=None ) ->Optional[Any]: """simple docstring""" if backend_specific_objects is None: lowercase__ : int= read_init() # For special correspondence backend to module name as used in the function requires_modulename lowercase__ : Dict= {} for backend, objects in backend_specific_objects.items(): lowercase__ : str= "[" + ", ".join(f'''"{b}"''' for b in backend.split("_and_" ) ) + "]" lowercase__ : List[str]= "# This file is autogenerated by the command `make fix-copies`, do not edit.\n" dummy_file += "from ..utils import DummyObject, requires_backends\n\n" dummy_file += "\n".join([create_dummy_object(A , A ) for o in objects] ) lowercase__ : Optional[Any]= dummy_file return dummy_files def lowercase__(A=False ) ->List[Any]: """simple docstring""" lowercase__ : Tuple= create_dummy_files() # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py lowercase__ : int= {"torch": "pt"} # Locate actual dummy modules and read their content. lowercase__ : Dict= os.path.join(A , "utils" ) lowercase__ : str= { backend: os.path.join(A , f'''dummy_{short_names.get(A , A )}_objects.py''' ) for backend in dummy_files.keys() } lowercase__ : Union[str, Any]= {} for backend, file_path in dummy_file_paths.items(): if os.path.isfile(A ): with open(A , "r" , encoding="utf-8" , newline="\n" ) as f: lowercase__ : List[Any]= f.read() else: lowercase__ : Tuple= "" for backend in dummy_files.keys(): if dummy_files[backend] != actual_dummies[backend]: if overwrite: print( f'''Updating diffusers.utils.dummy_{short_names.get(A , A )}_objects.py as the main ''' "__init__ has new objects." ) with open(dummy_file_paths[backend] , "w" , encoding="utf-8" , newline="\n" ) as f: f.write(dummy_files[backend] ) else: raise ValueError( "The main __init__ has objects that are not present in " f'''diffusers.utils.dummy_{short_names.get(A , A )}_objects.py. Run `make fix-copies` ''' "to fix this." ) if __name__ == "__main__": a : Optional[Any] = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") a : Tuple = parser.parse_args() check_dummies(args.fix_and_overwrite)
150
1
from typing import List, Optional, Union import numpy as np from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ....feature_extraction_sequence_utils import SequenceFeatureExtractor from ....feature_extraction_utils import BatchFeature from ....file_utils import PaddingStrategy, TensorType from ....utils import logging _snake_case = logging.get_logger(__name__) class UpperCAmelCase_ ( a): lowerCamelCase__ = ['input_features', 'attention_mask'] def __init__( self, __a=80, __a=1_6000, __a=0.0, __a=10, __a=25, __a="hamming_window", __a=32_768.0, __a=0.97, __a=1.0, __a=True, __a=True, __a=False, **__a, ): '''simple docstring''' super().__init__(feature_size=__a, sampling_rate=__a, padding_value=__a, **__a) _lowerCAmelCase : int = feature_size _lowerCAmelCase : Optional[Any] = sampling_rate _lowerCAmelCase : Tuple = padding_value _lowerCAmelCase : int = hop_length _lowerCAmelCase : str = win_length _lowerCAmelCase : str = frame_signal_scale _lowerCAmelCase : Union[str, Any] = preemphasis_coeff _lowerCAmelCase : Optional[Any] = mel_floor _lowerCAmelCase : str = normalize_means _lowerCAmelCase : Union[str, Any] = normalize_vars _lowerCAmelCase : List[str] = win_function _lowerCAmelCase : str = return_attention_mask _lowerCAmelCase : str = win_length * sampling_rate // 1000 _lowerCAmelCase : Union[str, Any] = hop_length * sampling_rate // 1000 _lowerCAmelCase : Tuple = optimal_fft_length(self.sample_size) _lowerCAmelCase : Tuple = (self.n_fft // 2) + 1 def snake_case__ ( self, __a): '''simple docstring''' if self.win_function == "hamming_window": _lowerCAmelCase : str = window_function(window_length=self.sample_size, name=self.win_function, periodic=__a) else: _lowerCAmelCase : Union[str, Any] = window_function(window_length=self.sample_size, name=self.win_function) _lowerCAmelCase : List[Any] = mel_filter_bank( num_frequency_bins=self.n_freqs, num_mel_filters=self.feature_size, min_frequency=0.0, max_frequency=self.sampling_rate / 2.0, sampling_rate=self.sampling_rate, ) _lowerCAmelCase : Optional[Any] = spectrogram( one_waveform * self.frame_signal_scale, window=__a, frame_length=self.sample_size, hop_length=self.sample_stride, fft_length=self.n_fft, center=__a, preemphasis=self.preemphasis_coeff, mel_filters=__a, mel_floor=self.mel_floor, log_mel="log", ) return msfc_features.T def snake_case__ ( self, __a, __a, __a): '''simple docstring''' if self.normalize_means: _lowerCAmelCase : Dict = x[:input_length].mean(axis=0) _lowerCAmelCase : Optional[Any] = np.subtract(__a, __a) if self.normalize_vars: _lowerCAmelCase : List[str] = x[:input_length].std(axis=0) _lowerCAmelCase : Optional[int] = np.divide(__a, __a) if input_length < x.shape[0]: _lowerCAmelCase : Union[str, Any] = padding_value # make sure array is in float32 _lowerCAmelCase : Optional[int] = x.astype(np.floataa) return x def snake_case__ ( self, __a, __a = None): '''simple docstring''' _lowerCAmelCase : int = attention_mask.sum(-1) if attention_mask is not None else [x.shape[0] for x in input_features] return [self._normalize_one(__a, __a, self.padding_value) for x, n in zip(__a, __a)] def __call__( self, __a, __a = False, __a = None, __a = False, __a = None, __a = None, __a = None, __a = None, **__a, ): '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of" f" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with" f" {self.sampling_rate} and not {sampling_rate}.") else: logger.warning( "It is strongly recommended to pass the ``sampling_rate`` argument to this function. " "Failing to do so can result in silent errors that might be hard to debug.") _lowerCAmelCase : List[Any] = isinstance(__a, np.ndarray) and len(raw_speech.shape) > 1 if is_batched_numpy and len(raw_speech.shape) > 2: raise ValueError(f"Only mono-channel audio is supported for input to {self}") _lowerCAmelCase : int = is_batched_numpy or ( isinstance(__a, (list, tuple)) and (isinstance(raw_speech[0], (np.ndarray, tuple, list))) ) if is_batched: _lowerCAmelCase : Any = [np.asarray(__a, dtype=np.floataa) for speech in raw_speech] elif not is_batched and not isinstance(__a, np.ndarray): _lowerCAmelCase : Tuple = np.asarray(__a, dtype=np.floataa) elif isinstance(__a, np.ndarray) and raw_speech.dtype is np.dtype(np.floataa): _lowerCAmelCase : Union[str, Any] = raw_speech.astype(np.floataa) # always return batch if not is_batched: _lowerCAmelCase : Optional[Any] = [raw_speech] # extract fbank features _lowerCAmelCase : List[str] = [self._extract_mfsc_features(__a) for one_waveform in raw_speech] # convert into correct format for padding _lowerCAmelCase : int = BatchFeature({"input_features": features}) _lowerCAmelCase : str = self.pad( __a, padding=__a, max_length=__a, truncation=__a, pad_to_multiple_of=__a, return_attention_mask=__a, **__a, ) # make sure list is in array format _lowerCAmelCase : Optional[Any] = padded_inputs.get("input_features") if isinstance(input_features[0], __a): _lowerCAmelCase : int = [np.asarray(__a, dtype=np.floataa) for feature in input_features] _lowerCAmelCase : str = padded_inputs.get("attention_mask") if attention_mask is not None: _lowerCAmelCase : Optional[Any] = [np.asarray(__a, dtype=np.intaa) for array in attention_mask] if self.normalize_means or self.normalize_vars: _lowerCAmelCase : int = ( np.array(__a, dtype=np.intaa) if self._get_padding_strategies(__a, max_length=__a) is not PaddingStrategy.DO_NOT_PAD and padding else None ) _lowerCAmelCase : List[Any] = self.normalize( padded_inputs["input_features"], attention_mask=__a) if return_tensors is not None: _lowerCAmelCase : Tuple = padded_inputs.convert_to_tensors(__a) return padded_inputs
36
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() _snake_case = logging.get_logger(__name__) def A ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : List[Any] = "huggingface/label-files" _lowerCAmelCase : int = "imagenet-1k-id2label.json" _lowerCAmelCase : Tuple = json.load(open(hf_hub_download(_lowerCamelCase , _lowerCamelCase , repo_type="dataset" ) , "r" ) ) _lowerCAmelCase : Tuple = {int(_lowerCamelCase ): v for k, v in idalabel.items()} _lowerCAmelCase : Union[str, Any] = {v: k for k, v in idalabel.items()} _lowerCAmelCase : Tuple = "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" _lowerCAmelCase : Optional[int] = BitConfig( conv_layer=_lowerCamelCase , num_labels=1_000 , idalabel=_lowerCamelCase , labelaid=_lowerCamelCase , ) return config def A ( _lowerCamelCase ): '''simple docstring''' if "stem.conv" in name: _lowerCAmelCase : List[str] = name.replace("stem.conv" , "bit.embedder.convolution" ) if "blocks" in name: _lowerCAmelCase : Any = name.replace("blocks" , "layers" ) if "head.fc" in name: _lowerCAmelCase : Optional[Any] = name.replace("head.fc" , "classifier.1" ) if name.startswith("norm" ): _lowerCAmelCase : Any = "bit." + name if "bit" not in name and "classifier" not in name: _lowerCAmelCase : Dict = "bit.encoder." + name return name def A ( ): '''simple docstring''' _lowerCAmelCase : Tuple = "http://images.cocodataset.org/val2017/000000039769.jpg" _lowerCAmelCase : Optional[int] = Image.open(requests.get(_lowerCamelCase , stream=_lowerCamelCase ).raw ) return im @torch.no_grad() def A ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=False ): '''simple docstring''' _lowerCAmelCase : Dict = get_config(_lowerCamelCase ) # load original model from timm _lowerCAmelCase : int = create_model(_lowerCamelCase , pretrained=_lowerCamelCase ) timm_model.eval() # load state_dict of original model _lowerCAmelCase : Any = timm_model.state_dict() for key in state_dict.copy().keys(): _lowerCAmelCase : Dict = state_dict.pop(_lowerCamelCase ) _lowerCAmelCase : Tuple = val.squeeze() if "head" in key else val # load HuggingFace model _lowerCAmelCase : Optional[Any] = BitForImageClassification(_lowerCamelCase ) model.eval() model.load_state_dict(_lowerCamelCase ) # create image processor _lowerCAmelCase : Dict = create_transform(**resolve_data_config({} , model=_lowerCamelCase ) ) _lowerCAmelCase : Optional[int] = transform.transforms _lowerCAmelCase : Tuple = { "bilinear": PILImageResampling.BILINEAR, "bicubic": PILImageResampling.BICUBIC, "nearest": PILImageResampling.NEAREST, } _lowerCAmelCase : Tuple = BitImageProcessor( do_resize=_lowerCamelCase , size={"shortest_edge": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=_lowerCamelCase , crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]} , do_normalize=_lowerCamelCase , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) _lowerCAmelCase : Optional[int] = prepare_img() _lowerCAmelCase : Any = transform(_lowerCamelCase ).unsqueeze(0 ) _lowerCAmelCase : Optional[int] = processor(_lowerCamelCase , return_tensors="pt" ).pixel_values # verify pixel values assert torch.allclose(_lowerCamelCase , _lowerCamelCase ) # verify logits with torch.no_grad(): _lowerCAmelCase : Tuple = model(_lowerCamelCase ) _lowerCAmelCase : str = outputs.logits print("Logits:" , logits[0, :3] ) print("Predicted class:" , model.config.idalabel[logits.argmax(-1 ).item()] ) _lowerCAmelCase : Union[str, Any] = timm_model(_lowerCamelCase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_lowerCamelCase , outputs.logits , atol=1e-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: Path(_lowerCamelCase ).mkdir(exist_ok=_lowerCamelCase ) print(F"Saving model {model_name} and processor to {pytorch_dump_folder_path}" ) model.save_pretrained(_lowerCamelCase ) processor.save_pretrained(_lowerCamelCase ) 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__": _snake_case = 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.", ) _snake_case = parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
36
1
from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline _UpperCAmelCase : Dict = logging.get_logger(__name__) # pylint: disable=invalid-name class lowerCAmelCase ( lowerCamelCase__ ): def __init__( self : Union[str, Any] , UpperCAmelCase : Any , UpperCAmelCase : int ) -> Optional[int]: super().__init__() self.register_modules(unet=__A , scheduler=__A ) @torch.no_grad() def __call__( self : int , UpperCAmelCase : int = 1 , UpperCAmelCase : int = 100 , UpperCAmelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase : Optional[float] = None , UpperCAmelCase : bool = True , ) -> Dict: if audio_length_in_s is None: lowerCamelCase__ : List[Any] = self.unet.config.sample_size / self.unet.config.sample_rate lowerCamelCase__ : Dict = audio_length_in_s * self.unet.config.sample_rate lowerCamelCase__ : int = 2 ** len(self.unet.up_blocks ) if sample_size < 3 * down_scale_factor: raise ValueError( F"""{audio_length_in_s} is too small. Make sure it\'s bigger or equal to""" F""" {3 * down_scale_factor / self.unet.config.sample_rate}.""" ) lowerCamelCase__ : List[Any] = int(__A ) if sample_size % down_scale_factor != 0: lowerCamelCase__ : Union[str, Any] = ( (audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1 ) * down_scale_factor logger.info( F"""{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled""" F""" by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising""" ' process.' ) lowerCamelCase__ : List[str] = int(__A ) lowerCamelCase__ : Any = next(iter(self.unet.parameters() ) ).dtype lowerCamelCase__ : List[Any] = (batch_size, self.unet.config.in_channels, sample_size) if isinstance(__A , __A ) and len(__A ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(__A )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) lowerCamelCase__ : Optional[int] = randn_tensor(__A , generator=__A , device=self.device , dtype=__A ) # set step values self.scheduler.set_timesteps(__A , device=audio.device ) lowerCamelCase__ : str = self.scheduler.timesteps.to(__A ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output lowerCamelCase__ : Tuple = self.unet(__A , __A ).sample # 2. compute previous image: x_t -> t_t-1 lowerCamelCase__ : Union[str, Any] = self.scheduler.step(__A , __A , __A ).prev_sample lowerCamelCase__ : str = audio.clamp(-1 , 1 ).float().cpu().numpy() lowerCamelCase__ : int = audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=__A )
360
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _UpperCAmelCase : int = { """configuration_bigbird_pegasus""": [ """BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BigBirdPegasusConfig""", """BigBirdPegasusOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase : List[str] = [ """BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST""", """BigBirdPegasusForCausalLM""", """BigBirdPegasusForConditionalGeneration""", """BigBirdPegasusForQuestionAnswering""", """BigBirdPegasusForSequenceClassification""", """BigBirdPegasusModel""", """BigBirdPegasusPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdPegasusConfig, BigBirdPegasusOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST, BigBirdPegasusForCausalLM, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, BigBirdPegasusForSequenceClassification, BigBirdPegasusModel, BigBirdPegasusPreTrainedModel, ) else: import sys _UpperCAmelCase : Dict = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
45
0
"""simple docstring""" import inspect import unittest from transformers import BitConfig 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, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import BitBackbone, BitForImageClassification, BitImageProcessor, BitModel from transformers.models.bit.modeling_bit import BIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class lowerCAmelCase__ : '''simple docstring''' def __init__( self : List[str] , lowercase_ : Union[str, Any] , lowercase_ : Tuple=3 , lowercase_ : Union[str, Any]=32 , lowercase_ : Optional[Any]=3 , lowercase_ : Tuple=10 , lowercase_ : Dict=[8, 16, 32, 64] , lowercase_ : List[Any]=[1, 1, 2, 1] , lowercase_ : int=True , lowercase_ : Any=True , lowercase_ : List[str]="relu" , lowercase_ : Dict=3 , lowercase_ : List[str]=None , lowercase_ : Dict=["stage2", "stage3", "stage4"] , lowercase_ : Optional[Any]=[2, 3, 4] , lowercase_ : Any=1 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = parent SCREAMING_SNAKE_CASE_ : List[str] = batch_size SCREAMING_SNAKE_CASE_ : List[Any] = image_size SCREAMING_SNAKE_CASE_ : Tuple = num_channels SCREAMING_SNAKE_CASE_ : List[str] = embeddings_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_sizes SCREAMING_SNAKE_CASE_ : str = depths SCREAMING_SNAKE_CASE_ : List[str] = is_training SCREAMING_SNAKE_CASE_ : List[str] = use_labels SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE_ : List[Any] = num_labels SCREAMING_SNAKE_CASE_ : Optional[int] = scope SCREAMING_SNAKE_CASE_ : List[str] = len(lowercase_) SCREAMING_SNAKE_CASE_ : Dict = out_features SCREAMING_SNAKE_CASE_ : Tuple = out_indices SCREAMING_SNAKE_CASE_ : str = num_groups def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE_ : str = None if self.use_labels: SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size] , self.num_labels) SCREAMING_SNAKE_CASE_ : str = self.get_config() return config, pixel_values, labels def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' return BitConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , out_features=self.out_features , out_indices=self.out_indices , num_groups=self.num_groups , ) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = BitModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Tuple = model(lowercase_) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : Union[str, Any] , lowercase_ : Optional[Any] , lowercase_ : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.num_labels SCREAMING_SNAKE_CASE_ : Optional[int] = BitForImageClassification(lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = BitBackbone(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[str] = model(lowercase_) # 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.hidden_sizes[1], 4, 4]) # 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 SCREAMING_SNAKE_CASE_ : Dict = None SCREAMING_SNAKE_CASE_ : str = BitBackbone(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Any = model(lowercase_) # verify feature maps self.parent.assertEqual(len(result.feature_maps) , 1) self.parent.assertListEqual(list(result.feature_maps[0].shape) , [self.batch_size, self.hidden_sizes[-1], 1, 1]) # verify channels self.parent.assertEqual(len(model.channels) , 1) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]]) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = config_and_inputs SCREAMING_SNAKE_CASE_ : Union[str, Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else () __UpperCamelCase = ( {"feature-extraction": BitModel, "image-classification": BitForImageClassification} if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = BitModelTester(self) SCREAMING_SNAKE_CASE_ : Tuple = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' 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 _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return @unittest.skip(reason='''Bit does not output attentions''') def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' pass @unittest.skip(reason='''Bit does not use inputs_embeds''') def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' pass @unittest.skip(reason='''Bit does not support input and output embeddings''') def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Any = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : Any = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : int = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Dict = model_class(config=lowercase_) for name, module in model.named_modules(): if isinstance(lowercase_ , (nn.BatchNormad, nn.GroupNorm)): self.assertTrue( torch.all(module.weight == 1) , msg=F'Parameter {name} of model {model_class} seems not properly initialized' , ) self.assertTrue( torch.all(module.bias == 0) , msg=F'Parameter {name} of model {model_class} seems not properly initialized' , ) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' def check_hidden_states_output(lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[str]): SCREAMING_SNAKE_CASE_ : Optional[int] = model_class(lowercase_) model.to(lowercase_) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : int = model(**self._prepare_for_class(lowercase_ , lowercase_)) SCREAMING_SNAKE_CASE_ : Optional[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE_ : Dict = self.model_tester.num_stages self.assertEqual(len(lowercase_) , expected_num_stages + 1) # Bit's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : Any = ['''preactivation''', '''bottleneck'''] for model_class in self.all_model_classes: for layer_type in layers_type: SCREAMING_SNAKE_CASE_ : Union[str, Any] = layer_type SCREAMING_SNAKE_CASE_ : str = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ : Union[str, Any] = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) @unittest.skip(reason='''Bit does not use feedforward chunking''') def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_) @slow def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Dict = BitModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) def _A () -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' return ( BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to(lowercase_) SCREAMING_SNAKE_CASE_ : str = self.default_image_processor SCREAMING_SNAKE_CASE_ : Dict = prepare_img() SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_processor(images=lowercase_ , return_tensors='''pt''').to(lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : str = model(**lowercase_) # verify the logits SCREAMING_SNAKE_CASE_ : int = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([[-0.65_26, -0.52_63, -1.43_98]]).to(lowercase_) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase_ , atol=1e-4)) @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = (BitBackbone,) if is_torch_available() else () __UpperCamelCase = BitConfig __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = BitModelTester(self)
91
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL UpperCAmelCase_ : int = logging.get_logger(__name__) def _A (__a ) -> List[List[ImageInput]]: """simple docstring""" if isinstance(__a , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(__a , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(__a ): return [[videos]] raise ValueError(f'Could not make batched video from {videos}' ) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["pixel_values"] def __init__( self : Dict , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : bool = True , lowercase_ : Union[int, float] = 1 / 255 , lowercase_ : bool = True , lowercase_ : bool = True , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , **lowercase_ : Dict , ): '''simple docstring''' super().__init__(**lowercase_) SCREAMING_SNAKE_CASE_ : str = size if size is not None else {'''shortest_edge''': 256} SCREAMING_SNAKE_CASE_ : Optional[int] = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') SCREAMING_SNAKE_CASE_ : Optional[int] = do_resize SCREAMING_SNAKE_CASE_ : List[Any] = size SCREAMING_SNAKE_CASE_ : Tuple = do_center_crop SCREAMING_SNAKE_CASE_ : Dict = crop_size SCREAMING_SNAKE_CASE_ : List[Any] = resample SCREAMING_SNAKE_CASE_ : List[str] = do_rescale SCREAMING_SNAKE_CASE_ : List[str] = rescale_factor SCREAMING_SNAKE_CASE_ : List[Any] = offset SCREAMING_SNAKE_CASE_ : List[Any] = do_normalize SCREAMING_SNAKE_CASE_ : Tuple = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE_ : Optional[int] = image_std if image_std is not None else IMAGENET_STANDARD_STD def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) if "shortest_edge" in size: SCREAMING_SNAKE_CASE_ : List[Any] = get_resize_output_image_size(lowercase_ , size['''shortest_edge'''] , default_to_square=lowercase_) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE_ : Union[str, Any] = (size['''height'''], size['''width''']) else: raise ValueError(F'Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}') return resize(lowercase_ , size=lowercase_ , resample=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = get_size_dict(lowercase_) if "height" not in size or "width" not in size: raise ValueError(F'Size must have \'height\' and \'width\' as keys. Got {size.keys()}') return center_crop(lowercase_ , size=(size['''height'''], size['''width''']) , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Union[int, float] , lowercase_ : bool = True , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = image.astype(np.floataa) if offset: SCREAMING_SNAKE_CASE_ : Tuple = image - (scale / 2) return rescale(lowercase_ , scale=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : np.ndarray , lowercase_ : Union[float, List[float]] , lowercase_ : Union[float, List[float]] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[str] , ): '''simple docstring''' return normalize(lowercase_ , mean=lowercase_ , std=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[ChannelDimension] = ChannelDimension.FIRST , ): '''simple docstring''' if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''') if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''') if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''') if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''') if offset and not do_rescale: raise ValueError('''For offset, do_rescale must also be set to True.''') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_ : List[str] = to_numpy_array(lowercase_) if do_resize: SCREAMING_SNAKE_CASE_ : List[Any] = self.resize(image=lowercase_ , size=lowercase_ , resample=lowercase_) if do_center_crop: SCREAMING_SNAKE_CASE_ : Dict = self.center_crop(lowercase_ , size=lowercase_) if do_rescale: SCREAMING_SNAKE_CASE_ : int = self.rescale(image=lowercase_ , scale=lowercase_ , offset=lowercase_) if do_normalize: SCREAMING_SNAKE_CASE_ : Dict = self.normalize(image=lowercase_ , mean=lowercase_ , std=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = to_channel_dimension_format(lowercase_ , lowercase_) return image def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[str, TensorType]] = None , lowercase_ : ChannelDimension = ChannelDimension.FIRST , **lowercase_ : Optional[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_ : int = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_ : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE_ : Dict = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE_ : Dict = offset if offset is not None else self.offset SCREAMING_SNAKE_CASE_ : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_ : Dict = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE_ : List[str] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE_ : Union[str, Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Any = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') if not valid_images(lowercase_): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''') SCREAMING_SNAKE_CASE_ : Tuple = make_batched(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = [ [ self._preprocess_image( image=lowercase_ , do_resize=lowercase_ , size=lowercase_ , resample=lowercase_ , do_center_crop=lowercase_ , crop_size=lowercase_ , do_rescale=lowercase_ , rescale_factor=lowercase_ , offset=lowercase_ , do_normalize=lowercase_ , image_mean=lowercase_ , image_std=lowercase_ , data_format=lowercase_ , ) for img in video ] for video in videos ] SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': videos} return BatchFeature(data=lowercase_ , tensor_type=lowercase_)
91
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging __lowercase = logging.get_logger(__name__) if is_vision_available(): import PIL class _lowercase ( __a ): """simple docstring""" lowercase__ = ['''pixel_values'''] def __init__( self : List[str] , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 255 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : bool = True , **UpperCamelCase__ : List[Any] , ) -> None: '''simple docstring''' super().__init__(**UpperCamelCase__ ) __UpperCamelCase =size if size is not None else {'''shortest_edge''': 224} __UpperCamelCase =get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) __UpperCamelCase =crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} __UpperCamelCase =get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ , param_name='''crop_size''' ) __UpperCamelCase =do_resize __UpperCamelCase =size __UpperCamelCase =resample __UpperCamelCase =do_center_crop __UpperCamelCase =crop_size __UpperCamelCase =do_rescale __UpperCamelCase =rescale_factor __UpperCamelCase =do_normalize __UpperCamelCase =image_mean if image_mean is not None else OPENAI_CLIP_MEAN __UpperCamelCase =image_std if image_std is not None else OPENAI_CLIP_STD __UpperCamelCase =do_convert_rgb def UpperCAmelCase_ ( self : List[str] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Dict , ) -> np.ndarray: '''simple docstring''' __UpperCamelCase =get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) if "shortest_edge" not in size: raise ValueError(f"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" ) __UpperCamelCase =get_resize_output_image_size(UpperCamelCase__ , size=size['''shortest_edge'''] , default_to_square=UpperCamelCase__ ) return resize(UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple , ) -> np.ndarray: '''simple docstring''' __UpperCamelCase =get_size_dict(UpperCamelCase__ ) if "height" not in size or "width" not in size: raise ValueError(f"""The `size` parameter must contain the keys (height, width). Got {size.keys()}""" ) return center_crop(UpperCamelCase__ , size=(size['''height'''], size['''width''']) , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[int, float] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Any , ) -> List[str]: '''simple docstring''' return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def UpperCAmelCase_ ( self : Any , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Optional[int] , ) -> np.ndarray: '''simple docstring''' return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def UpperCAmelCase_ ( self : List[str] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : bool = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : int = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : float = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : Optional[ChannelDimension] = ChannelDimension.FIRST , **UpperCamelCase__ : Tuple , ) -> PIL.Image.Image: '''simple docstring''' __UpperCamelCase =do_resize if do_resize is not None else self.do_resize __UpperCamelCase =size if size is not None else self.size __UpperCamelCase =get_size_dict(UpperCamelCase__ , param_name='''size''' , default_to_square=UpperCamelCase__ ) __UpperCamelCase =resample if resample is not None else self.resample __UpperCamelCase =do_center_crop if do_center_crop is not None else self.do_center_crop __UpperCamelCase =crop_size if crop_size is not None else self.crop_size __UpperCamelCase =get_size_dict(UpperCamelCase__ , param_name='''crop_size''' , default_to_square=UpperCamelCase__ ) __UpperCamelCase =do_rescale if do_rescale is not None else self.do_rescale __UpperCamelCase =rescale_factor if rescale_factor is not None else self.rescale_factor __UpperCamelCase =do_normalize if do_normalize is not None else self.do_normalize __UpperCamelCase =image_mean if image_mean is not None else self.image_mean __UpperCamelCase =image_std if image_std is not None else self.image_std __UpperCamelCase =do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __UpperCamelCase =make_list_of_images(UpperCamelCase__ ) if not valid_images(UpperCamelCase__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # PIL RGBA images are converted to RGB if do_convert_rgb: __UpperCamelCase =[convert_to_rgb(UpperCamelCase__ ) for image in images] # All transformations expect numpy arrays. __UpperCamelCase =[to_numpy_array(UpperCamelCase__ ) for image in images] if do_resize: __UpperCamelCase =[self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images] if do_center_crop: __UpperCamelCase =[self.center_crop(image=UpperCamelCase__ , size=UpperCamelCase__ ) for image in images] if do_rescale: __UpperCamelCase =[self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images] if do_normalize: __UpperCamelCase =[self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images] __UpperCamelCase =[to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images] __UpperCamelCase ={'''pixel_values''': images} return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ )
85
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable __lowercase = {'''configuration_gpt_neox''': ['''GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXConfig''']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = ['''GPTNeoXTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = [ '''GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXForCausalLM''', '''GPTNeoXForQuestionAnswering''', '''GPTNeoXForSequenceClassification''', '''GPTNeoXForTokenClassification''', '''GPTNeoXLayer''', '''GPTNeoXModel''', '''GPTNeoXPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys __lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
85
1
def A_ ( snake_case : int ) -> None: '''simple docstring''' __UpperCamelCase = generate_pascal_triangle(__A ) for row_idx in range(__A ): # Print left spaces for _ in range(num_rows - row_idx - 1 ): print(end=''' ''' ) # Print row values for col_idx in range(row_idx + 1 ): if col_idx != row_idx: print(triangle[row_idx][col_idx] , end=''' ''' ) else: print(triangle[row_idx][col_idx] , end='''''' ) print() def A_ ( snake_case : int ) -> list[list[int]]: '''simple docstring''' if not isinstance(__A , __A ): raise TypeError('''The input value of \'num_rows\' should be \'int\'''' ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( '''The input value of \'num_rows\' should be greater than or equal to 0''' ) __UpperCamelCase = [] for current_row_idx in range(__A ): __UpperCamelCase = populate_current_row(__A , __A ) triangle.append(__A ) return triangle def A_ ( snake_case : list[list[int]] , snake_case : int ) -> list[int]: '''simple docstring''' __UpperCamelCase = [-1] * (current_row_idx + 1) # first and last elements of current row are equal to 1 __UpperCamelCase , __UpperCamelCase = 1, 1 for current_col_idx in range(1 , __A ): calculate_current_element( __A , __A , __A , __A ) return current_row def A_ ( snake_case : list[list[int]] , snake_case : list[int] , snake_case : int , snake_case : int , ) -> None: '''simple docstring''' __UpperCamelCase = triangle[current_row_idx - 1][current_col_idx - 1] __UpperCamelCase = triangle[current_row_idx - 1][current_col_idx] __UpperCamelCase = above_to_left_elt + above_to_right_elt def A_ ( snake_case : int ) -> list[list[int]]: '''simple docstring''' if not isinstance(__A , __A ): raise TypeError('''The input value of \'num_rows\' should be \'int\'''' ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( '''The input value of \'num_rows\' should be greater than or equal to 0''' ) __UpperCamelCase = [[1]] for row_index in range(1 , __A ): __UpperCamelCase = [0] + result[-1] + [0] __UpperCamelCase = row_index + 1 # Calculate the number of distinct elements in a row __UpperCamelCase = sum(divmod(__A , 2 ) ) __UpperCamelCase = [ temp_row[i - 1] + temp_row[i] for i in range(1 , distinct_elements + 1 ) ] __UpperCamelCase = row_first_half[: (row_index + 1) // 2] row_second_half.reverse() __UpperCamelCase = row_first_half + row_second_half result.append(__A ) return result def A_ ( ) -> None: '''simple docstring''' from collections.abc import Callable from timeit import timeit def benchmark_a_function(snake_case : Callable , snake_case : int ) -> None: __UpperCamelCase = f"{func.__name__}({value})" __UpperCamelCase = timeit(f"__main__.{call}" , setup='''import __main__''' ) # print(f"{call:38} = {func(value)} -- {timing:.4f} seconds") print(f"{call:38} -- {timing:.4f} seconds" ) for value in range(15 ): # (1, 7, 14): for func in (generate_pascal_triangle, generate_pascal_triangle_optimized): benchmark_a_function(__A , __A ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
328
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) snake_case_ : int = { "configuration_deberta": ["DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP", "DebertaConfig", "DebertaOnnxConfig"], "tokenization_deberta": ["DebertaTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : int = ["DebertaTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : List[str] = [ "DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "DebertaForMaskedLM", "DebertaForQuestionAnswering", "DebertaForSequenceClassification", "DebertaForTokenClassification", "DebertaModel", "DebertaPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Any = [ "TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDebertaForMaskedLM", "TFDebertaForQuestionAnswering", "TFDebertaForSequenceClassification", "TFDebertaForTokenClassification", "TFDebertaModel", "TFDebertaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys snake_case_ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
51
0
import os import sys import unittest a : Optional[Any] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model_to_tester_mapping, get_test_to_tester_mapping, ) a : List[str] = os.path.join('tests', 'models', 'bert', 'test_modeling_bert.py') a : Any = os.path.join('tests', 'models', 'blip', 'test_modeling_blip.py') class _a ( unittest.TestCase ): def __snake_case (self ) -> Tuple: UpperCAmelCase_: Any = get_test_to_tester_mapping(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Union[str, Any] = get_test_to_tester_mapping(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Optional[Any] = {"""BertModelTest""": """BertModelTester"""} UpperCAmelCase_: str = { """BlipModelTest""": """BlipModelTester""", """BlipTextImageModelTest""": """BlipTextImageModelsModelTester""", """BlipTextModelTest""": """BlipTextModelTester""", """BlipTextRetrievalModelTest""": """BlipTextRetrievalModelTester""", """BlipVQAModelTest""": """BlipVQAModelTester""", """BlipVisionModelTest""": """BlipVisionModelTester""", } self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE_ ), SCREAMING_SNAKE_CASE_ ) self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE_ ), SCREAMING_SNAKE_CASE_ ) def __snake_case (self ) -> Optional[Any]: UpperCAmelCase_: Optional[Any] = get_model_to_test_mapping(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Tuple = get_model_to_test_mapping(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: str = { """BertForMaskedLM""": ["""BertModelTest"""], """BertForMultipleChoice""": ["""BertModelTest"""], """BertForNextSentencePrediction""": ["""BertModelTest"""], """BertForPreTraining""": ["""BertModelTest"""], """BertForQuestionAnswering""": ["""BertModelTest"""], """BertForSequenceClassification""": ["""BertModelTest"""], """BertForTokenClassification""": ["""BertModelTest"""], """BertLMHeadModel""": ["""BertModelTest"""], """BertModel""": ["""BertModelTest"""], } UpperCAmelCase_: int = { """BlipForConditionalGeneration""": ["""BlipTextImageModelTest"""], """BlipForImageTextRetrieval""": ["""BlipTextRetrievalModelTest"""], """BlipForQuestionAnswering""": ["""BlipVQAModelTest"""], """BlipModel""": ["""BlipModelTest"""], """BlipTextModel""": ["""BlipTextModelTest"""], """BlipVisionModel""": ["""BlipVisionModelTest"""], } self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE_ ), SCREAMING_SNAKE_CASE_ ) self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE_ ), SCREAMING_SNAKE_CASE_ ) def __snake_case (self ) -> int: UpperCAmelCase_: Optional[int] = get_model_to_tester_mapping(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: List[Any] = get_model_to_tester_mapping(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Dict = { """BertForMaskedLM""": ["""BertModelTester"""], """BertForMultipleChoice""": ["""BertModelTester"""], """BertForNextSentencePrediction""": ["""BertModelTester"""], """BertForPreTraining""": ["""BertModelTester"""], """BertForQuestionAnswering""": ["""BertModelTester"""], """BertForSequenceClassification""": ["""BertModelTester"""], """BertForTokenClassification""": ["""BertModelTester"""], """BertLMHeadModel""": ["""BertModelTester"""], """BertModel""": ["""BertModelTester"""], } UpperCAmelCase_: Optional[int] = { """BlipForConditionalGeneration""": ["""BlipTextImageModelsModelTester"""], """BlipForImageTextRetrieval""": ["""BlipTextRetrievalModelTester"""], """BlipForQuestionAnswering""": ["""BlipVQAModelTester"""], """BlipModel""": ["""BlipModelTester"""], """BlipTextModel""": ["""BlipTextModelTester"""], """BlipVisionModel""": ["""BlipVisionModelTester"""], } self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE_ ), SCREAMING_SNAKE_CASE_ ) self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE_ ), SCREAMING_SNAKE_CASE_ )
82
import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->UnCLIP class _a ( _lowerCAmelCase ): A = 42 A = None def lowerCAmelCase_ (lowerCAmelCase__: List[str] , lowerCAmelCase__: Optional[int]=0.999 , lowerCAmelCase__: List[str]="cosine" , ): """simple docstring""" if alpha_transform_type == "cosine": def alpha_bar_fn(lowerCAmelCase__: List[str] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(lowerCAmelCase__: str ): return math.exp(t * -12.0 ) else: raise ValueError(F'Unsupported alpha_tranform_type: {alpha_transform_type}' ) UpperCAmelCase_: List[Any] = [] for i in range(lowerCAmelCase__ ): UpperCAmelCase_: Optional[int] = i / num_diffusion_timesteps UpperCAmelCase_: int = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(lowerCAmelCase__ ) / alpha_bar_fn(lowerCAmelCase__ ) , lowerCAmelCase__ ) ) return torch.tensor(lowerCAmelCase__ , dtype=torch.floataa ) class _a ( _lowerCAmelCase , _lowerCAmelCase ): @register_to_config def __init__(self, SCREAMING_SNAKE_CASE_ = 1000, SCREAMING_SNAKE_CASE_ = "fixed_small_log", SCREAMING_SNAKE_CASE_ = True, SCREAMING_SNAKE_CASE_ = 1.0, SCREAMING_SNAKE_CASE_ = "epsilon", SCREAMING_SNAKE_CASE_ = "squaredcos_cap_v2", ) -> List[Any]: if beta_schedule != "squaredcos_cap_v2": raise ValueError("""UnCLIPScheduler only supports `beta_schedule`: 'squaredcos_cap_v2'""" ) UpperCAmelCase_: Tuple = betas_for_alpha_bar(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Dict = 1.0 - self.betas UpperCAmelCase_: int = torch.cumprod(self.alphas, dim=0 ) UpperCAmelCase_: Tuple = torch.tensor(1.0 ) # standard deviation of the initial noise distribution UpperCAmelCase_: List[str] = 1.0 # setable values UpperCAmelCase_: str = None UpperCAmelCase_: str = torch.from_numpy(np.arange(0, SCREAMING_SNAKE_CASE_ )[::-1].copy() ) UpperCAmelCase_: Dict = variance_type def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None ) -> torch.FloatTensor: return sample def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None ) -> Optional[Any]: UpperCAmelCase_: Optional[Any] = num_inference_steps UpperCAmelCase_: Tuple = (self.config.num_train_timesteps - 1) / (self.num_inference_steps - 1) UpperCAmelCase_: Tuple = (np.arange(0, SCREAMING_SNAKE_CASE_ ) * step_ratio).round()[::-1].copy().astype(np.intaa ) UpperCAmelCase_: Any = torch.from_numpy(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_=None ) -> List[Any]: if prev_timestep is None: UpperCAmelCase_: Any = t - 1 UpperCAmelCase_: int = self.alphas_cumprod[t] UpperCAmelCase_: Optional[int] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one UpperCAmelCase_: int = 1 - alpha_prod_t UpperCAmelCase_: List[Any] = 1 - alpha_prod_t_prev if prev_timestep == t - 1: UpperCAmelCase_: List[str] = self.betas[t] else: UpperCAmelCase_: List[str] = 1 - alpha_prod_t / alpha_prod_t_prev # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample UpperCAmelCase_: Tuple = beta_prod_t_prev / beta_prod_t * beta if variance_type is None: UpperCAmelCase_: List[Any] = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small_log": UpperCAmelCase_: str = torch.log(torch.clamp(SCREAMING_SNAKE_CASE_, min=1E-20 ) ) UpperCAmelCase_: Dict = torch.exp(0.5 * variance ) elif variance_type == "learned_range": # NOTE difference with DDPM scheduler UpperCAmelCase_: Dict = variance.log() UpperCAmelCase_: Tuple = beta.log() UpperCAmelCase_: int = (predicted_variance + 1) / 2 UpperCAmelCase_: int = frac * max_log + (1 - frac) * min_log return variance def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_ = True, ) -> Union[UnCLIPSchedulerOutput, Tuple]: UpperCAmelCase_: List[Any] = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type == "learned_range": UpperCAmelCase_ , UpperCAmelCase_: List[str] = torch.split(SCREAMING_SNAKE_CASE_, sample.shape[1], dim=1 ) else: UpperCAmelCase_: Union[str, Any] = None # 1. compute alphas, betas if prev_timestep is None: UpperCAmelCase_: List[Any] = t - 1 UpperCAmelCase_: Optional[int] = self.alphas_cumprod[t] UpperCAmelCase_: Union[str, Any] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one UpperCAmelCase_: Optional[Any] = 1 - alpha_prod_t UpperCAmelCase_: Optional[Any] = 1 - alpha_prod_t_prev if prev_timestep == t - 1: UpperCAmelCase_: Tuple = self.betas[t] UpperCAmelCase_: Dict = self.alphas[t] else: UpperCAmelCase_: List[Any] = 1 - alpha_prod_t / alpha_prod_t_prev UpperCAmelCase_: List[str] = 1 - beta # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": UpperCAmelCase_: Union[str, Any] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": UpperCAmelCase_: int = model_output else: raise ValueError( f'prediction_type given as {self.config.prediction_type} must be one of `epsilon` or `sample`' """ for the UnCLIPScheduler.""" ) # 3. Clip "predicted x_0" if self.config.clip_sample: UpperCAmelCase_: Optional[int] = torch.clamp( SCREAMING_SNAKE_CASE_, -self.config.clip_sample_range, self.config.clip_sample_range ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf UpperCAmelCase_: Optional[Any] = (alpha_prod_t_prev ** 0.5 * beta) / beta_prod_t UpperCAmelCase_: Optional[int] = alpha ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf UpperCAmelCase_: List[str] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise UpperCAmelCase_: Union[str, Any] = 0 if t > 0: UpperCAmelCase_: Any = randn_tensor( model_output.shape, dtype=model_output.dtype, generator=SCREAMING_SNAKE_CASE_, device=model_output.device ) UpperCAmelCase_: Dict = self._get_variance( SCREAMING_SNAKE_CASE_, predicted_variance=SCREAMING_SNAKE_CASE_, prev_timestep=SCREAMING_SNAKE_CASE_, ) if self.variance_type == "fixed_small_log": UpperCAmelCase_: Optional[int] = variance elif self.variance_type == "learned_range": UpperCAmelCase_: Dict = (0.5 * variance).exp() else: raise ValueError( f'variance_type given as {self.variance_type} must be one of `fixed_small_log` or `learned_range`' """ for the UnCLIPScheduler.""" ) UpperCAmelCase_: int = variance * variance_noise UpperCAmelCase_: List[Any] = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return UnCLIPSchedulerOutput(prev_sample=SCREAMING_SNAKE_CASE_, pred_original_sample=SCREAMING_SNAKE_CASE_ ) def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, ) -> torch.FloatTensor: # Make sure alphas_cumprod and timestep have same device and dtype as original_samples UpperCAmelCase_: Tuple = self.alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype ) UpperCAmelCase_: Union[str, Any] = timesteps.to(original_samples.device ) UpperCAmelCase_: Dict = alphas_cumprod[timesteps] ** 0.5 UpperCAmelCase_: int = sqrt_alpha_prod.flatten() while len(sqrt_alpha_prod.shape ) < len(original_samples.shape ): UpperCAmelCase_: str = sqrt_alpha_prod.unsqueeze(-1 ) UpperCAmelCase_: Tuple = (1 - alphas_cumprod[timesteps]) ** 0.5 UpperCAmelCase_: Optional[Any] = sqrt_one_minus_alpha_prod.flatten() while len(sqrt_one_minus_alpha_prod.shape ) < len(original_samples.shape ): UpperCAmelCase_: Optional[int] = sqrt_one_minus_alpha_prod.unsqueeze(-1 ) UpperCAmelCase_: List[str] = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples
82
1
"""simple docstring""" import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py SCREAMING_SNAKE_CASE__ = "src/diffusers" # Matches is_xxx_available() SCREAMING_SNAKE_CASE__ = re.compile(R"is\_([a-z_]*)_available\(\)") # Matches from xxx import bla SCREAMING_SNAKE_CASE__ = re.compile(R"\s+from\s+\S*\s+import\s+([^\(\s].*)\n") SCREAMING_SNAKE_CASE__ = "\n{0} = None\n" SCREAMING_SNAKE_CASE__ = "\nclass {0}(metaclass=DummyObject):\n _backends = {1}\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, {1})\n\n @classmethod\n def from_config(cls, *args, **kwargs):\n requires_backends(cls, {1})\n\n @classmethod\n def from_pretrained(cls, *args, **kwargs):\n requires_backends(cls, {1})\n" SCREAMING_SNAKE_CASE__ = "\ndef {0}(*args, **kwargs):\n requires_backends({0}, {1})\n" def lowerCAmelCase__ ( _UpperCamelCase : int ) -> Union[str, Any]: """simple docstring""" snake_case = _re_backend.findall(_UpperCamelCase ) if len(_UpperCamelCase ) == 0: return None return "_and_".join(_UpperCamelCase ) def lowerCAmelCase__ ( ) -> List[str]: """simple docstring""" with open(os.path.join(_UpperCamelCase , '__init__.py' ) , 'r' , encoding='utf-8' , newline='\n' ) as f: snake_case = f.readlines() # Get to the point we do the actual imports for type checking snake_case = 0 snake_case = {} # Go through the end of the file while line_index < len(_UpperCamelCase ): # If the line contains is_backend_available, we grab all objects associated with the `else` block snake_case = find_backend(lines[line_index] ) if backend is not None: while not lines[line_index].startswith('else:' ): line_index += 1 line_index += 1 snake_case = [] # Until we unindent, add backend objects to the list while line_index < len(_UpperCamelCase ) and len(lines[line_index] ) > 1: snake_case = lines[line_index] snake_case = _re_single_line_import.search(_UpperCamelCase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 8 ): objects.append(line[8:-2] ) line_index += 1 if len(_UpperCamelCase ) > 0: snake_case = objects else: line_index += 1 return backend_specific_objects def lowerCAmelCase__ ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : str ) -> int: """simple docstring""" if name.isupper(): return DUMMY_CONSTANT.format(_UpperCamelCase ) elif name.islower(): return DUMMY_FUNCTION.format(_UpperCamelCase , _UpperCamelCase ) else: return DUMMY_CLASS.format(_UpperCamelCase , _UpperCamelCase ) def lowerCAmelCase__ ( _UpperCamelCase : Any=None ) -> Optional[Any]: """simple docstring""" if backend_specific_objects is None: snake_case = read_init() # For special correspondence backend to module name as used in the function requires_modulename snake_case = {} for backend, objects in backend_specific_objects.items(): snake_case = '[' + ', '.join(f"""\"{b}\"""" for b in backend.split('_and_' ) ) + ']' snake_case = '# This file is autogenerated by the command `make fix-copies`, do not edit.\n' dummy_file += "from ..utils import DummyObject, requires_backends\n\n" dummy_file += "\n".join([create_dummy_object(_UpperCamelCase , _UpperCamelCase ) for o in objects] ) snake_case = dummy_file return dummy_files def lowerCAmelCase__ ( _UpperCamelCase : Optional[int]=False ) -> Optional[Any]: """simple docstring""" snake_case = create_dummy_files() # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py snake_case = {'torch': 'pt'} # Locate actual dummy modules and read their content. snake_case = os.path.join(_UpperCamelCase , 'utils' ) snake_case = { backend: os.path.join(_UpperCamelCase , f"""dummy_{short_names.get(_UpperCamelCase , _UpperCamelCase )}_objects.py""" ) for backend in dummy_files.keys() } snake_case = {} for backend, file_path in dummy_file_paths.items(): if os.path.isfile(_UpperCamelCase ): with open(_UpperCamelCase , 'r' , encoding='utf-8' , newline='\n' ) as f: snake_case = f.read() else: snake_case = '' for backend in dummy_files.keys(): if dummy_files[backend] != actual_dummies[backend]: if overwrite: print( f"""Updating diffusers.utils.dummy_{short_names.get(_UpperCamelCase , _UpperCamelCase )}_objects.py as the main """ '__init__ has new objects.' ) with open(dummy_file_paths[backend] , 'w' , encoding='utf-8' , newline='\n' ) as f: f.write(dummy_files[backend] ) else: raise ValueError( 'The main __init__ has objects that are not present in ' f"""diffusers.utils.dummy_{short_names.get(_UpperCamelCase , _UpperCamelCase )}_objects.py. Run `make fix-copies` """ 'to fix this.' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") SCREAMING_SNAKE_CASE__ = parser.parse_args() check_dummies(args.fix_and_overwrite)
150
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax.numpy as jnp from jax import random from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .scheduling_utils_flax import FlaxSchedulerMixin @flax.struct.dataclass class lowerCAmelCase_ : """simple docstring""" # setable values _lowerCAmelCase : Optional[int] = None _lowerCAmelCase : Optional[jnp.ndarray] = None _lowerCAmelCase : Optional[jnp.ndarray] = None # sigma(t_i) @classmethod def snake_case ( cls ): """simple docstring""" return cls() @dataclass class lowerCAmelCase_ ( lowerCAmelCase ): """simple docstring""" _lowerCAmelCase : jnp.ndarray _lowerCAmelCase : jnp.ndarray _lowerCAmelCase : KarrasVeSchedulerState class lowerCAmelCase_ ( lowerCAmelCase , lowerCAmelCase ): """simple docstring""" @property def snake_case ( self ): """simple docstring""" return True @register_to_config def __init__( self , lowerCAmelCase = 0.02 , lowerCAmelCase = 1_00 , lowerCAmelCase = 1.0_07 , lowerCAmelCase = 80 , lowerCAmelCase = 0.05 , lowerCAmelCase = 50 , ): """simple docstring""" pass def snake_case ( self ): """simple docstring""" return KarrasVeSchedulerState.create() def snake_case ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = () ): """simple docstring""" snake_case = jnp.arange(0 , lowerCAmelCase )[::-1].copy() snake_case = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in timesteps ] return state.replace( num_inference_steps=lowerCAmelCase , schedule=jnp.array(lowerCAmelCase , dtype=jnp.floataa ) , timesteps=lowerCAmelCase , ) def snake_case ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , ): """simple docstring""" if self.config.s_min <= sigma <= self.config.s_max: snake_case = min(self.config.s_churn / state.num_inference_steps , 2**0.5 - 1 ) else: snake_case = 0 # sample eps ~ N(0, S_noise^2 * I) snake_case = random.split(lowerCAmelCase , num=1 ) snake_case = self.config.s_noise * random.normal(key=lowerCAmelCase , shape=sample.shape ) snake_case = sigma + gamma * sigma snake_case = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def snake_case ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = True , ): """simple docstring""" snake_case = sample_hat + sigma_hat * model_output snake_case = (sample_hat - pred_original_sample) / sigma_hat snake_case = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=lowerCAmelCase , derivative=lowerCAmelCase , state=lowerCAmelCase ) def snake_case ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = True , ): """simple docstring""" snake_case = sample_prev + sigma_prev * model_output snake_case = (sample_prev - pred_original_sample) / sigma_prev snake_case = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=lowerCAmelCase , derivative=lowerCAmelCase , state=lowerCAmelCase ) def snake_case ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" raise NotImplementedError()
150
1
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss _snake_case = pytest.mark.integration @require_faiss class _snake_case ( _lowercase ): def _lowerCamelCase ( self: Union[str, Any] ) -> str: __UpperCAmelCase : Optional[int] = Dataset.from_dict({"filename": ["my_name-train" + "_" + str(__lowerCamelCase ) for x in np.arange(30 ).tolist()]} ) return dset def _lowerCamelCase ( self: Optional[Any] ) -> Tuple: import faiss __UpperCAmelCase : Dataset = self._create_dummy_dataset() __UpperCAmelCase : int = dset.map( lambda __lowerCamelCase , __lowerCamelCase : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__lowerCamelCase , keep_in_memory=__lowerCamelCase ) __UpperCAmelCase : Tuple = dset.add_faiss_index("vecs" , batch_size=1_00 , metric_type=faiss.METRIC_INNER_PRODUCT ) __UpperCAmelCase , __UpperCAmelCase : Dict = dset.get_nearest_examples("vecs" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) dset.drop_index("vecs" ) def _lowerCamelCase ( self: List[str] ) -> int: import faiss __UpperCAmelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" , batch_size=1_00 , metric_type=faiss.METRIC_INNER_PRODUCT , ) __UpperCAmelCase , __UpperCAmelCase : Tuple = dset.get_nearest_examples("vecs" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) def _lowerCamelCase ( self: Optional[int] ) -> Dict: import faiss __UpperCAmelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__lowerCamelCase ) as tmp_file: dset.save_faiss_index("vecs" , tmp_file.name ) dset.load_faiss_index("vecs2" , tmp_file.name ) os.unlink(tmp_file.name ) __UpperCAmelCase , __UpperCAmelCase : List[Any] = dset.get_nearest_examples("vecs2" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) def _lowerCamelCase ( self: List[Any] ) -> List[Any]: __UpperCAmelCase : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" ) dset.drop_index("vecs" ) self.assertRaises(__lowerCamelCase , partial(dset.get_nearest_examples , "vecs2" , np.ones(5 , dtype=np.floataa ) ) ) def _lowerCamelCase ( self: List[str] ) -> Dict: from elasticsearch import Elasticsearch __UpperCAmelCase : Dataset = self._create_dummy_dataset() with patch("elasticsearch.Elasticsearch.search" ) as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk" ) as mocked_bulk: __UpperCAmelCase : int = {"acknowledged": True} mocked_bulk.return_value([(True, None)] * 30 ) __UpperCAmelCase : Dict = {"hits": {"hits": [{"_score": 1, "_id": 29}]}} __UpperCAmelCase : Any = Elasticsearch() dset.add_elasticsearch_index("filename" , es_client=__lowerCamelCase ) __UpperCAmelCase , __UpperCAmelCase : Optional[int] = dset.get_nearest_examples("filename" , "my_name-train_29" ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) @require_faiss class _snake_case ( _lowercase ): def _lowerCamelCase ( self: List[str] ) -> Optional[int]: import faiss __UpperCAmelCase : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query __UpperCAmelCase : Dict = np.zeros(5 , dtype=np.floataa ) __UpperCAmelCase : List[str] = 1 __UpperCAmelCase , __UpperCAmelCase : List[str] = index.search(__lowerCamelCase ) self.assertRaises(__lowerCamelCase , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries __UpperCAmelCase : List[str] = np.eye(5 , dtype=np.floataa )[::-1] __UpperCAmelCase , __UpperCAmelCase : Any = index.search_batch(__lowerCamelCase ) self.assertRaises(__lowerCamelCase , index.search_batch , queries[0] ) __UpperCAmelCase : Dict = [scores[0] for scores in total_scores] __UpperCAmelCase : int = [indices[0] for indices in total_indices] self.assertGreater(np.min(__lowerCamelCase ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __lowerCamelCase ) def _lowerCamelCase ( self: Any ) -> List[str]: import faiss __UpperCAmelCase : Dict = FaissIndex(string_factory="Flat" ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) __UpperCAmelCase : Optional[Any] = FaissIndex(string_factory="LSH" ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__lowerCamelCase ): __UpperCAmelCase : Any = FaissIndex(string_factory="Flat" , custom_index=faiss.IndexFlat(5 ) ) def _lowerCamelCase ( self: List[str] ) -> Dict: import faiss __UpperCAmelCase : str = faiss.IndexFlat(5 ) __UpperCAmelCase : int = FaissIndex(custom_index=__lowerCamelCase ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def _lowerCamelCase ( self: Union[str, Any] ) -> int: import faiss __UpperCAmelCase : Any = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__lowerCamelCase ) as tmp_file: index.save(tmp_file.name ) __UpperCAmelCase : List[str] = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) __UpperCAmelCase : Tuple = np.zeros(5 , dtype=np.floataa ) __UpperCAmelCase : Tuple = 1 __UpperCAmelCase , __UpperCAmelCase : List[Any] = index.search(__lowerCamelCase ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def _UpperCamelCase ( snake_case__ ) -> Optional[Any]: import faiss __UpperCAmelCase : Optional[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5, dtype=np.floataa ) ) __UpperCAmelCase : Optional[Any] = "index.faiss" __UpperCAmelCase : Optional[int] = f'''mock://{index_name}''' index.save(snake_case__, storage_options=mockfs.storage_options ) __UpperCAmelCase : Dict = FaissIndex.load(snake_case__, storage_options=mockfs.storage_options ) __UpperCAmelCase : str = np.zeros(5, dtype=np.floataa ) __UpperCAmelCase : Any = 1 __UpperCAmelCase , __UpperCAmelCase : List[str] = index.search(snake_case__ ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class _snake_case ( _lowercase ): def _lowerCamelCase ( self: str ) -> Union[str, Any]: from elasticsearch import Elasticsearch with patch("elasticsearch.Elasticsearch.search" ) as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk" ) as mocked_bulk: __UpperCAmelCase : Optional[Any] = Elasticsearch() __UpperCAmelCase : Dict = {"acknowledged": True} __UpperCAmelCase : Any = ElasticSearchIndex(es_client=__lowerCamelCase ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(["foo", "bar", "foobar"] ) # single query __UpperCAmelCase : Dict = "foo" __UpperCAmelCase : Optional[Any] = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} __UpperCAmelCase , __UpperCAmelCase : Optional[int] = index.search(__lowerCamelCase ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout __UpperCAmelCase : int = "foo" __UpperCAmelCase : Optional[Any] = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = index.search(__lowerCamelCase , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries __UpperCAmelCase : int = ["foo", "bar", "foobar"] __UpperCAmelCase : Union[str, Any] = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} __UpperCAmelCase , __UpperCAmelCase : List[Any] = index.search_batch(__lowerCamelCase ) __UpperCAmelCase : Tuple = [scores[0] for scores in total_scores] __UpperCAmelCase : Optional[int] = [indices[0] for indices in total_indices] self.assertGreater(np.min(__lowerCamelCase ) , 0 ) self.assertListEqual([1, 1, 1] , __lowerCamelCase ) # batched queries with timeout __UpperCAmelCase : str = ["foo", "bar", "foobar"] __UpperCAmelCase : Tuple = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = index.search_batch(__lowerCamelCase , request_timeout=30 ) __UpperCAmelCase : Union[str, Any] = [scores[0] for scores in total_scores] __UpperCAmelCase : List[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(__lowerCamelCase ) , 0 ) self.assertListEqual([1, 1, 1] , __lowerCamelCase )
342
import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _snake_case : def __init__( self: Tuple , __lowerCamelCase: Optional[int] , __lowerCamelCase: Optional[Any]=13 , __lowerCamelCase: Optional[int]=32 , __lowerCamelCase: List[str]=3 , __lowerCamelCase: Dict=4 , __lowerCamelCase: Optional[Any]=[10, 20, 30, 40] , __lowerCamelCase: int=[2, 2, 3, 2] , __lowerCamelCase: Union[str, Any]=True , __lowerCamelCase: Union[str, Any]=True , __lowerCamelCase: Tuple=37 , __lowerCamelCase: Tuple="gelu" , __lowerCamelCase: List[Any]=10 , __lowerCamelCase: Optional[int]=0.02 , __lowerCamelCase: Optional[Any]=["stage2", "stage3", "stage4"] , __lowerCamelCase: Optional[int]=[2, 3, 4] , __lowerCamelCase: int=None , ) -> List[str]: __UpperCAmelCase : Union[str, Any] = parent __UpperCAmelCase : List[str] = batch_size __UpperCAmelCase : Optional[int] = image_size __UpperCAmelCase : List[str] = num_channels __UpperCAmelCase : Union[str, Any] = num_stages __UpperCAmelCase : List[str] = hidden_sizes __UpperCAmelCase : Any = depths __UpperCAmelCase : Optional[int] = is_training __UpperCAmelCase : List[Any] = use_labels __UpperCAmelCase : Optional[int] = intermediate_size __UpperCAmelCase : Optional[Any] = hidden_act __UpperCAmelCase : Union[str, Any] = num_labels __UpperCAmelCase : Any = initializer_range __UpperCAmelCase : List[str] = out_features __UpperCAmelCase : Tuple = out_indices __UpperCAmelCase : List[Any] = scope def _lowerCamelCase ( self: List[Any] ) -> Optional[int]: __UpperCAmelCase : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __UpperCAmelCase : List[str] = None if self.use_labels: __UpperCAmelCase : List[Any] = ids_tensor([self.batch_size] , self.num_labels ) __UpperCAmelCase : Optional[Any] = self.get_config() return config, pixel_values, labels def _lowerCamelCase ( self: Tuple ) -> List[Any]: return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=__lowerCamelCase , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def _lowerCamelCase ( self: List[Any] , __lowerCamelCase: int , __lowerCamelCase: int , __lowerCamelCase: Optional[int] ) -> Union[str, Any]: __UpperCAmelCase : Optional[Any] = ConvNextVaModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() __UpperCAmelCase : List[str] = model(__lowerCamelCase ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def _lowerCamelCase ( self: Optional[Any] , __lowerCamelCase: Optional[Any] , __lowerCamelCase: Any , __lowerCamelCase: Tuple ) -> Tuple: __UpperCAmelCase : Union[str, Any] = ConvNextVaForImageClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() __UpperCAmelCase : Optional[int] = model(__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowerCamelCase ( self: int , __lowerCamelCase: Any , __lowerCamelCase: Optional[int] , __lowerCamelCase: Optional[Any] ) -> Optional[int]: __UpperCAmelCase : List[str] = ConvNextVaBackbone(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() __UpperCAmelCase : Any = model(__lowerCamelCase ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # 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 __UpperCAmelCase : List[Any] = None __UpperCAmelCase : List[str] = ConvNextVaBackbone(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() __UpperCAmelCase : Any = model(__lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def _lowerCamelCase ( self: int ) -> List[str]: __UpperCAmelCase : int = self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = config_and_inputs __UpperCAmelCase : str = {"pixel_values": pixel_values} return config, inputs_dict def _lowerCamelCase ( self: List[Any] ) -> List[Any]: __UpperCAmelCase : Optional[int] = self.prepare_config_and_inputs() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Tuple = config_and_inputs __UpperCAmelCase : Dict = {"pixel_values": pixel_values, "labels": labels} return config, inputs_dict @require_torch class _snake_case ( _lowercase , _lowercase , unittest.TestCase ): lowerCamelCase__: Dict = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) lowerCamelCase__: str = ( {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification} if is_torch_available() else {} ) lowerCamelCase__: Tuple = False lowerCamelCase__: int = False lowerCamelCase__: Dict = False lowerCamelCase__: int = False lowerCamelCase__: Any = False def _lowerCamelCase ( self: Union[str, Any] ) -> Union[str, Any]: __UpperCAmelCase : Union[str, Any] = ConvNextVaModelTester(self ) __UpperCAmelCase : str = ConfigTester(self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase , hidden_size=37 ) def _lowerCamelCase ( self: Dict ) -> Tuple: 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 _lowerCamelCase ( self: List[Any] ) -> int: return @unittest.skip(reason="ConvNextV2 does not use inputs_embeds" ) def _lowerCamelCase ( self: Optional[Any] ) -> Optional[int]: pass @unittest.skip(reason="ConvNextV2 does not support input and output embeddings" ) def _lowerCamelCase ( self: Any ) -> Any: pass @unittest.skip(reason="ConvNextV2 does not use feedforward chunking" ) def _lowerCamelCase ( self: str ) -> Optional[Any]: pass def _lowerCamelCase ( self: List[Any] ) -> int: if not self.model_tester.is_training: return for model_class in self.all_model_classes: __UpperCAmelCase , __UpperCAmelCase : str = self.model_tester.prepare_config_and_inputs_with_labels() __UpperCAmelCase : Optional[Any] = True if model_class.__name__ in [ *get_values(__lowerCamelCase ), *get_values(__lowerCamelCase ), ]: continue __UpperCAmelCase : Optional[Any] = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.train() __UpperCAmelCase : Any = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) __UpperCAmelCase : Any = model(**__lowerCamelCase ).loss loss.backward() def _lowerCamelCase ( self: Optional[int] ) -> Dict: if not self.model_tester.is_training: return for model_class in self.all_model_classes: __UpperCAmelCase , __UpperCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs_with_labels() __UpperCAmelCase : List[str] = False __UpperCAmelCase : int = True if ( model_class.__name__ in [*get_values(__lowerCamelCase ), *get_values(__lowerCamelCase )] or not model_class.supports_gradient_checkpointing ): continue __UpperCAmelCase : int = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.gradient_checkpointing_enable() model.train() __UpperCAmelCase : List[Any] = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase , return_labels=__lowerCamelCase ) __UpperCAmelCase : Any = model(**__lowerCamelCase ).loss loss.backward() def _lowerCamelCase ( self: List[str] ) -> Dict: __UpperCAmelCase , __UpperCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase : str = model_class(__lowerCamelCase ) __UpperCAmelCase : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCAmelCase : List[Any] = [*signature.parameters.keys()] __UpperCAmelCase : int = ["pixel_values"] self.assertListEqual(arg_names[:1] , __lowerCamelCase ) def _lowerCamelCase ( self: str ) -> List[Any]: __UpperCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def _lowerCamelCase ( self: Union[str, Any] ) -> Dict: def check_hidden_states_output(__lowerCamelCase: Any , __lowerCamelCase: Tuple , __lowerCamelCase: str ): __UpperCAmelCase : Any = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() with torch.no_grad(): __UpperCAmelCase : Tuple = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) __UpperCAmelCase : List[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __UpperCAmelCase : Optional[int] = self.model_tester.num_stages self.assertEqual(len(__lowerCamelCase ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) __UpperCAmelCase , __UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase : Optional[int] = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCAmelCase : Any = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def _lowerCamelCase ( self: Optional[Any] ) -> Optional[int]: __UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase ) @slow def _lowerCamelCase ( self: Dict ) -> List[Any]: for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCAmelCase : Optional[int] = ConvNextVaModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def _UpperCamelCase ( ) -> List[Any]: __UpperCAmelCase : List[str] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class _snake_case ( unittest.TestCase ): @cached_property def _lowerCamelCase ( self: Optional[int] ) -> Dict: return AutoImageProcessor.from_pretrained("facebook/convnextv2-tiny-1k-224" ) if is_vision_available() else None @slow def _lowerCamelCase ( self: List[Any] ) -> Tuple: __UpperCAmelCase : List[Any] = ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224" ).to(__lowerCamelCase ) __UpperCAmelCase : List[str] = self.default_image_processor __UpperCAmelCase : Optional[Any] = prepare_img() __UpperCAmelCase : int = preprocessor(images=__lowerCamelCase , return_tensors="pt" ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): __UpperCAmelCase : str = model(**__lowerCamelCase ) # verify the logits __UpperCAmelCase : Dict = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) __UpperCAmelCase : str = torch.tensor([0.99_96, 0.19_66, -0.43_86] ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCamelCase , atol=1e-4 ) )
342
1
"""simple docstring""" from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def a_ ( lowerCamelCase ): return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) lowerCAmelCase__ : List[Any] = '\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n' class snake_case ( __UpperCAmelCase ): """simple docstring""" @staticmethod def __lowerCAmelCase ( lowerCamelCase__ : ArgumentParser ): UpperCAmelCase__ = parser.add_parser( 'convert' ,help='CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.' ,) train_parser.add_argument('--model_type' ,type=lowerCamelCase__ ,required=lowerCamelCase__ ,help='Model\'s type.' ) train_parser.add_argument( '--tf_checkpoint' ,type=lowerCamelCase__ ,required=lowerCamelCase__ ,help='TensorFlow checkpoint path or folder.' ) train_parser.add_argument( '--pytorch_dump_output' ,type=lowerCamelCase__ ,required=lowerCamelCase__ ,help='Path to the PyTorch saved model output.' ) train_parser.add_argument('--config' ,type=lowerCamelCase__ ,default='' ,help='Configuration file path or folder.' ) train_parser.add_argument( '--finetuning_task_name' ,type=lowerCamelCase__ ,default=lowerCamelCase__ ,help='Optional fine-tuning task name if the TF model was a finetuned model.' ,) train_parser.set_defaults(func=lowerCamelCase__ ) def __init__( self : List[Any] ,lowerCamelCase__ : str ,lowerCamelCase__ : str ,lowerCamelCase__ : str ,lowerCamelCase__ : str ,lowerCamelCase__ : str ,*lowerCamelCase__ : Any ,): UpperCAmelCase__ = logging.get_logger('transformers-cli/converting' ) self._logger.info(f'''Loading model {model_type}''' ) UpperCAmelCase__ = model_type UpperCAmelCase__ = tf_checkpoint UpperCAmelCase__ = pytorch_dump_output UpperCAmelCase__ = config UpperCAmelCase__ = finetuning_task_name def __lowerCAmelCase ( self : str ): if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCamelCase__ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint ,self._config ,self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCamelCase__ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint ,self._config ,self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCamelCase__ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint ,self._config ,self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(lowerCamelCase__ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint ,self._config ,self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint ,self._config ,self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCamelCase__ ) if "ckpt" in self._tf_checkpoint.lower(): UpperCAmelCase__ = self._tf_checkpoint UpperCAmelCase__ = '' else: UpperCAmelCase__ = self._tf_checkpoint UpperCAmelCase__ = '' convert_transfo_xl_checkpoint_to_pytorch( lowerCamelCase__ ,self._config ,self._pytorch_dump_output ,lowerCamelCase__ ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCamelCase__ ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint ,self._config ,self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCamelCase__ ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint ,self._config ,self._pytorch_dump_output ,self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint ,self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint ,self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint ,self._config ,self._pytorch_dump_output ) else: raise ValueError( '--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]' )
98
"""simple docstring""" import numpy as np def lowercase ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : float ) -> np.ndarray: return np.where(vector > 0 , lowerCAmelCase__ , (alpha * (np.exp(lowerCAmelCase__ ) - 1)) ) if __name__ == "__main__": import doctest doctest.testmod()
45
0
"""simple docstring""" from ....utils import logging _lowerCAmelCase : List[str] = logging.get_logger(__name__) class A_ ( _a ): def __init__( self: Union[str, Any] ,__lowerCAmelCase: List[Any] ,__lowerCAmelCase: List[str]=None ,__lowerCAmelCase: Optional[Any]=2_048 ): '''simple docstring''' _lowerCamelCase : str = config.__dict__ _lowerCamelCase : Any = modal_hidden_size if num_labels: _lowerCamelCase : Optional[int] = num_labels
340
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCAmelCase : Optional[Any] = { '''configuration_mctct''': ['''MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MCTCTConfig'''], '''feature_extraction_mctct''': ['''MCTCTFeatureExtractor'''], '''processing_mctct''': ['''MCTCTProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Dict = [ '''MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MCTCTForCTC''', '''MCTCTModel''', '''MCTCTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig from .feature_extraction_mctct import MCTCTFeatureExtractor from .processing_mctct import MCTCTProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel else: import sys _lowerCAmelCase : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
340
1
'''simple docstring''' import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy _SCREAMING_SNAKE_CASE : Optional[Any] = logging.getLogger(__name__) def UpperCamelCase_( snake_case : torch.nn.Module , snake_case : BnbQuantizationConfig , snake_case : Union[str, os.PathLike] = None , snake_case : Optional[Dict[str, Union[int, str, torch.device]]] = None , snake_case : Optional[List[str]] = None , snake_case : Optional[Dict[Union[int, str], Union[int, str]]] = None , snake_case : Optional[Union[str, os.PathLike]] = None , snake_case : bool = False , ): '''simple docstring''' snake_case_ = bnb_quantization_config.load_in_abit snake_case_ = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( "You have a version of `bitsandbytes` that is not compatible with 8bit quantization," " make sure you have the latest version of `bitsandbytes` installed." ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( "You have a version of `bitsandbytes` that is not compatible with 4bit quantization," "make sure you have the latest version of `bitsandbytes` installed." ) snake_case_ = [] # custom device map if isinstance(snake_case , snake_case ) and len(device_map.keys() ) > 1: snake_case_ = [key for key, value in device_map.items() if value in ["disk", "cpu"]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: snake_case_ = get_keys_to_not_convert(snake_case ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(snake_case ) snake_case_ = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: snake_case_ = [] snake_case_ = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(snake_case ) # compatibility with peft snake_case_ = load_in_abit snake_case_ = load_in_abit snake_case_ = get_parameter_device(snake_case ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( "It is not recommended to quantize a loaded model. " "The model should be instantiated under the `init_empty_weights` context manager." ) snake_case_ = replace_with_bnb_layers(snake_case , snake_case , modules_to_not_convert=snake_case ) # convert param to the right dtype snake_case_ = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: snake_case_ = name.replace(".weight" , "" ).replace(".bias" , "" ) snake_case_ = getattr(snake_case , snake_case , snake_case ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(snake_case ): param.to(snake_case ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info( f'The model device type is {model_device.type}. However, cuda is needed for quantization.' "We move the model to cuda." ) return model elif weights_location is None: raise RuntimeError( f'`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} ' ) else: with init_empty_weights(): snake_case_ = replace_with_bnb_layers( snake_case , snake_case , modules_to_not_convert=snake_case ) snake_case_ = get_quantized_model_device_map( snake_case , snake_case , snake_case , max_memory=snake_case , no_split_module_classes=snake_case , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): snake_case_ = True snake_case_ = any(x in list(device_map.values() ) for x in ["cpu", "disk"] ) load_checkpoint_in_model( snake_case , snake_case , snake_case , dtype=bnb_quantization_config.torch_dtype , offload_folder=snake_case , offload_state_dict=snake_case , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(snake_case , device_map=snake_case , offload_dir=snake_case ) def UpperCamelCase_( snake_case : Union[str, Any] , snake_case : List[str] , snake_case : Optional[Any]=None , snake_case : Any=None , snake_case : Any=None ): '''simple docstring''' if device_map is None: if torch.cuda.is_available(): snake_case_ = {"": torch.cuda.current_device()} else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info("The device_map was not initialized." "Setting device_map to `{'':torch.cuda.current_device()}`." ) if isinstance(snake_case , snake_case ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or " "'sequential'." ) snake_case_ = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) snake_case_ = {} snake_case_ = special_dtypes snake_case_ = no_split_module_classes snake_case_ = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": snake_case_ = get_balanced_memory( snake_case , low_zero=(device_map == "balanced_low_0") , max_memory=snake_case , **snake_case , ) snake_case_ = max_memory snake_case_ = infer_auto_device_map(snake_case , **snake_case ) if isinstance(snake_case , snake_case ): # check if don't have any quantized module on the cpu snake_case_ = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules snake_case_ = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( "\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n " ) else: logger.info( "Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit" ) del device_map_without_some_modules return device_map def UpperCamelCase_( snake_case : Tuple , snake_case : str , snake_case : int=None , snake_case : Optional[Any]=None ): '''simple docstring''' if modules_to_not_convert is None: snake_case_ = [] snake_case_ , snake_case_ = _replace_with_bnb_layers( snake_case , snake_case , snake_case , snake_case ) if not has_been_replaced: logger.warning( "You are loading your model in 8bit or 4bit but no linear modules were found in your model." " this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers." " Please double check your model architecture, or submit an issue on github if you think this is" " a bug." ) return model def UpperCamelCase_( snake_case : List[Any] , snake_case : Optional[int] , snake_case : int=None , snake_case : Any=None , ): '''simple docstring''' snake_case_ = False for name, module in model.named_children(): if current_key_name is None: snake_case_ = [] current_key_name.append(snake_case ) if isinstance(snake_case , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` snake_case_ = ".".join(snake_case ) snake_case_ = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: snake_case_ = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: snake_case_ = bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=snake_case , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: snake_case_ = bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("load_in_8bit and load_in_4bit can't be both False" ) snake_case_ = module.weight.data if module.bias is not None: snake_case_ = module.bias.data bnb_module.requires_grad_(snake_case ) setattr(snake_case , snake_case , snake_case ) snake_case_ = True if len(list(module.children() ) ) > 0: snake_case_ , snake_case_ = _replace_with_bnb_layers( snake_case , snake_case , snake_case , snake_case ) snake_case_ = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def UpperCamelCase_( snake_case : Optional[Any] ): '''simple docstring''' with init_empty_weights(): snake_case_ = deepcopy(snake_case ) # this has 0 cost since it is done inside `init_empty_weights` context manager` snake_case_ = find_tied_parameters(snake_case ) # For compatibility with Accelerate < 0.18 if isinstance(snake_case , snake_case ): snake_case_ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: snake_case_ = sum(snake_case , [] ) snake_case_ = len(snake_case ) > 0 # Check if it is a base model snake_case_ = False if hasattr(snake_case , "base_model_prefix" ): snake_case_ = not hasattr(snake_case , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head snake_case_ = list(model.named_children() ) snake_case_ = [list_modules[-1][0]] # add last module together with tied weights snake_case_ = set(snake_case ) - set(snake_case ) snake_case_ = list(set(snake_case ) ) + list(snake_case ) # remove ".weight" from the keys snake_case_ = [".weight", ".bias"] snake_case_ = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: snake_case_ = name.replace(snake_case , "" ) filtered_module_names.append(snake_case ) return filtered_module_names def UpperCamelCase_( snake_case : List[Any] ): '''simple docstring''' for m in model.modules(): if isinstance(snake_case , bnb.nn.Linearabit ): return True return False def UpperCamelCase_( snake_case : nn.Module ): '''simple docstring''' return next(parameter.parameters() ).device def UpperCamelCase_( snake_case : int , snake_case : Optional[Any] , snake_case : Union[str, Any] , snake_case : Optional[int] , snake_case : Dict , snake_case : int , snake_case : int ): '''simple docstring''' if fpaa_statistics is None: set_module_tensor_to_device(snake_case , snake_case , 0 , dtype=snake_case , value=snake_case ) snake_case_ = param_name snake_case_ = model if "." in tensor_name: snake_case_ = tensor_name.split("." ) for split in splits[:-1]: snake_case_ = getattr(snake_case , snake_case ) if new_module is None: raise ValueError(f'{module} has no attribute {split}.' ) snake_case_ = new_module snake_case_ = splits[-1] # offload weights snake_case_ = False offload_weight(module._parameters[tensor_name] , snake_case , snake_case , index=snake_case ) if hasattr(module._parameters[tensor_name] , "SCB" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("weight" , "SCB" ) , snake_case , index=snake_case , ) else: offload_weight(snake_case , snake_case , snake_case , index=snake_case ) offload_weight(snake_case , param_name.replace("weight" , "SCB" ) , snake_case , index=snake_case ) set_module_tensor_to_device(snake_case , snake_case , "meta" , dtype=snake_case , value=torch.empty(*param.size() ) )
85
'''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 _snake_case : def __init__( self , a__ = None , a__ = [] ) -> List[str]: '''simple docstring''' snake_case_ = 0 snake_case_ = choices snake_case_ = prompt if sys.platform == "win32": snake_case_ = "*" else: snake_case_ = "➔ " def lowerCAmelCase__ ( self , a__ , a__ = "" ) -> int: '''simple docstring''' if sys.platform != "win32": writeColor(self.choices[index] , 32 , a__ ) else: forceWrite(self.choices[index] , a__ ) def lowerCAmelCase__ ( self , a__ ) -> Tuple: '''simple docstring''' if index == self.position: forceWrite(F' {self.arrow_char} ' ) self.write_choice(a__ ) else: forceWrite(F' {self.choices[index]}' ) reset_cursor() def lowerCAmelCase__ ( self , a__ , a__ = 1 ) -> List[str]: '''simple docstring''' snake_case_ = 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 lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' self.move_direction(Direction.UP ) @input.mark(KEYMAP["down"] ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' self.move_direction(Direction.DOWN ) @input.mark(KEYMAP["newline"] ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' move_cursor(len(self.choices ) - self.position , "DOWN" ) return self.position @input.mark(KEYMAP["interrupt"] ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' move_cursor(len(self.choices ) - self.position , "DOWN" ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(a__ )] for number in range(10 )] ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = int(chr(self.current_selection ) ) snake_case_ = 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 lowerCAmelCase__ ( self , a__ = 0 ) -> List[str]: '''simple docstring''' 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" ) snake_case_ = 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: snake_case_ = int(builtins.input() ) except ValueError: snake_case_ = default_choice else: snake_case_ = 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
85
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCamelCase : List[str] = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : str = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Tuple = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : List[Any] = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Any = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys __UpperCamelCase : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
347
def __A ( __lowerCamelCase ) -> int: if not numbers: return 0 if not isinstance(__lowerCamelCase , (list, tuple) ) or not all( isinstance(__lowerCamelCase , __lowerCamelCase ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) a = a = a = numbers[0] for i in range(1 , len(__lowerCamelCase ) ): # update the maximum and minimum subarray products a = numbers[i] if number < 0: a , a = min_till_now, max_till_now a = max(__lowerCamelCase , max_till_now * number ) a = min(__lowerCamelCase , min_till_now * number ) # update the maximum product found till now a = max(__lowerCamelCase , __lowerCamelCase ) return max_prod
347
1
import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __lowerCAmelCase : def __init__( self , _snake_case , _snake_case=2 , _snake_case=3 , _snake_case=4 , _snake_case=2 , _snake_case=7 , _snake_case=True , _snake_case=True , _snake_case=True , _snake_case=True , _snake_case=99 , _snake_case=36 , _snake_case=3 , _snake_case=4 , _snake_case=37 , _snake_case="gelu" , _snake_case=0.1 , _snake_case=0.1 , _snake_case=512 , _snake_case=16 , _snake_case=2 , _snake_case=0.02 , _snake_case=6 , _snake_case=6 , _snake_case=3 , _snake_case=4 , _snake_case=None , _snake_case=1000 , ): """simple docstring""" _lowerCAmelCase = parent _lowerCAmelCase = batch_size _lowerCAmelCase = num_channels _lowerCAmelCase = image_size _lowerCAmelCase = patch_size _lowerCAmelCase = text_seq_length _lowerCAmelCase = is_training _lowerCAmelCase = use_input_mask _lowerCAmelCase = use_token_type_ids _lowerCAmelCase = use_labels _lowerCAmelCase = vocab_size _lowerCAmelCase = hidden_size _lowerCAmelCase = num_hidden_layers _lowerCAmelCase = num_attention_heads _lowerCAmelCase = intermediate_size _lowerCAmelCase = hidden_act _lowerCAmelCase = hidden_dropout_prob _lowerCAmelCase = attention_probs_dropout_prob _lowerCAmelCase = max_position_embeddings _lowerCAmelCase = type_vocab_size _lowerCAmelCase = type_sequence_label_size _lowerCAmelCase = initializer_range _lowerCAmelCase = coordinate_size _lowerCAmelCase = shape_size _lowerCAmelCase = num_labels _lowerCAmelCase = num_choices _lowerCAmelCase = scope _lowerCAmelCase = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) _lowerCAmelCase = text_seq_length _lowerCAmelCase = (image_size // patch_size) ** 2 + 1 _lowerCAmelCase = self.text_seq_length + self.image_seq_length def snake_case ( self ): """simple docstring""" _lowerCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) _lowerCAmelCase = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: _lowerCAmelCase = bbox[i, j, 3] _lowerCAmelCase = bbox[i, j, 1] _lowerCAmelCase = t if bbox[i, j, 2] < bbox[i, j, 0]: _lowerCAmelCase = bbox[i, j, 2] _lowerCAmelCase = bbox[i, j, 0] _lowerCAmelCase = t _lowerCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _lowerCAmelCase = None if self.use_input_mask: _lowerCAmelCase = random_attention_mask([self.batch_size, self.text_seq_length] ) _lowerCAmelCase = None if self.use_token_type_ids: _lowerCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) _lowerCAmelCase = None _lowerCAmelCase = None if self.use_labels: _lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) _lowerCAmelCase = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def snake_case ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ): """simple docstring""" _lowerCAmelCase = LayoutLMvaModel(config=_snake_case ) model.to(_snake_case ) model.eval() # text + image _lowerCAmelCase = model(_snake_case , pixel_values=_snake_case ) _lowerCAmelCase = model( _snake_case , bbox=_snake_case , pixel_values=_snake_case , attention_mask=_snake_case , token_type_ids=_snake_case ) _lowerCAmelCase = model(_snake_case , bbox=_snake_case , pixel_values=_snake_case , token_type_ids=_snake_case ) _lowerCAmelCase = model(_snake_case , bbox=_snake_case , pixel_values=_snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only _lowerCAmelCase = model(_snake_case ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only _lowerCAmelCase = model(pixel_values=_snake_case ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def snake_case ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ): """simple docstring""" _lowerCAmelCase = self.num_labels _lowerCAmelCase = LayoutLMvaForSequenceClassification(_snake_case ) model.to(_snake_case ) model.eval() _lowerCAmelCase = model( _snake_case , bbox=_snake_case , pixel_values=_snake_case , attention_mask=_snake_case , token_type_ids=_snake_case , labels=_snake_case , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def snake_case ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ): """simple docstring""" _lowerCAmelCase = self.num_labels _lowerCAmelCase = LayoutLMvaForTokenClassification(config=_snake_case ) model.to(_snake_case ) model.eval() _lowerCAmelCase = model( _snake_case , bbox=_snake_case , pixel_values=_snake_case , attention_mask=_snake_case , token_type_ids=_snake_case , labels=_snake_case , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def snake_case ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ): """simple docstring""" _lowerCAmelCase = LayoutLMvaForQuestionAnswering(config=_snake_case ) model.to(_snake_case ) model.eval() _lowerCAmelCase = model( _snake_case , bbox=_snake_case , pixel_values=_snake_case , attention_mask=_snake_case , token_type_ids=_snake_case , start_positions=_snake_case , end_positions=_snake_case , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def snake_case ( self ): """simple docstring""" _lowerCAmelCase = self.prepare_config_and_inputs() ( ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ) = config_and_inputs _lowerCAmelCase = { """input_ids""": input_ids, """bbox""": bbox, """pixel_values""": pixel_values, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class __lowerCAmelCase ( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) __lowerCamelCase = ( {'''document-question-answering''': LayoutLMvaForQuestionAnswering, '''feature-extraction''': LayoutLMvaModel} if is_torch_available() else {} ) def snake_case ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ): """simple docstring""" return True def snake_case ( self ): """simple docstring""" _lowerCAmelCase = LayoutLMvaModelTester(self ) _lowerCAmelCase = ConfigTester(self , config_class=_snake_case , hidden_size=37 ) def snake_case ( self , _snake_case , _snake_case , _snake_case=False ): """simple docstring""" _lowerCAmelCase = copy.deepcopy(_snake_case ) if model_class in get_values(_snake_case ): _lowerCAmelCase = { k: v.unsqueeze(1 ).expand(-1 , self.model_tester.num_choices , -1 ).contiguous() if isinstance(_snake_case , torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(_snake_case ): _lowerCAmelCase = torch.ones(self.model_tester.batch_size , dtype=torch.long , device=_snake_case ) elif model_class in get_values(_snake_case ): _lowerCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_snake_case ) _lowerCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_snake_case ) elif model_class in [ *get_values(_snake_case ), ]: _lowerCAmelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_snake_case ) elif model_class in [ *get_values(_snake_case ), ]: _lowerCAmelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=_snake_case , ) return inputs_dict def snake_case ( self ): """simple docstring""" self.config_tester.run_common_tests() def snake_case ( self ): """simple docstring""" _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_snake_case ) def snake_case ( self ): """simple docstring""" _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _lowerCAmelCase = type self.model_tester.create_and_check_model(*_snake_case ) def snake_case ( self ): """simple docstring""" _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_snake_case ) def snake_case ( self ): """simple docstring""" _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_snake_case ) def snake_case ( self ): """simple docstring""" _lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_snake_case ) @slow def snake_case ( self ): """simple docstring""" for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCAmelCase = LayoutLMvaModel.from_pretrained(_snake_case ) self.assertIsNotNone(_snake_case ) def _UpperCAmelCase ( ): """simple docstring""" _lowerCAmelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch class __lowerCAmelCase ( unittest.TestCase ): @cached_property def snake_case ( self ): """simple docstring""" return LayoutLMvaImageProcessor(apply_ocr=_snake_case ) if is_vision_available() else None @slow def snake_case ( self ): """simple docstring""" _lowerCAmelCase = LayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base""" ).to(_snake_case ) _lowerCAmelCase = self.default_image_processor _lowerCAmelCase = prepare_img() _lowerCAmelCase = image_processor(images=_snake_case , return_tensors="""pt""" ).pixel_values.to(_snake_case ) _lowerCAmelCase = torch.tensor([[1, 2]] ) _lowerCAmelCase = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass _lowerCAmelCase = model( input_ids=input_ids.to(_snake_case ) , bbox=bbox.to(_snake_case ) , pixel_values=pixel_values.to(_snake_case ) , ) # verify the logits _lowerCAmelCase = torch.Size((1, 199, 768) ) self.assertEqual(outputs.last_hidden_state.shape , _snake_case ) _lowerCAmelCase = torch.tensor( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ).to(_snake_case ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , _snake_case , atol=1e-4 ) )
82
from argparse import ArgumentParser from . import BaseTransformersCLICommand def _UpperCAmelCase ( snake_case ): """simple docstring""" return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class __lowerCAmelCase ( lowerCamelCase__ ): @staticmethod def snake_case ( _snake_case ): """simple docstring""" _lowerCAmelCase = parser.add_parser("""download""" ) download_parser.add_argument( """--cache-dir""" , type=_snake_case , default=_snake_case , help="""Path to location to store the models""" ) download_parser.add_argument( """--force""" , action="""store_true""" , help="""Force the model to be download even if already in cache-dir""" ) download_parser.add_argument( """--trust-remote-code""" , action="""store_true""" , help="""Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you've reviewed the code as it will execute on your local machine""" , ) download_parser.add_argument("""model""" , type=_snake_case , help="""Name of the model to download""" ) download_parser.set_defaults(func=_snake_case ) def __init__( self , _snake_case , _snake_case , _snake_case , _snake_case ): """simple docstring""" _lowerCAmelCase = model _lowerCAmelCase = cache _lowerCAmelCase = force _lowerCAmelCase = trust_remote_code def snake_case ( self ): """simple docstring""" from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code )
82
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _UpperCAmelCase : int = { """configuration_maskformer""": ["""MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MaskFormerConfig"""], """configuration_maskformer_swin""": ["""MaskFormerSwinConfig"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase : str = ["""MaskFormerFeatureExtractor"""] _UpperCAmelCase : List[str] = ["""MaskFormerImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase : Union[str, Any] = [ """MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """MaskFormerForInstanceSegmentation""", """MaskFormerModel""", """MaskFormerPreTrainedModel""", ] _UpperCAmelCase : Any = [ """MaskFormerSwinBackbone""", """MaskFormerSwinModel""", """MaskFormerSwinPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig from .configuration_maskformer_swin import MaskFormerSwinConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_maskformer import MaskFormerFeatureExtractor from .image_processing_maskformer import MaskFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskformer import ( MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskFormerForInstanceSegmentation, MaskFormerModel, MaskFormerPreTrainedModel, ) from .modeling_maskformer_swin import ( MaskFormerSwinBackbone, MaskFormerSwinModel, MaskFormerSwinPreTrainedModel, ) else: import sys _UpperCAmelCase : List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
371
from __future__ import annotations import os from typing import Any import requests _UpperCAmelCase : int = """https://api.github.com""" # https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user _UpperCAmelCase : Dict = BASE_URL + """/user""" # https://github.com/settings/tokens _UpperCAmelCase : Optional[Any] = os.environ.get("""USER_TOKEN""", """""") def __lowerCamelCase ( UpperCamelCase__ ): '''simple docstring''' snake_case_ = { 'Authorization': F'''token {auth_token}''', 'Accept': 'application/vnd.github.v3+json', } return requests.get(UpperCamelCase__ , headers=UpperCamelCase__ ).json() if __name__ == "__main__": # pragma: no cover if USER_TOKEN: for key, value in fetch_github_info(USER_TOKEN).items(): print(F'''{key}: {value}''') else: raise ValueError("""'USER_TOKEN' field cannot be empty.""")
200
0
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss __magic_name__: str = pytest.mark.integration @require_faiss class snake_case__ ( _lowerCAmelCase ): def __magic_name__ ( self ) -> str: __magic_name__ : Optional[Any] = Dataset.from_dict({"""filename""": ["""my_name-train""" + """_""" + str(lowerCAmelCase__ ) for x in np.arange(30 ).tolist()]} ) return dset def __magic_name__ ( self ) -> List[str]: import faiss __magic_name__ : Dataset = self._create_dummy_dataset() __magic_name__ : Union[str, Any] = dset.map( lambda lowerCAmelCase__ , lowerCAmelCase__ : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ ) __magic_name__ : Dict = dset.add_faiss_index("""vecs""" , batch_size=1_00 , metric_type=faiss.METRIC_INNER_PRODUCT ) __magic_name__ ,__magic_name__ : str = dset.get_nearest_examples("""vecs""" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["""filename"""][0] , """my_name-train_29""" ) dset.drop_index("""vecs""" ) def __magic_name__ ( self ) -> int: import faiss __magic_name__ : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="""vecs""" , batch_size=1_00 , metric_type=faiss.METRIC_INNER_PRODUCT , ) __magic_name__ ,__magic_name__ : int = dset.get_nearest_examples("""vecs""" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["""filename"""][0] , """my_name-train_29""" ) def __magic_name__ ( self ) -> Optional[int]: import faiss __magic_name__ : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="""vecs""" , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=lowerCAmelCase__ ) as tmp_file: dset.save_faiss_index("""vecs""" , tmp_file.name ) dset.load_faiss_index("""vecs2""" , tmp_file.name ) os.unlink(tmp_file.name ) __magic_name__ ,__magic_name__ : Dict = dset.get_nearest_examples("""vecs2""" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["""filename"""][0] , """my_name-train_29""" ) def __magic_name__ ( self ) -> List[str]: __magic_name__ : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="""vecs""" ) dset.drop_index("""vecs""" ) self.assertRaises(lowerCAmelCase__ , partial(dset.get_nearest_examples , """vecs2""" , np.ones(5 , dtype=np.floataa ) ) ) def __magic_name__ ( self ) -> List[str]: from elasticsearch import Elasticsearch __magic_name__ : Dataset = self._create_dummy_dataset() with patch("""elasticsearch.Elasticsearch.search""" ) as mocked_search, patch( """elasticsearch.client.IndicesClient.create""" ) as mocked_index_create, patch("""elasticsearch.helpers.streaming_bulk""" ) as mocked_bulk: __magic_name__ : List[Any] = {"""acknowledged""": True} mocked_bulk.return_value([(True, None)] * 30 ) __magic_name__ : int = {"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 29}]}} __magic_name__ : Optional[Any] = Elasticsearch() dset.add_elasticsearch_index("""filename""" , es_client=lowerCAmelCase__ ) __magic_name__ ,__magic_name__ : Any = dset.get_nearest_examples("""filename""" , """my_name-train_29""" ) self.assertEqual(examples["""filename"""][0] , """my_name-train_29""" ) @require_faiss class snake_case__ ( _lowerCAmelCase ): def __magic_name__ ( self ) -> str: import faiss __magic_name__ : List[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query __magic_name__ : int = np.zeros(5 , dtype=np.floataa ) __magic_name__ : Dict = 1 __magic_name__ ,__magic_name__ : int = index.search(lowerCAmelCase__ ) self.assertRaises(lowerCAmelCase__ , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries __magic_name__ : Optional[Any] = np.eye(5 , dtype=np.floataa )[::-1] __magic_name__ ,__magic_name__ : int = index.search_batch(lowerCAmelCase__ ) self.assertRaises(lowerCAmelCase__ , index.search_batch , queries[0] ) __magic_name__ : str = [scores[0] for scores in total_scores] __magic_name__ : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(lowerCAmelCase__ ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , lowerCAmelCase__ ) def __magic_name__ ( self ) -> Optional[Any]: import faiss __magic_name__ : List[str] = FaissIndex(string_factory="""Flat""" ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) __magic_name__ : Dict = FaissIndex(string_factory="""LSH""" ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(lowerCAmelCase__ ): __magic_name__ : List[Any] = FaissIndex(string_factory="""Flat""" , custom_index=faiss.IndexFlat(5 ) ) def __magic_name__ ( self ) -> Optional[Any]: import faiss __magic_name__ : int = faiss.IndexFlat(5 ) __magic_name__ : Dict = FaissIndex(custom_index=lowerCAmelCase__ ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def __magic_name__ ( self ) -> str: import faiss __magic_name__ : str = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=lowerCAmelCase__ ) as tmp_file: index.save(tmp_file.name ) __magic_name__ : str = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) __magic_name__ : Union[str, Any] = np.zeros(5 , dtype=np.floataa ) __magic_name__ : Union[str, Any] = 1 __magic_name__ ,__magic_name__ : Optional[int] = index.search(lowerCAmelCase__ ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def UpperCamelCase ( _A ): """simple docstring""" import faiss __magic_name__ : Optional[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5, dtype=np.floataa ) ) __magic_name__ : List[Any] = """index.faiss""" __magic_name__ : Tuple = f'mock://{index_name}' index.save(_A, storage_options=mockfs.storage_options ) __magic_name__ : str = FaissIndex.load(_A, storage_options=mockfs.storage_options ) __magic_name__ : List[str] = np.zeros(5, dtype=np.floataa ) __magic_name__ : Union[str, Any] = 1 __magic_name__ ,__magic_name__ : List[Any] = index.search(_A ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class snake_case__ ( _lowerCAmelCase ): def __magic_name__ ( self ) -> Dict: from elasticsearch import Elasticsearch with patch("""elasticsearch.Elasticsearch.search""" ) as mocked_search, patch( """elasticsearch.client.IndicesClient.create""" ) as mocked_index_create, patch("""elasticsearch.helpers.streaming_bulk""" ) as mocked_bulk: __magic_name__ : str = Elasticsearch() __magic_name__ : List[Any] = {"""acknowledged""": True} __magic_name__ : Dict = ElasticSearchIndex(es_client=lowerCAmelCase__ ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(["""foo""", """bar""", """foobar"""] ) # single query __magic_name__ : Tuple = """foo""" __magic_name__ : Optional[int] = {"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 0}]}} __magic_name__ ,__magic_name__ : int = index.search(lowerCAmelCase__ ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout __magic_name__ : List[Any] = """foo""" __magic_name__ : Optional[int] = {"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 0}]}} __magic_name__ ,__magic_name__ : Any = index.search(lowerCAmelCase__ , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries __magic_name__ : List[Any] = ["""foo""", """bar""", """foobar"""] __magic_name__ : Optional[Any] = {"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 1}]}} __magic_name__ ,__magic_name__ : Union[str, Any] = index.search_batch(lowerCAmelCase__ ) __magic_name__ : Optional[Any] = [scores[0] for scores in total_scores] __magic_name__ : Optional[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(lowerCAmelCase__ ) , 0 ) self.assertListEqual([1, 1, 1] , lowerCAmelCase__ ) # batched queries with timeout __magic_name__ : Any = ["""foo""", """bar""", """foobar"""] __magic_name__ : List[str] = {"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 1}]}} __magic_name__ ,__magic_name__ : Optional[Any] = index.search_batch(lowerCAmelCase__ , request_timeout=30 ) __magic_name__ : Tuple = [scores[0] for scores in total_scores] __magic_name__ : int = [indices[0] for indices in total_indices] self.assertGreater(np.min(lowerCAmelCase__ ) , 0 ) self.assertListEqual([1, 1, 1] , lowerCAmelCase__ )
342
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class snake_case__ : def __init__( self , lowerCAmelCase__ = None ) -> None: if components is None: __magic_name__ : Any = [] __magic_name__ : List[str] = list(lowerCAmelCase__ ) def __len__( self ) -> int: return len(self.__components ) def __str__( self ) -> str: return "(" + ",".join(map(lowerCAmelCase__ , self.__components ) ) + ")" def __add__( self , lowerCAmelCase__ ) -> Vector: __magic_name__ : Dict = len(self ) if size == len(lowerCAmelCase__ ): __magic_name__ : str = [self.__components[i] + other.component(lowerCAmelCase__ ) for i in range(lowerCAmelCase__ )] return Vector(lowerCAmelCase__ ) else: raise Exception("""must have the same size""" ) def __sub__( self , lowerCAmelCase__ ) -> Vector: __magic_name__ : int = len(self ) if size == len(lowerCAmelCase__ ): __magic_name__ : str = [self.__components[i] - other.component(lowerCAmelCase__ ) for i in range(lowerCAmelCase__ )] return Vector(lowerCAmelCase__ ) else: # error case raise Exception("""must have the same size""" ) @overload def __mul__( self , lowerCAmelCase__ ) -> Vector: ... @overload def __mul__( self , lowerCAmelCase__ ) -> float: ... def __mul__( self , lowerCAmelCase__ ) -> float | Vector: if isinstance(lowerCAmelCase__ , (float, int) ): __magic_name__ : Optional[Any] = [c * other for c in self.__components] return Vector(lowerCAmelCase__ ) elif isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and len(self ) == len(lowerCAmelCase__ ): __magic_name__ : Optional[Any] = len(self ) __magic_name__ : List[Any] = [self.__components[i] * other.component(lowerCAmelCase__ ) for i in range(lowerCAmelCase__ )] return sum(lowerCAmelCase__ ) else: # error case raise Exception("""invalid operand!""" ) def __magic_name__ ( self ) -> Vector: return Vector(self.__components ) def __magic_name__ ( self , lowerCAmelCase__ ) -> float: if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception("""index out of range""" ) def __magic_name__ ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> None: assert -len(self.__components ) <= pos < len(self.__components ) __magic_name__ : Optional[int] = value def __magic_name__ ( self ) -> float: if len(self.__components ) == 0: raise Exception("""Vector is empty""" ) __magic_name__ : Dict = [c**2 for c in self.__components] return math.sqrt(sum(lowerCAmelCase__ ) ) def __magic_name__ ( self , lowerCAmelCase__ , lowerCAmelCase__ = False ) -> float: __magic_name__ : Optional[Any] = self * other __magic_name__ : List[str] = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def UpperCamelCase ( _A ): """simple docstring""" assert isinstance(_A, _A ) return Vector([0] * dimension ) def UpperCamelCase ( _A, _A ): """simple docstring""" assert isinstance(_A, _A ) and (isinstance(_A, _A )) __magic_name__ : Union[str, Any] = [0] * dimension __magic_name__ : Optional[int] = 1 return Vector(_A ) def UpperCamelCase ( _A, _A, _A ): """simple docstring""" assert ( isinstance(_A, _A ) and isinstance(_A, _A ) and (isinstance(_A, (int, float) )) ) return x * scalar + y def UpperCamelCase ( _A, _A, _A ): """simple docstring""" random.seed(_A ) __magic_name__ : Union[str, Any] = [random.randint(_A, _A ) for _ in range(_A )] return Vector(_A ) class snake_case__ : def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> None: __magic_name__ : Dict = matrix __magic_name__ : Tuple = w __magic_name__ : Union[str, Any] = h def __str__( self ) -> str: __magic_name__ : Dict = """""" for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , lowerCAmelCase__ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __magic_name__ : Tuple = [] for i in range(self.__height ): __magic_name__ : Tuple = [ self.__matrix[i][j] + other.component(lowerCAmelCase__ , lowerCAmelCase__ ) for j in range(self.__width ) ] matrix.append(lowerCAmelCase__ ) return Matrix(lowerCAmelCase__ , self.__width , self.__height ) else: raise Exception("""matrix must have the same dimension!""" ) def __sub__( self , lowerCAmelCase__ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __magic_name__ : Optional[Any] = [] for i in range(self.__height ): __magic_name__ : int = [ self.__matrix[i][j] - other.component(lowerCAmelCase__ , lowerCAmelCase__ ) for j in range(self.__width ) ] matrix.append(lowerCAmelCase__ ) return Matrix(lowerCAmelCase__ , self.__width , self.__height ) else: raise Exception("""matrices must have the same dimension!""" ) @overload def __mul__( self , lowerCAmelCase__ ) -> Matrix: ... @overload def __mul__( self , lowerCAmelCase__ ) -> Vector: ... def __mul__( self , lowerCAmelCase__ ) -> Vector | Matrix: if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): # matrix-vector if len(lowerCAmelCase__ ) == self.__width: __magic_name__ : Tuple = zero_vector(self.__height ) for i in range(self.__height ): __magic_name__ : Optional[int] = [ self.__matrix[i][j] * other.component(lowerCAmelCase__ ) for j in range(self.__width ) ] ans.change_component(lowerCAmelCase__ , sum(lowerCAmelCase__ ) ) return ans else: raise Exception( """vector must have the same size as the """ """number of columns of the matrix!""" ) elif isinstance(lowerCAmelCase__ , (int, float) ): # matrix-scalar __magic_name__ : Any = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(lowerCAmelCase__ , self.__width , self.__height ) return None def __magic_name__ ( self ) -> int: return self.__height def __magic_name__ ( self ) -> int: return self.__width def __magic_name__ ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> float: if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception("""change_component: indices out of bounds""" ) def __magic_name__ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> None: if 0 <= x < self.__height and 0 <= y < self.__width: __magic_name__ : List[Any] = value else: raise Exception("""change_component: indices out of bounds""" ) def __magic_name__ ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> float: if self.__height != self.__width: raise Exception("""Matrix is not square""" ) __magic_name__ : Optional[int] = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(lowerCAmelCase__ ) ): __magic_name__ : List[str] = minor[i][:y] + minor[i][y + 1 :] return Matrix(lowerCAmelCase__ , self.__width - 1 , self.__height - 1 ).determinant() def __magic_name__ ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> float: if self.__height != self.__width: raise Exception("""Matrix is not square""" ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(lowerCAmelCase__ , lowerCAmelCase__ ) else: raise Exception("""Indices out of bounds""" ) def __magic_name__ ( self ) -> float: if self.__height != self.__width: raise Exception("""Matrix is not square""" ) if self.__height < 1: raise Exception("""Matrix has no element""" ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __magic_name__ : str = [ self.__matrix[0][y] * self.cofactor(0 , lowerCAmelCase__ ) for y in range(self.__width ) ] return sum(lowerCAmelCase__ ) def UpperCamelCase ( _A ): """simple docstring""" __magic_name__ : list[list[float]] = [[0] * n for _ in range(_A )] return Matrix(_A, _A, _A ) def UpperCamelCase ( _A, _A, _A, _A ): """simple docstring""" random.seed(_A ) __magic_name__ : list[list[float]] = [ [random.randint(_A, _A ) for _ in range(_A )] for _ in range(_A ) ] return Matrix(_A, _A, _A )
342
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL __A = logging.get_logger(__name__) class lowerCamelCase__ ( __magic_name__ ): '''simple docstring''' lowerCamelCase = ['''pixel_values'''] def __init__( self , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = PILImageResampling.BILINEAR , __UpperCAmelCase = True , __UpperCAmelCase = 1 / 2_55 , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> None: super().__init__(**__UpperCAmelCase ) _lowerCAmelCase =size if size is not None else {"""shortest_edge""": 3_84} _lowerCAmelCase =get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) _lowerCAmelCase =do_resize _lowerCAmelCase =size # Default value set here for backwards compatibility where the value in config is None _lowerCAmelCase =crop_pct if crop_pct is not None else 2_24 / 2_56 _lowerCAmelCase =resample _lowerCAmelCase =do_rescale _lowerCAmelCase =rescale_factor _lowerCAmelCase =do_normalize _lowerCAmelCase =image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN _lowerCAmelCase =image_std if image_std is not None else IMAGENET_STANDARD_STD def _lowerCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = PILImageResampling.BICUBIC , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> np.ndarray: _lowerCAmelCase =get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) if "shortest_edge" not in size: raise ValueError(f'''Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}''' ) _lowerCAmelCase =size["""shortest_edge"""] if shortest_edge < 3_84: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct _lowerCAmelCase =int(shortest_edge / crop_pct ) _lowerCAmelCase =get_resize_output_image_size(__UpperCAmelCase , size=__UpperCAmelCase , default_to_square=__UpperCAmelCase ) _lowerCAmelCase =resize(image=__UpperCAmelCase , size=__UpperCAmelCase , resample=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=__UpperCAmelCase , size=(shortest_edge, shortest_edge) , data_format=__UpperCAmelCase , **__UpperCAmelCase ) else: # warping (no cropping) when evaluated at 384 or larger return resize( __UpperCAmelCase , size=(shortest_edge, shortest_edge) , resample=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def _lowerCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> List[str]: return rescale(__UpperCAmelCase , scale=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def _lowerCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> np.ndarray: return normalize(__UpperCAmelCase , mean=__UpperCAmelCase , std=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def _lowerCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = ChannelDimension.FIRST , **__UpperCAmelCase , ) -> PIL.Image.Image: _lowerCAmelCase =do_resize if do_resize is not None else self.do_resize _lowerCAmelCase =crop_pct if crop_pct is not None else self.crop_pct _lowerCAmelCase =resample if resample is not None else self.resample _lowerCAmelCase =do_rescale if do_rescale is not None else self.do_rescale _lowerCAmelCase =rescale_factor if rescale_factor is not None else self.rescale_factor _lowerCAmelCase =do_normalize if do_normalize is not None else self.do_normalize _lowerCAmelCase =image_mean if image_mean is not None else self.image_mean _lowerCAmelCase =image_std if image_std is not None else self.image_std _lowerCAmelCase =size if size is not None else self.size _lowerCAmelCase =get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) _lowerCAmelCase =make_list_of_images(__UpperCAmelCase ) if not valid_images(__UpperCAmelCase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_resize and size["shortest_edge"] < 3_84 and crop_pct is None: raise ValueError("""crop_pct must be specified if size < 384.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. _lowerCAmelCase =[to_numpy_array(__UpperCAmelCase ) for image in images] if do_resize: _lowerCAmelCase =[self.resize(image=__UpperCAmelCase , size=__UpperCAmelCase , crop_pct=__UpperCAmelCase , resample=__UpperCAmelCase ) for image in images] if do_rescale: _lowerCAmelCase =[self.rescale(image=__UpperCAmelCase , scale=__UpperCAmelCase ) for image in images] if do_normalize: _lowerCAmelCase =[self.normalize(image=__UpperCAmelCase , mean=__UpperCAmelCase , std=__UpperCAmelCase ) for image in images] _lowerCAmelCase =[to_channel_dimension_format(__UpperCAmelCase , __UpperCAmelCase ) for image in images] _lowerCAmelCase ={"""pixel_values""": images} return BatchFeature(data=__UpperCAmelCase , tensor_type=__UpperCAmelCase )
341
"""simple docstring""" def _lowerCamelCase(__UpperCamelCase ) -> Optional[Any]: _lowerCAmelCase =0 _lowerCAmelCase =len(__UpperCamelCase ) for i in range(n - 1 ): for j in range(i + 1 , __UpperCamelCase ): if arr[i] > arr[j]: num_inversions += 1 return num_inversions def _lowerCamelCase(__UpperCamelCase ) -> List[Any]: if len(__UpperCamelCase ) <= 1: return arr, 0 _lowerCAmelCase =len(__UpperCamelCase ) // 2 _lowerCAmelCase =arr[0:mid] _lowerCAmelCase =arr[mid:] _lowerCAmelCase , _lowerCAmelCase =count_inversions_recursive(__UpperCamelCase ) _lowerCAmelCase , _lowerCAmelCase =count_inversions_recursive(__UpperCamelCase ) _lowerCAmelCase , _lowerCAmelCase =_count_cross_inversions(__UpperCamelCase , __UpperCamelCase ) _lowerCAmelCase =inversion_p + inversions_q + cross_inversions return c, num_inversions def _lowerCamelCase(__UpperCamelCase , __UpperCamelCase ) -> Any: _lowerCAmelCase =[] _lowerCAmelCase =_lowerCAmelCase =_lowerCAmelCase =0 while i < len(__UpperCamelCase ) and j < len(__UpperCamelCase ): if p[i] > q[j]: # if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P) # These are all inversions. The claim emerges from the # property that P is sorted. num_inversion += len(__UpperCamelCase ) - i r.append(q[j] ) j += 1 else: r.append(p[i] ) i += 1 if i < len(__UpperCamelCase ): r.extend(p[i:] ) else: r.extend(q[j:] ) return r, num_inversion def _lowerCamelCase() -> str: _lowerCAmelCase =[10, 2, 1, 5, 5, 2, 11] # this arr has 8 inversions: # (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2) _lowerCAmelCase =count_inversions_bf(__UpperCamelCase ) _lowerCAmelCase , _lowerCAmelCase =count_inversions_recursive(__UpperCamelCase ) assert num_inversions_bf == num_inversions_recursive == 8 print("""number of inversions = """ , __UpperCamelCase ) # testing an array with zero inversion (a sorted arr_1) arr_a.sort() _lowerCAmelCase =count_inversions_bf(__UpperCamelCase ) _lowerCAmelCase , _lowerCAmelCase =count_inversions_recursive(__UpperCamelCase ) assert num_inversions_bf == num_inversions_recursive == 0 print("""number of inversions = """ , __UpperCamelCase ) # an empty list should also have zero inversions _lowerCAmelCase =[] _lowerCAmelCase =count_inversions_bf(__UpperCamelCase ) _lowerCAmelCase , _lowerCAmelCase =count_inversions_recursive(__UpperCamelCase ) assert num_inversions_bf == num_inversions_recursive == 0 print("""number of inversions = """ , __UpperCamelCase ) if __name__ == "__main__": main()
341
1
from ....utils import logging a_ = logging.get_logger(__name__) class lowercase__ ( _UpperCAmelCase ): def __init__( self , __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=2048 )-> int: '''simple docstring''' lowerCAmelCase__ = config.__dict__ lowerCAmelCase__ = modal_hidden_size if num_labels: lowerCAmelCase__ = num_labels
340
import requests from bsa import BeautifulSoup def _a ( UpperCamelCase_ : str = "AAPL" ) -> str: """simple docstring""" lowerCAmelCase__ = F"https://in.finance.yahoo.com/quote/{symbol}?s={symbol}" lowerCAmelCase__ = BeautifulSoup(requests.get(UpperCamelCase_ ).text , "html.parser" ) lowerCAmelCase__ = "My(6px) Pos(r) smartphone_Mt(6px)" return soup.find("div" , class_=class_ ).find("span" ).text if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(F"Current {symbol:<4} stock price is {stock_price(symbol):>8}")
340
1
import os def UpperCAmelCase__ ( ): lowercase :Optional[Any] = os.path.join(os.path.dirname(lowerCamelCase ), "num.txt" ) with open(lowerCamelCase ) as file_hand: return str(sum(int(lowerCamelCase ) for line in file_hand ) )[:10] if __name__ == "__main__": print(solution())
158
import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class __lowerCAmelCase ( lowerCAmelCase): def __init__( self: Any , _lowerCAmelCase: int , _lowerCAmelCase: str , _lowerCAmelCase: Union[str, Any] ): lowercase :List[str] = dataset lowercase :Optional[int] = process lowercase :Union[str, Any] = params def __len__( self: str ): return len(self.dataset ) def __getitem__( self: int , _lowerCAmelCase: Dict ): lowercase :Union[str, Any] = self.dataset[i] lowercase :Optional[int] = self.process(_lowerCAmelCase , **self.params ) return processed class __lowerCAmelCase ( lowerCAmelCase): def __init__( self: int , _lowerCAmelCase: Tuple , _lowerCAmelCase: Union[str, Any] , _lowerCAmelCase: int , _lowerCAmelCase: Optional[int]=None ): lowercase :Optional[Any] = loader lowercase :int = infer lowercase :Dict = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether lowercase :Union[str, Any] = None lowercase :Any = loader_batch_size # Internal bookkeeping lowercase :Optional[Any] = None lowercase :Dict = None def __len__( self: Tuple ): return len(self.loader ) def __iter__( self: List[str] ): lowercase :Dict = iter(self.loader ) return self def SCREAMING_SNAKE_CASE ( self: Union[str, Any] ): if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice lowercase :Optional[int] = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) lowercase :str = {} for k, element in self._loader_batch_data.items(): if isinstance(_lowerCAmelCase , _lowerCAmelCase ): # Convert ModelOutput to tuple first lowercase :Dict = element.to_tuple() if isinstance(element[0] , torch.Tensor ): lowercase :int = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): lowercase :List[str] = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(_lowerCAmelCase , _lowerCAmelCase ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): lowercase :Union[str, Any] = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): lowercase :List[Any] = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around lowercase :Optional[int] = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers lowercase :Optional[Any] = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers lowercase :Any = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. lowercase :List[Any] = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 lowercase :List[Any] = self._loader_batch_data.__class__(_lowerCAmelCase ) self._loader_batch_index += 1 return result def SCREAMING_SNAKE_CASE ( self: Optional[Any] ): if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch lowercase :Tuple = next(self.iterator ) lowercase :Dict = self.infer(_lowerCAmelCase , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(_lowerCAmelCase , torch.Tensor ): lowercase :List[str] = processed else: lowercase :Tuple = list(processed.keys() )[0] lowercase :Optional[Any] = processed[key] if isinstance(_lowerCAmelCase , _lowerCAmelCase ): lowercase :Optional[int] = len(_lowerCAmelCase ) else: lowercase :Dict = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. lowercase :Tuple = observed_batch_size # Setting internal index to unwrap the batch lowercase :int = processed lowercase :Optional[Any] = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class __lowerCAmelCase ( lowerCAmelCase): def __init__( self: Union[str, Any] , _lowerCAmelCase: Tuple , _lowerCAmelCase: str , _lowerCAmelCase: str , _lowerCAmelCase: Optional[Any]=None ): super().__init__(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) def __iter__( self: Tuple ): lowercase :List[str] = iter(self.loader ) lowercase :str = None return self def SCREAMING_SNAKE_CASE ( self: Optional[Any] ): if self.subiterator is None: lowercase :List[Any] = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item lowercase :str = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators lowercase :Tuple = self.infer(next(self.iterator ) , **self.params ) lowercase :Dict = next(self.subiterator ) return processed class __lowerCAmelCase ( lowerCAmelCase): def __iter__( self: str ): lowercase :List[Any] = iter(self.loader ) return self def SCREAMING_SNAKE_CASE ( self: str ): # Extremely similar to PipelineIterator in its unpacking mechanism # BUT, we have an extra required item which is the presence of `is_last` # That is because everything is flattened by `PipelineChunkIterator` we # need to keep track of how to regroup here in the original `process` # boundaries so that `process` and `postprocess` see the same data. # This iterator accumulates items (possibly while unbatching) until it # its a `is_last` and then just passes it on to the caller. lowercase :str = False lowercase :int = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: lowercase :str = self.loader_batch_item() lowercase :int = item.pop("is_last" ) accumulator.append(_lowerCAmelCase ) if is_last: return accumulator while not is_last: lowercase :str = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(_lowerCAmelCase , torch.Tensor ): lowercase :Tuple = processed else: lowercase :Union[str, Any] = list(processed.keys() )[0] lowercase :Any = processed[key] if isinstance(_lowerCAmelCase , _lowerCAmelCase ): lowercase :Dict = len(_lowerCAmelCase ) else: lowercase :List[str] = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. lowercase :Union[str, Any] = observed_batch_size lowercase :str = processed lowercase :Optional[int] = 0 while self._loader_batch_index < self.loader_batch_size: lowercase :Any = self.loader_batch_item() lowercase :int = item.pop("is_last" ) accumulator.append(_lowerCAmelCase ) if is_last: return accumulator else: lowercase :Optional[Any] = processed lowercase :str = item.pop("is_last" ) accumulator.append(_lowerCAmelCase ) return accumulator class __lowerCAmelCase ( lowerCAmelCase): def __init__( self: Union[str, Any] , _lowerCAmelCase: Dataset , _lowerCAmelCase: str ): lowercase :Tuple = dataset lowercase :Dict = key def __len__( self: Any ): return len(self.dataset ) def __getitem__( self: int , _lowerCAmelCase: int ): return self.dataset[i][self.key] class __lowerCAmelCase ( lowerCAmelCase): def __init__( self: List[Any] , _lowerCAmelCase: Dataset , _lowerCAmelCase: str , _lowerCAmelCase: str ): lowercase :Union[str, Any] = dataset lowercase :Optional[int] = keya lowercase :str = keya def __len__( self: Optional[Any] ): return len(self.dataset ) def __getitem__( self: Optional[Any] , _lowerCAmelCase: int ): return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
158
1