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 from pathlib import Path import torch from bark.generation import _load_model as _bark_load_model from huggingface_hub import hf_hub_download from transformers import EncodecConfig, EncodecModel, set_seed from transformers.models.bark.configuration_bark import ( BarkCoarseConfig, BarkConfig, BarkFineConfig, BarkSemanticConfig, ) from transformers.models.bark.generation_configuration_bark import ( BarkCoarseGenerationConfig, BarkFineGenerationConfig, BarkGenerationConfig, BarkSemanticGenerationConfig, ) from transformers.models.bark.modeling_bark import BarkCoarseModel, BarkFineModel, BarkModel, BarkSemanticModel from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) set_seed(770) A_ = { '''c_attn''': '''att_proj''', '''c_proj''': '''out_proj''', '''c_fc''': '''in_proj''', '''transformer.''': '''''', '''h.''': '''layers.''', '''ln_1''': '''layernorm_1''', '''ln_2''': '''layernorm_2''', '''ln_f''': '''layernorm_final''', '''wpe''': '''position_embeds_layer''', '''wte''': '''input_embeds_layer''', } A_ = { '''text_small''': { '''repo_id''': '''suno/bark''', '''file_name''': '''text.pt''', }, '''coarse_small''': { '''repo_id''': '''suno/bark''', '''file_name''': '''coarse.pt''', }, '''fine_small''': { '''repo_id''': '''suno/bark''', '''file_name''': '''fine.pt''', }, '''text''': { '''repo_id''': '''suno/bark''', '''file_name''': '''text_2.pt''', }, '''coarse''': { '''repo_id''': '''suno/bark''', '''file_name''': '''coarse_2.pt''', }, '''fine''': { '''repo_id''': '''suno/bark''', '''file_name''': '''fine_2.pt''', }, } A_ = os.path.dirname(os.path.abspath(__file__)) A_ = os.path.join(os.path.expanduser('''~'''), '''.cache''') A_ = os.path.join(os.getenv('''XDG_CACHE_HOME''', default_cache_dir), '''suno''', '''bark_v0''') def _lowerCAmelCase ( UpperCAmelCase__ : Dict, UpperCAmelCase__ : Optional[int]=False ) ->Optional[int]: A__ : Union[str, Any] = model_type if use_small: key += "_small" return os.path.join(_lowerCAmelCase, REMOTE_MODEL_PATHS[key]["""file_name"""] ) def _lowerCAmelCase ( UpperCAmelCase__ : Union[str, Any], UpperCAmelCase__ : Dict ) ->List[str]: os.makedirs(_lowerCAmelCase, exist_ok=_lowerCAmelCase ) hf_hub_download(repo_id=_lowerCAmelCase, filename=_lowerCAmelCase, local_dir=_lowerCAmelCase ) def _lowerCAmelCase ( UpperCAmelCase__ : List[Any], UpperCAmelCase__ : int, UpperCAmelCase__ : Any=False, UpperCAmelCase__ : Any="text" ) ->int: if model_type == "text": A__ : Tuple = BarkSemanticModel A__ : Tuple = BarkSemanticConfig A__ : Optional[int] = BarkSemanticGenerationConfig elif model_type == "coarse": A__ : List[Any] = BarkCoarseModel A__ : Dict = BarkCoarseConfig A__ : Dict = BarkCoarseGenerationConfig elif model_type == "fine": A__ : List[str] = BarkFineModel A__ : Optional[Any] = BarkFineConfig A__ : Optional[Any] = BarkFineGenerationConfig else: raise NotImplementedError() A__ : Optional[int] = f'{model_type}_small' if use_small else model_type A__ : int = REMOTE_MODEL_PATHS[model_key] if not os.path.exists(_lowerCAmelCase ): logger.info(f'{model_type} model not found, downloading into `{CACHE_DIR}`.' ) _download(model_info["""repo_id"""], model_info["""file_name"""] ) A__ : Any = torch.load(_lowerCAmelCase, map_location=_lowerCAmelCase ) # this is a hack A__ : Dict = checkpoint["""model_args"""] if "input_vocab_size" not in model_args: A__ : Tuple = model_args["""vocab_size"""] A__ : str = model_args["""vocab_size"""] del model_args["vocab_size"] # convert Bark model arguments to HF Bark model arguments A__ : List[str] = model_args.pop("""n_head""" ) A__ : Dict = model_args.pop("""n_embd""" ) A__ : Union[str, Any] = model_args.pop("""n_layer""" ) A__ : List[Any] = ConfigClass(**checkpoint["""model_args"""] ) A__ : int = ModelClass(config=_lowerCAmelCase ) A__ : List[str] = GenerationConfigClass() A__ : List[str] = model_generation_config A__ : Dict = checkpoint["""model"""] # fixup checkpoint A__ : Optional[Any] = """_orig_mod.""" for k, v in list(state_dict.items() ): if k.startswith(_lowerCAmelCase ): # replace part of the key with corresponding layer name in HF implementation A__ : Dict = k[len(_lowerCAmelCase ) :] for old_layer_name in new_layer_name_dict: A__ : Optional[int] = new_k.replace(_lowerCAmelCase, new_layer_name_dict[old_layer_name] ) A__ : int = state_dict.pop(_lowerCAmelCase ) A__ : List[Any] = set(state_dict.keys() ) - set(model.state_dict().keys() ) A__ : List[Any] = {k for k in extra_keys if not k.endswith(""".attn.bias""" )} A__ : List[str] = set(model.state_dict().keys() ) - set(state_dict.keys() ) A__ : List[str] = {k for k in missing_keys if not k.endswith(""".attn.bias""" )} if len(_lowerCAmelCase ) != 0: raise ValueError(f'extra keys found: {extra_keys}' ) if len(_lowerCAmelCase ) != 0: raise ValueError(f'missing keys: {missing_keys}' ) model.load_state_dict(_lowerCAmelCase, strict=_lowerCAmelCase ) A__ : Optional[int] = model.num_parameters(exclude_embeddings=_lowerCAmelCase ) A__ : Union[str, Any] = checkpoint["""best_val_loss"""].item() logger.info(f'model loaded: {round(n_params/1e6, 1 )}M params, {round(_lowerCAmelCase, 3 )} loss' ) model.eval() model.to(_lowerCAmelCase ) del checkpoint, state_dict return model def _lowerCAmelCase ( UpperCAmelCase__ : List[Any], UpperCAmelCase__ : List[str]=False, UpperCAmelCase__ : Any="text" ) ->Union[str, Any]: if model_type not in ("text", "coarse", "fine"): raise NotImplementedError() A__ : Optional[Any] = """cpu""" # do conversion on cpu A__ : Optional[int] = _get_ckpt_path(_lowerCAmelCase, use_small=_lowerCAmelCase ) A__ : Any = _load_model(_lowerCAmelCase, _lowerCAmelCase, model_type=_lowerCAmelCase, use_small=_lowerCAmelCase ) # load bark initial model A__ : List[str] = _bark_load_model(_lowerCAmelCase, """cpu""", model_type=_lowerCAmelCase, use_small=_lowerCAmelCase ) if model_type == "text": A__ : str = bark_model["""model"""] if model.num_parameters(exclude_embeddings=_lowerCAmelCase ) != bark_model.get_num_params(): raise ValueError("""initial and new models don\'t have the same number of parameters""" ) # check if same output as the bark model A__ : str = 5 A__ : List[str] = 1_0 if model_type in ["text", "coarse"]: A__ : Any = torch.randint(2_5_6, (batch_size, sequence_length), dtype=torch.int ) A__ : Tuple = bark_model(_lowerCAmelCase )[0] A__ : Dict = model(_lowerCAmelCase ) # take last logits A__ : Dict = output_new_model_total.logits[:, [-1], :] else: A__ : Union[str, Any] = 3 A__ : Union[str, Any] = 8 A__ : int = torch.randint(2_5_6, (batch_size, sequence_length, n_codes_total), dtype=torch.int ) A__ : Optional[int] = model(_lowerCAmelCase, _lowerCAmelCase ) A__ : Optional[Any] = bark_model(_lowerCAmelCase, _lowerCAmelCase ) A__ : Optional[int] = output_new_model_total.logits # output difference should come from the difference of self-attention implementation design if output_new_model.shape != output_old_model.shape: raise ValueError("""initial and new outputs don\'t have the same shape""" ) if (output_new_model - output_old_model).abs().max().item() > 1e-3: raise ValueError("""initial and new outputs are not equal""" ) Path(_lowerCAmelCase ).mkdir(exist_ok=_lowerCAmelCase ) model.save_pretrained(_lowerCAmelCase ) def _lowerCAmelCase ( UpperCAmelCase__ : Any, UpperCAmelCase__ : Optional[Any], UpperCAmelCase__ : Dict, UpperCAmelCase__ : List[Any], UpperCAmelCase__ : List[str], UpperCAmelCase__ : List[Any], ) ->Tuple: A__ : str = os.path.join(_lowerCAmelCase, _lowerCAmelCase ) A__ : int = BarkSemanticConfig.from_pretrained(os.path.join(_lowerCAmelCase, """config.json""" ) ) A__ : Optional[Any] = BarkCoarseConfig.from_pretrained(os.path.join(_lowerCAmelCase, """config.json""" ) ) A__ : Tuple = BarkFineConfig.from_pretrained(os.path.join(_lowerCAmelCase, """config.json""" ) ) A__ : Optional[int] = EncodecConfig.from_pretrained("""facebook/encodec_24khz""" ) A__ : str = BarkSemanticModel.from_pretrained(_lowerCAmelCase ) A__ : int = BarkCoarseModel.from_pretrained(_lowerCAmelCase ) A__ : Union[str, Any] = BarkFineModel.from_pretrained(_lowerCAmelCase ) A__ : Tuple = EncodecModel.from_pretrained("""facebook/encodec_24khz""" ) A__ : Dict = BarkConfig.from_sub_model_configs( _lowerCAmelCase, _lowerCAmelCase, _lowerCAmelCase, _lowerCAmelCase ) A__ : List[str] = BarkGenerationConfig.from_sub_model_configs( semantic.generation_config, coarseAcoustic.generation_config, fineAcoustic.generation_config ) A__ : List[Any] = BarkModel(_lowerCAmelCase ) A__ : List[str] = semantic A__ : Any = coarseAcoustic A__ : Optional[Any] = fineAcoustic A__ : Optional[Any] = codec A__ : Optional[Any] = bark_generation_config Path(_lowerCAmelCase ).mkdir(exist_ok=_lowerCAmelCase ) bark.save_pretrained(_lowerCAmelCase, repo_id=_lowerCAmelCase, push_to_hub=_lowerCAmelCase ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument('''model_type''', type=str, help='''text, coarse or fine.''') parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--is_small''', action='''store_true''', help='''convert the small version instead of the large.''') A_ = parser.parse_args() load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
354
"""simple docstring""" import cva import numpy as np class __SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , snake_case : float , snake_case : int ): '''simple docstring''' if k in (0.04, 0.06): A__ : Optional[int] = k A__ : int = window_size else: raise ValueError("""invalid k value""" ) def __str__( self : List[Any] ): '''simple docstring''' return str(self.k ) def _UpperCamelCase ( self : int , snake_case : str ): '''simple docstring''' A__ : List[str] = cva.imread(snake_case , 0 ) A__ , A__ : Union[str, Any] = img.shape A__ : list[list[int]] = [] A__ : Optional[Any] = img.copy() A__ : List[str] = cva.cvtColor(snake_case , cva.COLOR_GRAY2RGB ) A__ , A__ : List[Any] = np.gradient(snake_case ) A__ : List[Any] = dx**2 A__ : Any = dy**2 A__ : Dict = dx * dy A__ : Any = 0.04 A__ : Optional[Any] = self.window_size // 2 for y in range(snake_case , h - offset ): for x in range(snake_case , w - offset ): A__ : List[str] = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() A__ : Tuple = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() A__ : Optional[int] = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() A__ : int = (wxx * wyy) - (wxy**2) A__ : Any = wxx + wyy A__ : List[str] = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 255 ) return color_img, corner_list if __name__ == "__main__": A_ = HarrisCorner(0.04, 3) A_ , A_ = edge_detect.detect('''path_to_image''') cva.imwrite('''detect.png''', color_img)
296
0
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=lowerCAmelCase__ ) class __SCREAMING_SNAKE_CASE ( lowerCAmelCase__ ): snake_case_ = field(default='automatic-speech-recognition' , metadata={'include_in_asdict_even_if_is_default': True} ) snake_case_ = Features({'audio': Audio()} ) snake_case_ = Features({'transcription': Value('string' )} ) snake_case_ = "audio" snake_case_ = "transcription" def _UpperCamelCase ( self : Any , snake_case : Any ): '''simple docstring''' if self.audio_column not in features: raise ValueError(F'Column {self.audio_column} is not present in features.' ) if not isinstance(features[self.audio_column] , _SCREAMING_SNAKE_CASE ): raise ValueError(F'Column {self.audio_column} is not an Audio type.' ) A__ : int = copy.deepcopy(self ) A__ : Any = self.input_schema.copy() A__ : Optional[Any] = features[self.audio_column] A__ : List[str] = input_schema return task_template @property def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' return {self.audio_column: "audio", self.transcription_column: "transcription"}
355
"""simple docstring""" from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING A_ = logging.get_logger(__name__) A_ = Dict[str, Any] A_ = List[Prediction] @add_end_docstrings(UpperCamelCase ) class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): def __init__( self : str , *snake_case : Tuple , **snake_case : Tuple ): '''simple docstring''' super().__init__(*snake_case , **snake_case ) if self.framework == "tf": raise ValueError(F'The {self.__class__} is only available in PyTorch.' ) requires_backends(self , """vision""" ) self.check_model_type( dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items() ) ) def _UpperCamelCase ( self : List[Any] , **snake_case : Optional[int] ): '''simple docstring''' A__ : Dict = {} if "threshold" in kwargs: A__ : int = kwargs["""threshold"""] return {}, {}, postprocess_kwargs def __call__( self : Tuple , *snake_case : Union[str, Any] , **snake_case : Union[str, Any] ): '''simple docstring''' return super().__call__(*snake_case , **snake_case ) def _UpperCamelCase ( self : str , snake_case : int ): '''simple docstring''' A__ : List[str] = load_image(snake_case ) A__ : int = torch.IntTensor([[image.height, image.width]] ) A__ : Union[str, Any] = self.image_processor(images=[image] , return_tensors="""pt""" ) if self.tokenizer is not None: A__ : str = self.tokenizer(text=inputs["""words"""] , boxes=inputs["""boxes"""] , return_tensors="""pt""" ) A__ : List[str] = target_size return inputs def _UpperCamelCase ( self : Optional[int] , snake_case : List[Any] ): '''simple docstring''' A__ : str = model_inputs.pop("""target_size""" ) A__ : Dict = self.model(**snake_case ) A__ : Optional[Any] = outputs.__class__({"""target_size""": target_size, **outputs} ) if self.tokenizer is not None: A__ : str = model_inputs["""bbox"""] return model_outputs def _UpperCamelCase ( self : Tuple , snake_case : Optional[int] , snake_case : int=0.9 ): '''simple docstring''' A__ : Any = model_outputs["""target_size"""] if self.tokenizer is not None: # This is a LayoutLMForTokenClassification variant. # The OCR got the boxes and the model classified the words. A__ , A__ : Tuple = target_size[0].tolist() def unnormalize(snake_case : Optional[int] ): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ] ) ) A__ , A__ : Optional[int] = model_outputs["""logits"""].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 ) A__ : Optional[Any] = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] A__ : List[str] = [unnormalize(snake_case ) for bbox in model_outputs["""bbox"""].squeeze(0 )] A__ : Tuple = ["""score""", """label""", """box"""] A__ : Any = [dict(zip(snake_case , snake_case ) ) for vals in zip(scores.tolist() , snake_case , snake_case ) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel A__ : Union[str, Any] = self.image_processor.post_process_object_detection(snake_case , snake_case , snake_case ) A__ : str = raw_annotations[0] A__ : str = raw_annotation["""scores"""] A__ : List[Any] = raw_annotation["""labels"""] A__ : int = raw_annotation["""boxes"""] A__ : str = scores.tolist() A__ : Any = [self.model.config.idalabel[label.item()] for label in labels] A__ : int = [self._get_bounding_box(snake_case ) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] A__ : str = ["""score""", """label""", """box"""] A__ : Dict = [ dict(zip(snake_case , snake_case ) ) for vals in zip(raw_annotation["""scores"""] , raw_annotation["""labels"""] , raw_annotation["""boxes"""] ) ] return annotation def _UpperCamelCase ( self : Union[str, Any] , snake_case : "torch.Tensor" ): '''simple docstring''' if self.framework != "pt": raise ValueError("""The ObjectDetectionPipeline is only available in PyTorch.""" ) A__ , A__ , A__ , A__ : Any = box.int().tolist() A__ : Any = { """xmin""": xmin, """ymin""": ymin, """xmax""": xmax, """ymax""": ymax, } return bbox
296
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { '''facebook/timesformer''': '''https://huggingface.co/facebook/timesformer/resolve/main/config.json''', } class __SCREAMING_SNAKE_CASE ( snake_case_ ): snake_case_ = 'timesformer' def __init__( self : Optional[Any] , snake_case : Tuple=224 , snake_case : str=16 , snake_case : int=3 , snake_case : List[Any]=8 , snake_case : Union[str, Any]=768 , snake_case : List[str]=12 , snake_case : List[Any]=12 , snake_case : Dict=3072 , snake_case : int="gelu" , snake_case : str=0.0 , snake_case : Any=0.0 , snake_case : Optional[Any]=0.02 , snake_case : Dict=1e-6 , snake_case : Tuple=True , snake_case : Dict="divided_space_time" , snake_case : Optional[int]=0 , **snake_case : Optional[Any] , ): '''simple docstring''' super().__init__(**snake_case ) A__ : List[str] = image_size A__ : Tuple = patch_size A__ : List[str] = num_channels A__ : Dict = num_frames A__ : Tuple = hidden_size A__ : Optional[Any] = num_hidden_layers A__ : Optional[Any] = num_attention_heads A__ : str = intermediate_size A__ : Dict = hidden_act A__ : List[str] = hidden_dropout_prob A__ : Dict = attention_probs_dropout_prob A__ : Optional[int] = initializer_range A__ : Any = layer_norm_eps A__ : Tuple = qkv_bias A__ : str = attention_type A__ : Optional[Any] = drop_path_rate
356
"""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 A_ = logging.get_logger(__name__) A_ = { '''microsoft/table-transformer-detection''': ( '''https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json''' ), } class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = 'table-transformer' snake_case_ = ['past_key_values'] snake_case_ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Dict , snake_case : int=True , snake_case : Dict=None , snake_case : Union[str, Any]=3 , snake_case : Dict=100 , snake_case : Tuple=6 , snake_case : Optional[int]=2048 , snake_case : int=8 , snake_case : Dict=6 , snake_case : Any=2048 , snake_case : str=8 , snake_case : Union[str, Any]=0.0 , snake_case : List[str]=0.0 , snake_case : List[str]=True , snake_case : Any="relu" , snake_case : str=256 , snake_case : int=0.1 , snake_case : Dict=0.0 , snake_case : str=0.0 , snake_case : Union[str, Any]=0.02 , snake_case : Union[str, Any]=1.0 , snake_case : Optional[Any]=False , snake_case : int="sine" , snake_case : Optional[Any]="resnet50" , snake_case : Optional[int]=True , snake_case : Any=False , snake_case : int=1 , snake_case : Tuple=5 , snake_case : Optional[int]=2 , snake_case : Tuple=1 , snake_case : Optional[Any]=1 , snake_case : Optional[Any]=5 , snake_case : Dict=2 , snake_case : Any=0.1 , **snake_case : Any , ): '''simple docstring''' 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.""" ) A__ : Optional[Any] = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(snake_case , snake_case ): A__ : Optional[int] = backbone_config.get("""model_type""" ) A__ : Optional[int] = CONFIG_MAPPING[backbone_model_type] A__ : List[str] = config_class.from_dict(snake_case ) # set timm attributes to None A__ , A__ , A__ : str = None, None, None A__ : Tuple = use_timm_backbone A__ : str = backbone_config A__ : str = num_channels A__ : List[Any] = num_queries A__ : Optional[Any] = d_model A__ : Tuple = encoder_ffn_dim A__ : Union[str, Any] = encoder_layers A__ : List[Any] = encoder_attention_heads A__ : Optional[int] = decoder_ffn_dim A__ : Any = decoder_layers A__ : int = decoder_attention_heads A__ : Any = dropout A__ : Dict = attention_dropout A__ : Dict = activation_dropout A__ : Tuple = activation_function A__ : List[str] = init_std A__ : List[str] = init_xavier_std A__ : Any = encoder_layerdrop A__ : Optional[Any] = decoder_layerdrop A__ : Union[str, Any] = encoder_layers A__ : Dict = auxiliary_loss A__ : List[Any] = position_embedding_type A__ : Optional[Any] = backbone A__ : str = use_pretrained_backbone A__ : Union[str, Any] = dilation # Hungarian matcher A__ : Tuple = class_cost A__ : Optional[Any] = bbox_cost A__ : Dict = giou_cost # Loss coefficients A__ : Any = mask_loss_coefficient A__ : str = dice_loss_coefficient A__ : str = bbox_loss_coefficient A__ : Union[str, Any] = giou_loss_coefficient A__ : List[str] = eos_coefficient super().__init__(is_encoder_decoder=snake_case , **snake_case ) @property def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return self.encoder_attention_heads @property def _UpperCamelCase ( self : Dict ): '''simple docstring''' return self.d_model class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = version.parse('1.11' ) @property def _UpperCamelCase ( self : Any ): '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' return 1e-5 @property def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return 12
296
0
"""simple docstring""" import argparse import math import traceback import dateutil.parser as date_parser import requests def _lowerCAmelCase ( UpperCAmelCase__ : Union[str, Any] ) ->Optional[Any]: A__ : Optional[int] = {} A__ : List[str] = job['''started_at'''] A__ : Optional[int] = job['''completed_at'''] A__ : List[Any] = date_parser.parse(UpperCAmelCase__ ) A__ : int = date_parser.parse(UpperCAmelCase__ ) A__ : Dict = round((end_datetime - start_datetime).total_seconds() / 60.0 ) A__ : List[str] = start A__ : List[str] = end A__ : List[str] = duration_in_min return job_info def _lowerCAmelCase ( UpperCAmelCase__ : Optional[Any], UpperCAmelCase__ : Optional[Any]=None ) ->Union[str, Any]: A__ : Dict = None if token is not None: A__ : Dict = {'''Accept''': '''application/vnd.github+json''', '''Authorization''': f'Bearer {token}'} A__ : Any = f'https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100' A__ : Tuple = requests.get(UpperCAmelCase__, headers=UpperCAmelCase__ ).json() A__ : Optional[int] = {} try: job_time.update({job["""name"""]: extract_time_from_single_job(UpperCAmelCase__ ) for job in result["""jobs"""]} ) A__ : Tuple = math.ceil((result["""total_count"""] - 1_0_0) / 1_0_0 ) for i in range(UpperCAmelCase__ ): A__ : List[Any] = requests.get(url + f'&page={i + 2}', headers=UpperCAmelCase__ ).json() job_time.update({job["""name"""]: extract_time_from_single_job(UpperCAmelCase__ ) for job in result["""jobs"""]} ) return job_time except Exception: print(f'Unknown error, could not fetch links:\n{traceback.format_exc()}' ) return {} if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument('''--workflow_run_id''', type=str, required=True, help='''A GitHub Actions workflow run id.''') A_ = parser.parse_args() A_ = get_job_time(args.workflow_run_id) A_ = dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True)) for k, v in job_time.items(): print(F'{k}: {v["duration"]}')
357
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = 'Salesforce/blip-image-captioning-base' snake_case_ = ( 'This is a tool that generates a description of an image. It takes an input named `image` which should be the ' 'image to caption, and returns a text that contains the description in English.' ) snake_case_ = 'image_captioner' snake_case_ = AutoModelForVisionaSeq snake_case_ = ['image'] snake_case_ = ['text'] def __init__( self : int , *snake_case : Optional[int] , **snake_case : Optional[int] ): '''simple docstring''' requires_backends(self , ["""vision"""] ) super().__init__(*snake_case , **snake_case ) def _UpperCamelCase ( self : int , snake_case : "Image" ): '''simple docstring''' return self.pre_processor(images=snake_case , return_tensors="""pt""" ) def _UpperCamelCase ( self : int , snake_case : List[Any] ): '''simple docstring''' return self.model.generate(**snake_case ) def _UpperCamelCase ( self : Optional[int] , snake_case : Any ): '''simple docstring''' return self.pre_processor.batch_decode(snake_case , skip_special_tokens=snake_case )[0].strip()
296
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, is_valid_image, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL A_ = logging.get_logger(__name__) def _lowerCAmelCase ( UpperCAmelCase__ : Optional[Any] ) ->Optional[Any]: 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 __SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): snake_case_ = ['pixel_values'] def __init__( self : List[Any] , snake_case : bool = True , snake_case : Dict[str, int] = None , snake_case : PILImageResampling = PILImageResampling.BILINEAR , snake_case : bool = True , snake_case : Dict[str, int] = None , snake_case : bool = True , snake_case : Union[int, float] = 1 / 255 , snake_case : bool = True , snake_case : Optional[Union[float, List[float]]] = None , snake_case : Optional[Union[float, List[float]]] = None , **snake_case : List[str] , ): '''simple docstring''' super().__init__(**lowercase__ ) A__ : str = size if size is not None else {"""shortest_edge""": 224} A__ : Union[str, Any] = get_size_dict(lowercase__ , default_to_square=lowercase__ ) A__ : Tuple = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} A__ : Optional[Any] = get_size_dict(lowercase__ , param_name="""crop_size""" ) A__ : str = do_resize A__ : int = size A__ : List[str] = do_center_crop A__ : Tuple = crop_size A__ : List[Any] = resample A__ : Any = do_rescale A__ : Dict = rescale_factor A__ : Union[str, Any] = do_normalize A__ : str = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN A__ : Tuple = image_std if image_std is not None else IMAGENET_STANDARD_STD def _UpperCamelCase ( self : str , snake_case : np.ndarray , snake_case : Dict[str, int] , snake_case : PILImageResampling = PILImageResampling.BILINEAR , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : str , ): '''simple docstring''' A__ : Optional[Any] = get_size_dict(lowercase__ , default_to_square=lowercase__ ) if "shortest_edge" in size: A__ : Any = get_resize_output_image_size(lowercase__ , size["""shortest_edge"""] , default_to_square=lowercase__ ) elif "height" in size and "width" in size: A__ : Optional[int] = (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 _UpperCamelCase ( self : Any , snake_case : np.ndarray , snake_case : Dict[str, int] , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : Optional[Any] , ): '''simple docstring''' A__ : 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 _UpperCamelCase ( self : List[str] , snake_case : np.ndarray , snake_case : Union[int, float] , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : Dict , ): '''simple docstring''' return rescale(lowercase__ , scale=lowercase__ , data_format=lowercase__ , **lowercase__ ) def _UpperCamelCase ( self : int , snake_case : np.ndarray , snake_case : Union[float, List[float]] , snake_case : Union[float, List[float]] , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : int , ): '''simple docstring''' return normalize(lowercase__ , mean=lowercase__ , std=lowercase__ , data_format=lowercase__ , **lowercase__ ) def _UpperCamelCase ( self : Tuple , snake_case : ImageInput , snake_case : bool = None , snake_case : Dict[str, int] = None , snake_case : PILImageResampling = None , snake_case : bool = None , snake_case : Dict[str, int] = None , snake_case : bool = None , snake_case : float = None , snake_case : bool = None , snake_case : Optional[Union[float, List[float]]] = None , snake_case : Optional[Union[float, List[float]]] = None , snake_case : 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.""" ) # All transformations expect numpy arrays. A__ : List[str] = to_numpy_array(lowercase__ ) if do_resize: A__ : str = self.resize(image=lowercase__ , size=lowercase__ , resample=lowercase__ ) if do_center_crop: A__ : Any = self.center_crop(lowercase__ , size=lowercase__ ) if do_rescale: A__ : int = self.rescale(image=lowercase__ , scale=lowercase__ ) if do_normalize: A__ : Optional[Any] = self.normalize(image=lowercase__ , mean=lowercase__ , std=lowercase__ ) A__ : List[Any] = to_channel_dimension_format(lowercase__ , lowercase__ ) return image def _UpperCamelCase ( self : Optional[Any] , snake_case : ImageInput , snake_case : bool = None , snake_case : Dict[str, int] = None , snake_case : PILImageResampling = None , snake_case : bool = None , snake_case : Dict[str, int] = None , snake_case : bool = None , snake_case : float = None , snake_case : bool = None , snake_case : Optional[Union[float, List[float]]] = None , snake_case : Optional[Union[float, List[float]]] = None , snake_case : Optional[Union[str, TensorType]] = None , snake_case : ChannelDimension = ChannelDimension.FIRST , **snake_case : Optional[int] , ): '''simple docstring''' A__ : Tuple = do_resize if do_resize is not None else self.do_resize A__ : Dict = resample if resample is not None else self.resample A__ : Optional[int] = do_center_crop if do_center_crop is not None else self.do_center_crop A__ : Tuple = do_rescale if do_rescale is not None else self.do_rescale A__ : List[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor A__ : Union[str, Any] = do_normalize if do_normalize is not None else self.do_normalize A__ : int = image_mean if image_mean is not None else self.image_mean A__ : str = image_std if image_std is not None else self.image_std A__ : Union[str, Any] = size if size is not None else self.size A__ : Dict = get_size_dict(lowercase__ , default_to_square=lowercase__ ) A__ : Union[str, Any] = crop_size if crop_size is not None else self.crop_size A__ : Any = 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.""" ) A__ : Optional[int] = make_batched(lowercase__ ) A__ : Dict = [ [ 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__ , do_normalize=lowercase__ , image_mean=lowercase__ , image_std=lowercase__ , data_format=lowercase__ , ) for img in video ] for video in videos ] A__ : Dict = {"""pixel_values""": videos} return BatchFeature(data=lowercase__ , tensor_type=lowercase__ )
358
"""simple docstring""" import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : List[Any] ): '''simple docstring''' super().__init__() A__ : int = nn.Linear(3 , 4 ) A__ : Union[str, Any] = nn.BatchNormad(4 ) A__ : Union[str, Any] = nn.Linear(4 , 5 ) def _UpperCamelCase ( self : str , snake_case : List[str] ): '''simple docstring''' return self.lineara(self.batchnorm(self.lineara(snake_case ) ) ) class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : int = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(snake_case , model.state_dict() ) A__ : List[str] = os.path.join(snake_case , """index.json""" ) self.assertTrue(os.path.isfile(snake_case ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: A__ : List[str] = os.path.join(snake_case , F'{key}.dat' ) self.assertTrue(os.path.isfile(snake_case ) ) # TODO: add tests on the fact weights are properly loaded def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Union[str, Any] = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: A__ : str = torch.randn(2 , 3 , dtype=snake_case ) with TemporaryDirectory() as tmp_dir: A__ : List[str] = offload_weight(snake_case , """weight""" , snake_case , {} ) A__ : Union[str, Any] = os.path.join(snake_case , """weight.dat""" ) self.assertTrue(os.path.isfile(snake_case ) ) self.assertDictEqual(snake_case , {"""weight""": {"""shape""": [2, 3], """dtype""": str(snake_case ).split(""".""" )[1]}} ) A__ : str = load_offloaded_weight(snake_case , index["""weight"""] ) self.assertTrue(torch.equal(snake_case , snake_case ) ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : str = ModelForTest() A__ : Union[str, Any] = model.state_dict() A__ : Optional[int] = {k: v for k, v in state_dict.items() if """linear2""" not in k} A__ : List[Any] = {k: v for k, v in state_dict.items() if """linear2""" in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(snake_case , snake_case ) A__ : Dict = OffloadedWeightsLoader(state_dict=snake_case , save_folder=snake_case ) # Every key is there with the right value self.assertEqual(sorted(snake_case ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(snake_case , weight_map[key] ) ) A__ : int = {k: v for k, v in state_dict.items() if """weight""" in k} A__ : Tuple = {k: v for k, v in state_dict.items() if """weight""" not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(snake_case , snake_case ) A__ : Optional[Any] = OffloadedWeightsLoader(state_dict=snake_case , save_folder=snake_case ) # Every key is there with the right value self.assertEqual(sorted(snake_case ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(snake_case , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(snake_case , snake_case ) # Duplicates are removed A__ : int = OffloadedWeightsLoader(state_dict=snake_case , save_folder=snake_case ) # Every key is there with the right value self.assertEqual(sorted(snake_case ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(snake_case , weight_map[key] ) ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : List[str] = {"""a.1""": 0, """a.10""": 1, """a.2""": 2} A__ : str = extract_submodules_state_dict(snake_case , ["""a.1""", """a.2"""] ) self.assertDictEqual(snake_case , {"""a.1""": 0, """a.2""": 2} ) A__ : Dict = {"""a.1.a""": 0, """a.10.a""": 1, """a.2.a""": 2} A__ : int = extract_submodules_state_dict(snake_case , ["""a.1""", """a.2"""] ) self.assertDictEqual(snake_case , {"""a.1.a""": 0, """a.2.a""": 2} )
296
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging A_ = logging.get_logger(__name__) if is_vision_available(): import PIL class __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE__ ): snake_case_ = ['pixel_values'] def __init__( self : List[Any] , snake_case : bool = True , snake_case : Dict[str, int] = None , snake_case : PILImageResampling = PILImageResampling.BICUBIC , snake_case : bool = True , snake_case : Dict[str, int] = None , snake_case : bool = True , snake_case : Union[int, float] = 1 / 255 , snake_case : bool = True , snake_case : Optional[Union[float, List[float]]] = None , snake_case : Optional[Union[float, List[float]]] = None , snake_case : bool = True , **snake_case : Dict , ): '''simple docstring''' super().__init__(**snake_case ) A__ : Union[str, Any] = size if size is not None else {'shortest_edge': 224} A__ : Optional[int] = get_size_dict(snake_case , default_to_square=snake_case ) A__ : Optional[Any] = crop_size if crop_size is not None else {'height': 224, 'width': 224} A__ : List[str] = get_size_dict(snake_case , default_to_square=snake_case , param_name="""crop_size""" ) A__ : Union[str, Any] = do_resize A__ : Tuple = size A__ : Dict = resample A__ : List[Any] = do_center_crop A__ : Tuple = crop_size A__ : Optional[int] = do_rescale A__ : int = rescale_factor A__ : Dict = do_normalize A__ : Any = image_mean if image_mean is not None else OPENAI_CLIP_MEAN A__ : Any = image_std if image_std is not None else OPENAI_CLIP_STD A__ : List[str] = do_convert_rgb def _UpperCamelCase ( self : str , snake_case : np.ndarray , snake_case : Dict[str, int] , snake_case : PILImageResampling = PILImageResampling.BICUBIC , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : Dict , ): '''simple docstring''' A__ : str = get_size_dict(snake_case , default_to_square=snake_case ) if "shortest_edge" not in size: raise ValueError(F'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) A__ : List[str] = get_resize_output_image_size(snake_case , size=size["""shortest_edge"""] , default_to_square=snake_case ) return resize(snake_case , size=snake_case , resample=snake_case , data_format=snake_case , **snake_case ) def _UpperCamelCase ( self : str , snake_case : np.ndarray , snake_case : Dict[str, int] , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : Optional[Any] , ): '''simple docstring''' A__ : Dict = get_size_dict(snake_case ) 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(snake_case , size=(size["""height"""], size["""width"""]) , data_format=snake_case , **snake_case ) def _UpperCamelCase ( self : List[str] , snake_case : np.ndarray , snake_case : Union[int, float] , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : Optional[int] , ): '''simple docstring''' return rescale(snake_case , scale=snake_case , data_format=snake_case , **snake_case ) def _UpperCamelCase ( self : Union[str, Any] , snake_case : np.ndarray , snake_case : Union[float, List[float]] , snake_case : Union[float, List[float]] , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : Any , ): '''simple docstring''' return normalize(snake_case , mean=snake_case , std=snake_case , data_format=snake_case , **snake_case ) def _UpperCamelCase ( self : Optional[Any] , snake_case : ImageInput , snake_case : bool = None , snake_case : Dict[str, int] = None , snake_case : PILImageResampling = None , snake_case : bool = None , snake_case : int = None , snake_case : bool = None , snake_case : float = None , snake_case : bool = None , snake_case : Optional[Union[float, List[float]]] = None , snake_case : Optional[Union[float, List[float]]] = None , snake_case : bool = None , snake_case : Optional[Union[str, TensorType]] = None , snake_case : Optional[ChannelDimension] = ChannelDimension.FIRST , **snake_case : Dict , ): '''simple docstring''' A__ : Optional[Any] = do_resize if do_resize is not None else self.do_resize A__ : Optional[Any] = size if size is not None else self.size A__ : List[str] = get_size_dict(snake_case , param_name="""size""" , default_to_square=snake_case ) A__ : Dict = resample if resample is not None else self.resample A__ : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop A__ : Dict = crop_size if crop_size is not None else self.crop_size A__ : str = get_size_dict(snake_case , param_name="""crop_size""" , default_to_square=snake_case ) A__ : Dict = do_rescale if do_rescale is not None else self.do_rescale A__ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor A__ : Any = do_normalize if do_normalize is not None else self.do_normalize A__ : Tuple = image_mean if image_mean is not None else self.image_mean A__ : Optional[int] = image_std if image_std is not None else self.image_std A__ : str = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb A__ : List[Any] = make_list_of_images(snake_case ) if not valid_images(snake_case ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # PIL RGBA images are converted to RGB if do_convert_rgb: A__ : Tuple = [convert_to_rgb(snake_case ) for image in images] # All transformations expect numpy arrays. A__ : Dict = [to_numpy_array(snake_case ) for image in images] if do_resize: A__ : Dict = [self.resize(image=snake_case , size=snake_case , resample=snake_case ) for image in images] if do_center_crop: A__ : List[Any] = [self.center_crop(image=snake_case , size=snake_case ) for image in images] if do_rescale: A__ : Optional[int] = [self.rescale(image=snake_case , scale=snake_case ) for image in images] if do_normalize: A__ : int = [self.normalize(image=snake_case , mean=snake_case , std=snake_case ) for image in images] A__ : List[Any] = [to_channel_dimension_format(snake_case , snake_case ) for image in images] A__ : Optional[Any] = {'pixel_values': images} return BatchFeature(data=snake_case , tensor_type=snake_case )
359
"""simple docstring""" import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class __SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , snake_case : str , snake_case : List[Any]=13 , snake_case : Union[str, Any]=7 , snake_case : Optional[Any]=True , snake_case : str=True , snake_case : Dict=False , snake_case : Union[str, Any]=True , snake_case : Optional[Any]=99 , snake_case : str=32 , snake_case : Tuple=5 , snake_case : List[str]=4 , snake_case : Optional[int]=37 , snake_case : str="gelu" , snake_case : Tuple=0.1 , snake_case : Optional[int]=0.1 , snake_case : int=512 , snake_case : List[str]=16 , snake_case : str=2 , snake_case : Optional[int]=0.02 , snake_case : str=3 , snake_case : Dict=4 , snake_case : Optional[Any]=None , ): '''simple docstring''' A__ : int = parent A__ : Union[str, Any] = batch_size A__ : Optional[int] = seq_length A__ : List[Any] = is_training A__ : List[str] = use_input_mask A__ : Optional[Any] = use_token_type_ids A__ : List[Any] = use_labels A__ : Union[str, Any] = vocab_size A__ : List[Any] = hidden_size A__ : Any = num_hidden_layers A__ : Any = num_attention_heads A__ : Optional[int] = intermediate_size A__ : Any = hidden_act A__ : Tuple = hidden_dropout_prob A__ : Dict = attention_probs_dropout_prob A__ : Optional[int] = max_position_embeddings A__ : Tuple = type_vocab_size A__ : Union[str, Any] = type_sequence_label_size A__ : List[str] = initializer_range A__ : Any = num_labels A__ : Any = num_choices A__ : int = scope def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Tuple = None if self.use_input_mask: A__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) A__ : Union[str, Any] = None if self.use_token_type_ids: A__ : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A__ : int = None A__ : int = None A__ : List[str] = None if self.use_labels: A__ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : Dict = ids_tensor([self.batch_size] , self.num_choices ) A__ : Union[str, Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCamelCase ( self : Tuple ): '''simple docstring''' return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case , initializer_range=self.initializer_range , ) def _UpperCamelCase ( self : Optional[int] , snake_case : Dict , snake_case : Any , snake_case : Dict , snake_case : Any , snake_case : Union[str, Any] , snake_case : Tuple , snake_case : Optional[Any] ): '''simple docstring''' A__ : Optional[Any] = BioGptModel(config=snake_case ) model.to(snake_case ) model.eval() A__ : List[Any] = model(snake_case , attention_mask=snake_case ) A__ : Dict = model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : Optional[int] , snake_case : Dict , snake_case : Optional[int] , snake_case : List[str] , snake_case : str , snake_case : Optional[Any] , snake_case : List[str] , snake_case : List[Any] , snake_case : Tuple , snake_case : Optional[Any] , ): '''simple docstring''' A__ : List[str] = BioGptForCausalLM(config=snake_case ) model.to(snake_case ) model.eval() A__ : Union[str, Any] = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCamelCase ( self : Any , snake_case : str , snake_case : Tuple , snake_case : int , snake_case : Optional[Any] , snake_case : Any , *snake_case : Dict ): '''simple docstring''' A__ : Union[str, Any] = BioGptModel(config=snake_case ) model.to(snake_case ) model.eval() # create attention mask A__ : List[Any] = torch.ones(input_ids.shape , dtype=torch.long , device=snake_case ) A__ : Any = self.seq_length // 2 A__ : str = 0 # first forward pass A__ , A__ : List[Any] = model(snake_case , attention_mask=snake_case ).to_tuple() # create hypothetical next token and extent to next_input_ids A__ : int = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids A__ : List[str] = ids_tensor((1,) , snake_case ).item() + 1 A__ : Optional[int] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) A__ : int = random_other_next_tokens # append to next input_ids and attn_mask A__ : str = torch.cat([input_ids, next_tokens] , dim=-1 ) A__ : List[Any] = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=snake_case )] , dim=1 , ) # get two different outputs A__ : Union[str, Any] = model(snake_case , attention_mask=snake_case )["""last_hidden_state"""] A__ : Optional[int] = model(snake_case , past_key_values=snake_case , attention_mask=snake_case )["""last_hidden_state"""] # select random slice A__ : List[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() A__ : List[str] = output_from_no_past[:, -1, random_slice_idx].detach() A__ : Any = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(snake_case , snake_case , atol=1e-3 ) ) def _UpperCamelCase ( self : int , snake_case : Optional[Any] , snake_case : Optional[Any] , snake_case : str , snake_case : int , snake_case : Optional[Any] , *snake_case : str ): '''simple docstring''' A__ : Dict = BioGptModel(config=snake_case ).to(snake_case ).eval() A__ : Tuple = torch.ones(input_ids.shape , dtype=torch.long , device=snake_case ) # first forward pass A__ : Dict = model(snake_case , attention_mask=snake_case , use_cache=snake_case ) A__ , A__ : List[Any] = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids A__ : Union[str, Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ : int = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and A__ : str = torch.cat([input_ids, next_tokens] , dim=-1 ) A__ : Optional[int] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) A__ : Any = model(snake_case , attention_mask=snake_case )["""last_hidden_state"""] A__ : Union[str, Any] = model(snake_case , attention_mask=snake_case , past_key_values=snake_case )[ """last_hidden_state""" ] # select random slice A__ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() A__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() A__ : List[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(snake_case , snake_case , atol=1e-3 ) ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Tuple , snake_case : Union[str, Any] , snake_case : Optional[Any] , snake_case : Any , snake_case : Tuple , *snake_case : Union[str, Any] , snake_case : Union[str, Any]=False ): '''simple docstring''' A__ : Tuple = BioGptForCausalLM(snake_case ) model.to(snake_case ) if gradient_checkpointing: model.gradient_checkpointing_enable() A__ : Optional[Any] = model(snake_case , labels=snake_case ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def _UpperCamelCase ( self : int , snake_case : Optional[Any] , *snake_case : Optional[int] ): '''simple docstring''' A__ : int = BioGptModel(snake_case ) A__ : Union[str, Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def _UpperCamelCase ( self : Any , snake_case : Dict , snake_case : Tuple , snake_case : int , snake_case : Union[str, Any] , snake_case : Dict , *snake_case : Any ): '''simple docstring''' A__ : Union[str, Any] = self.num_labels A__ : int = BioGptForTokenClassification(snake_case ) model.to(snake_case ) model.eval() A__ : str = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : List[str] = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) : str = config_and_inputs A__ : Union[str, Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase ): snake_case_ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) snake_case_ = (BioGptForCausalLM,) if is_torch_available() else () snake_case_ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = False def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : List[str] = BioGptModelTester(self ) A__ : List[Any] = ConfigTester(self , config_class=snake_case , hidden_size=37 ) def _UpperCamelCase ( self : int ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Any ): '''simple docstring''' A__ : int = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A__ : str = type self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*snake_case ) def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*snake_case , gradient_checkpointing=snake_case ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*snake_case ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*snake_case ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*snake_case ) @slow def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : Tuple = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(snake_case ) A__ : Optional[int] = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) A__ : Any = """left""" # Define PAD Token = EOS Token = 50256 A__ : Optional[int] = tokenizer.eos_token A__ : Dict = model.config.eos_token_id # use different length sentences to test batching A__ : Union[str, Any] = [ """Hello, my dog is a little""", """Today, I""", ] A__ : List[str] = tokenizer(snake_case , return_tensors="""pt""" , padding=snake_case ) A__ : str = inputs["""input_ids"""].to(snake_case ) A__ : Dict = model.generate( input_ids=snake_case , attention_mask=inputs["""attention_mask"""].to(snake_case ) , ) A__ : Optional[int] = tokenizer(sentences[0] , return_tensors="""pt""" ).input_ids.to(snake_case ) A__ : Any = model.generate(input_ids=snake_case ) A__ : List[str] = inputs_non_padded.shape[-1] - inputs["""attention_mask"""][-1].long().sum().cpu().item() A__ : str = tokenizer(sentences[1] , return_tensors="""pt""" ).input_ids.to(snake_case ) A__ : Dict = model.generate(input_ids=snake_case , max_length=model.config.max_length - num_paddings ) A__ : Optional[Any] = tokenizer.batch_decode(snake_case , skip_special_tokens=snake_case ) A__ : List[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=snake_case ) A__ : str = tokenizer.decode(output_padded[0] , skip_special_tokens=snake_case ) A__ : Optional[int] = [ """Hello, my dog is a little bit bigger than a little bit.""", """Today, I have a good idea of how to use the information""", ] self.assertListEqual(snake_case , snake_case ) self.assertListEqual(snake_case , [non_padded_sentence, padded_sentence] ) @slow def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ : Optional[Any] = BioGptModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ , A__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() A__ : Optional[int] = 3 A__ : List[Any] = input_dict["""input_ids"""] A__ : Dict = input_ids.ne(1 ).to(snake_case ) A__ : Optional[Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) A__ : Union[str, Any] = BioGptForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : int = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ , A__ : str = self.model_tester.prepare_config_and_inputs_for_common() A__ : Any = 3 A__ : List[Any] = """multi_label_classification""" A__ : Dict = input_dict["""input_ids"""] A__ : Tuple = input_ids.ne(1 ).to(snake_case ) A__ : Any = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) A__ : Tuple = BioGptForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : List[str] = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : Optional[Any] = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) A__ : str = torch.tensor([[2, 4805, 9, 656, 21]] ) A__ : Dict = model(snake_case )[0] A__ : Tuple = 4_2384 A__ : str = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , snake_case ) A__ : str = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) ) @slow def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : Tuple = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) A__ : Any = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(snake_case ) torch.manual_seed(0 ) A__ : Tuple = tokenizer("""COVID-19 is""" , return_tensors="""pt""" ).to(snake_case ) A__ : Optional[int] = model.generate( **snake_case , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=snake_case , ) A__ : Optional[int] = tokenizer.decode(output_ids[0] , skip_special_tokens=snake_case ) A__ : List[str] = ( """COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the""" """ causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and""" """ territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),""" """ and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and""" """ more than 800,000 deaths.""" ) self.assertEqual(snake_case , snake_case )
296
0
"""simple docstring""" import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _UpperCamelCase ( self : int ): '''simple docstring''' debug_launcher(test_script.main ) def _UpperCamelCase ( self : int ): '''simple docstring''' debug_launcher(test_ops.main )
360
"""simple docstring""" 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 SPIECE_UNDERLINE, logging A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''spiece.model'''} A_ = { '''vocab_file''': { '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model''', '''xlnet-large-cased''': '''https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model''', } } A_ = { '''xlnet-base-cased''': None, '''xlnet-large-cased''': None, } # Segments (not really needed) A_ = 0 A_ = 1 A_ = 2 A_ = 3 A_ = 4 class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = 'left' def __init__( self : Dict , snake_case : int , snake_case : List[Any]=False , snake_case : List[str]=True , snake_case : Dict=False , snake_case : Optional[Any]="<s>" , snake_case : List[str]="</s>" , snake_case : Tuple="<unk>" , snake_case : Tuple="<sep>" , snake_case : Union[str, Any]="<pad>" , snake_case : Dict="<cls>" , snake_case : Optional[Any]="<mask>" , snake_case : Optional[int]=["<eop>", "<eod>"] , snake_case : Optional[Dict[str, Any]] = None , **snake_case : Dict , ): '''simple docstring''' A__ : Optional[int] = AddedToken(snake_case , lstrip=snake_case , rstrip=snake_case ) if isinstance(snake_case , snake_case ) else mask_token A__ : Union[str, Any] = {} 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 , additional_special_tokens=snake_case , sp_model_kwargs=self.sp_model_kwargs , **snake_case , ) A__ : str = 3 A__ : str = do_lower_case A__ : Optional[Any] = remove_space A__ : List[Any] = keep_accents A__ : Union[str, Any] = vocab_file A__ : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(snake_case ) @property def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' return len(self.sp_model ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : 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 : str ): '''simple docstring''' A__ : int = self.__dict__.copy() A__ : int = None return state def __setstate__( self : Tuple , snake_case : Union[str, Any] ): '''simple docstring''' A__ : int = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): A__ : Optional[int] = {} A__ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _UpperCamelCase ( self : List[str] , snake_case : Optional[Any] ): '''simple docstring''' if self.remove_space: A__ : Optional[Any] = """ """.join(inputs.strip().split() ) else: A__ : Dict = inputs A__ : str = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: A__ : Any = unicodedata.normalize("""NFKD""" , snake_case ) A__ : Optional[int] = """""".join([c for c in outputs if not unicodedata.combining(snake_case )] ) if self.do_lower_case: A__ : Any = outputs.lower() return outputs def _UpperCamelCase ( self : Union[str, Any] , snake_case : str ): '''simple docstring''' A__ : Dict = self.preprocess_text(snake_case ) A__ : Dict = self.sp_model.encode(snake_case , out_type=snake_case ) A__ : Optional[int] = [] for piece in pieces: if len(snake_case ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): A__ : Optional[Any] = 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__ : Any = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(snake_case ) else: new_pieces.append(snake_case ) return new_pieces def _UpperCamelCase ( self : List[str] , snake_case : Tuple ): '''simple docstring''' return self.sp_model.PieceToId(snake_case ) def _UpperCamelCase ( self : List[str] , snake_case : Any ): '''simple docstring''' return self.sp_model.IdToPiece(snake_case ) def _UpperCamelCase ( self : Optional[int] , snake_case : Any ): '''simple docstring''' A__ : Union[str, Any] = """""".join(snake_case ).replace(snake_case , """ """ ).strip() return out_string def _UpperCamelCase ( self : int , snake_case : List[int] , snake_case : bool = False , snake_case : bool = None , snake_case : bool = True , **snake_case : Union[str, Any] , ): '''simple docstring''' A__ : List[str] = kwargs.pop("""use_source_tokenizer""" , snake_case ) A__ : Any = self.convert_ids_to_tokens(snake_case , skip_special_tokens=snake_case ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 A__ : Any = [] A__ : Any = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(snake_case ) ) A__ : str = [] sub_texts.append(snake_case ) else: current_sub_text.append(snake_case ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(snake_case ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens A__ : Dict = """""".join(snake_case ) A__ : int = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: A__ : Tuple = self.clean_up_tokenization(snake_case ) return clean_text else: return text def _UpperCamelCase ( self : str , snake_case : List[int] , snake_case : Optional[List[int]] = None ): '''simple docstring''' A__ : Tuple = [self.sep_token_id] A__ : Dict = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _UpperCamelCase ( self : Dict , snake_case : List[int] , snake_case : Optional[List[int]] = None , snake_case : bool = False ): '''simple docstring''' 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 ([0] * len(snake_case )) + [1] + ([0] * len(snake_case )) + [1, 1] return ([0] * len(snake_case )) + [1, 1] def _UpperCamelCase ( self : str , snake_case : List[int] , snake_case : Optional[List[int]] = None ): '''simple docstring''' A__ : Any = [self.sep_token_id] A__ : int = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _UpperCamelCase ( self : Optional[Any] , snake_case : str , snake_case : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(snake_case ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A__ : List[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__ : Optional[Any] = self.sp_model.serialized_model_proto() fi.write(snake_case ) return (out_vocab_file,)
296
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import RoFormerConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerModel, ) from transformers.models.roformer.modeling_tf_roformer import ( TFRoFormerSelfAttention, TFRoFormerSinusoidalPositionalEmbedding, ) class __SCREAMING_SNAKE_CASE : def __init__( self : int , snake_case : Union[str, Any] , snake_case : List[str]=13 , snake_case : Dict=7 , snake_case : Union[str, Any]=True , snake_case : Union[str, Any]=True , snake_case : int=True , snake_case : Tuple=True , snake_case : List[Any]=99 , snake_case : Union[str, Any]=32 , snake_case : Dict=2 , snake_case : List[str]=4 , snake_case : Union[str, Any]=37 , snake_case : List[Any]="gelu" , snake_case : str=0.1 , snake_case : Optional[Any]=0.1 , snake_case : Tuple=512 , snake_case : Optional[int]=16 , snake_case : Any=2 , snake_case : Optional[int]=0.02 , snake_case : int=3 , snake_case : str=4 , snake_case : Optional[Any]=None , ): '''simple docstring''' A__ : Any = parent A__ : List[Any] = 13 A__ : Any = 7 A__ : Optional[int] = True A__ : int = True A__ : Union[str, Any] = True A__ : int = True A__ : List[str] = 99 A__ : Any = 32 A__ : Dict = 2 A__ : Union[str, Any] = 4 A__ : List[Any] = 37 A__ : Optional[int] = """gelu""" A__ : Dict = 0.1 A__ : int = 0.1 A__ : Dict = 512 A__ : int = 16 A__ : int = 2 A__ : Any = 0.02 A__ : int = 3 A__ : str = 4 A__ : Optional[Any] = None def _UpperCamelCase ( self : Any ): '''simple docstring''' A__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Dict = None if self.use_input_mask: A__ : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) A__ : Dict = None if self.use_token_type_ids: A__ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A__ : List[Any] = None A__ : Any = None A__ : str = None if self.use_labels: A__ : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : List[str] = ids_tensor([self.batch_size] , self.num_choices ) A__ : Optional[Any] = RoFormerConfig( 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 , return_dict=UpperCAmelCase__ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCamelCase ( self : Dict , snake_case : List[Any] , snake_case : List[Any] , snake_case : Dict , snake_case : Tuple , snake_case : int , snake_case : Union[str, Any] , snake_case : Any ): '''simple docstring''' A__ : Tuple = TFRoFormerModel(config=UpperCAmelCase__ ) A__ : List[str] = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} A__ : str = [input_ids, input_mask] A__ : Any = model(UpperCAmelCase__ ) A__ : str = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : List[str] , snake_case : Optional[Any] , snake_case : List[Any] , snake_case : int , snake_case : Tuple , snake_case : Union[str, Any] , snake_case : Optional[Any] , snake_case : Union[str, Any] ): '''simple docstring''' A__ : Any = True A__ : Dict = TFRoFormerForCausalLM(config=UpperCAmelCase__ ) A__ : List[str] = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } A__ : List[str] = model(UpperCAmelCase__ )["""logits"""] self.parent.assertListEqual( list(prediction_scores.numpy().shape ) , [self.batch_size, self.seq_length, self.vocab_size] ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Dict , snake_case : Dict , snake_case : Dict , snake_case : Tuple , snake_case : Tuple , snake_case : Any , snake_case : List[str] ): '''simple docstring''' A__ : Optional[int] = TFRoFormerForMaskedLM(config=UpperCAmelCase__ ) A__ : str = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } A__ : List[str] = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCamelCase ( self : List[Any] , snake_case : Dict , snake_case : Dict , snake_case : Dict , snake_case : Tuple , snake_case : Tuple , snake_case : Dict , snake_case : Optional[Any] ): '''simple docstring''' A__ : int = self.num_labels A__ : Tuple = TFRoFormerForSequenceClassification(config=UpperCAmelCase__ ) A__ : Any = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } A__ : Optional[int] = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _UpperCamelCase ( self : List[Any] , snake_case : Tuple , snake_case : Optional[Any] , snake_case : Any , snake_case : int , snake_case : int , snake_case : Optional[int] , snake_case : Optional[Any] ): '''simple docstring''' A__ : Optional[int] = self.num_choices A__ : List[Any] = TFRoFormerForMultipleChoice(config=UpperCAmelCase__ ) A__ : str = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1 ) , (1, self.num_choices, 1) ) A__ : int = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1 ) , (1, self.num_choices, 1) ) A__ : str = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1 ) , (1, self.num_choices, 1) ) A__ : int = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, """token_type_ids""": multiple_choice_token_type_ids, } A__ : Optional[int] = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _UpperCamelCase ( self : List[Any] , snake_case : Dict , snake_case : Union[str, Any] , snake_case : Optional[Any] , snake_case : Optional[Any] , snake_case : Any , snake_case : Any , snake_case : List[str] ): '''simple docstring''' A__ : List[Any] = self.num_labels A__ : Any = TFRoFormerForTokenClassification(config=UpperCAmelCase__ ) A__ : Any = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } A__ : List[str] = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self : Any , snake_case : Optional[int] , snake_case : int , snake_case : Optional[Any] , snake_case : List[str] , snake_case : List[Any] , snake_case : Dict , snake_case : Union[str, Any] ): '''simple docstring''' A__ : List[Any] = TFRoFormerForQuestionAnswering(config=UpperCAmelCase__ ) A__ : Optional[Any] = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } A__ : Optional[int] = model(UpperCAmelCase__ ) 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 _UpperCamelCase ( self : int ): '''simple docstring''' A__ : str = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) : Optional[int] = config_and_inputs A__ : Optional[int] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class __SCREAMING_SNAKE_CASE ( __lowercase , __lowercase , unittest.TestCase ): snake_case_ = ( ( TFRoFormerModel, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerForMultipleChoice, ) if is_tf_available() else () ) snake_case_ = ( { '''feature-extraction''': TFRoFormerModel, '''fill-mask''': TFRoFormerForMaskedLM, '''question-answering''': TFRoFormerForQuestionAnswering, '''text-classification''': TFRoFormerForSequenceClassification, '''text-generation''': TFRoFormerForCausalLM, '''token-classification''': TFRoFormerForTokenClassification, '''zero-shot''': TFRoFormerForSequenceClassification, } if is_tf_available() else {} ) snake_case_ = False snake_case_ = False def _UpperCamelCase ( self : Tuple , snake_case : str , snake_case : Optional[Any] , snake_case : str , snake_case : Optional[Any] , snake_case : Union[str, Any] ): '''simple docstring''' if pipeline_test_casse_name == "TextGenerationPipelineTests": return True return False def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : Optional[int] = TFRoFormerModelTester(self ) A__ : int = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=37 ) def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase__ ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head(*UpperCAmelCase__ ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCAmelCase__ ) def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase__ ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase__ ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase__ ) @slow def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : List[Any] = TFRoFormerModel.from_pretrained("""junnyu/roformer_chinese_base""" ) self.assertIsNotNone(UpperCAmelCase__ ) @require_tf class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : List[str] = TFRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) A__ : int = tf.constant([[0, 1, 2, 3, 4, 5]] ) A__ : int = model(UpperCAmelCase__ )[0] # TODO Replace vocab size A__ : Dict = 5_0000 A__ : Optional[int] = [1, 6, vocab_size] self.assertEqual(output.shape , UpperCAmelCase__ ) print(output[:, :3, :3] ) # TODO Replace values below with what was printed above. A__ : Any = tf.constant( [ [ [-0.12053341, -1.0264901, 0.29221946], [-1.5133783, 0.197433, 0.15190607], [-5.0135403, -3.900256, -0.84038764], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4 ) @require_tf class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): snake_case_ = 1E-4 def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : List[Any] = tf.constant([[4, 10]] ) A__ : Optional[int] = TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 , embedding_dim=6 ) A__ : List[str] = emba(input_ids.shape ) A__ : Optional[Any] = tf.constant( [[0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 1.0000], [0.8415, 0.0464, 0.0022, 0.5403, 0.9989, 1.0000]] ) tf.debugging.assert_near(UpperCAmelCase__ , UpperCAmelCase__ , atol=self.tolerance ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Any = tf.constant( [ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.8415, 0.8219, 0.8020, 0.7819, 0.7617], [0.9093, 0.9364, 0.9581, 0.9749, 0.9870], ] ) A__ : str = TFRoFormerSinusoidalPositionalEmbedding(num_positions=512 , embedding_dim=512 ) emba([2, 16, 512] ) A__ : Optional[int] = emba.weight[:3, :5] tf.debugging.assert_near(UpperCAmelCase__ , UpperCAmelCase__ , atol=self.tolerance ) @require_tf class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): snake_case_ = 1E-4 def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : List[str] = tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa ) , shape=(2, 12, 16, 64) ) / 100 A__ : Dict = -tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa ) , shape=(2, 12, 16, 64) ) / 100 A__ : str = TFRoFormerSinusoidalPositionalEmbedding(num_positions=32 , embedding_dim=64 ) A__ : Optional[Any] = embed_positions([2, 16, 768] )[None, None, :, :] A__ , A__ : Optional[int] = TFRoFormerSelfAttention.apply_rotary_position_embeddings( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) A__ : int = tf.constant( [ [0.0000, 0.0100, 0.0200, 0.0300, 0.0400, 0.0500, 0.0600, 0.0700], [-0.2012, 0.8897, 0.0263, 0.9401, 0.2074, 0.9463, 0.3481, 0.9343], [-1.7057, 0.6271, -1.2145, 1.3897, -0.6303, 1.7647, -0.1173, 1.8985], [-2.1731, -1.6397, -2.7358, 0.2854, -2.1840, 1.7183, -1.3018, 2.4871], [0.2717, -3.6173, -2.9206, -2.1988, -3.6638, 0.3858, -2.9155, 2.2980], [3.9859, -2.1580, -0.7984, -4.4904, -4.1181, -2.0252, -4.4782, 1.1253], ] ) A__ : Any = tf.constant( [ [0.0000, -0.0100, -0.0200, -0.0300, -0.0400, -0.0500, -0.0600, -0.0700], [0.2012, -0.8897, -0.0263, -0.9401, -0.2074, -0.9463, -0.3481, -0.9343], [1.7057, -0.6271, 1.2145, -1.3897, 0.6303, -1.7647, 0.1173, -1.8985], [2.1731, 1.6397, 2.7358, -0.2854, 2.1840, -1.7183, 1.3018, -2.4871], [-0.2717, 3.6173, 2.9206, 2.1988, 3.6638, -0.3858, 2.9155, -2.2980], [-3.9859, 2.1580, 0.7984, 4.4904, 4.1181, 2.0252, 4.4782, -1.1253], ] ) tf.debugging.assert_near(query_layer[0, 0, :6, :8] , UpperCAmelCase__ , atol=self.tolerance ) tf.debugging.assert_near(key_layer[0, 0, :6, :8] , UpperCAmelCase__ , atol=self.tolerance )
361
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) def _lowerCAmelCase ( UpperCAmelCase__ : List[Any] ) ->List[str]: A__ : Union[str, Any] = DPTConfig() if "large" in checkpoint_url: A__ : int = 1_0_2_4 A__ : Union[str, Any] = 4_0_9_6 A__ : Optional[int] = 2_4 A__ : int = 1_6 A__ : Union[str, Any] = [5, 1_1, 1_7, 2_3] A__ : Tuple = [2_5_6, 5_1_2, 1_0_2_4, 1_0_2_4] A__ : Tuple = (1, 3_8_4, 3_8_4) if "ade" in checkpoint_url: A__ : Optional[int] = True A__ : int = 1_5_0 A__ : Union[str, Any] = """huggingface/label-files""" A__ : List[Any] = """ade20k-id2label.json""" A__ : Union[str, Any] = json.load(open(cached_download(hf_hub_url(UpperCAmelCase__, UpperCAmelCase__, repo_type="""dataset""" ) ), """r""" ) ) A__ : List[Any] = {int(UpperCAmelCase__ ): v for k, v in idalabel.items()} A__ : Dict = idalabel A__ : List[Any] = {v: k for k, v in idalabel.items()} A__ : Optional[Any] = [1, 1_5_0, 4_8_0, 4_8_0] return config, expected_shape def _lowerCAmelCase ( UpperCAmelCase__ : int ) ->Any: A__ : List[Any] = ["""pretrained.model.head.weight""", """pretrained.model.head.bias"""] for k in ignore_keys: state_dict.pop(UpperCAmelCase__, UpperCAmelCase__ ) def _lowerCAmelCase ( UpperCAmelCase__ : Union[str, Any] ) ->List[str]: if ( "pretrained.model" in name and "cls_token" not in name and "pos_embed" not in name and "patch_embed" not in name ): A__ : str = name.replace("""pretrained.model""", """dpt.encoder""" ) if "pretrained.model" in name: A__ : Dict = name.replace("""pretrained.model""", """dpt.embeddings""" ) if "patch_embed" in name: A__ : List[Any] = name.replace("""patch_embed""", """patch_embeddings""" ) if "pos_embed" in name: A__ : int = name.replace("""pos_embed""", """position_embeddings""" ) if "attn.proj" in name: A__ : Tuple = name.replace("""attn.proj""", """attention.output.dense""" ) if "proj" in name and "project" not in name: A__ : List[Any] = name.replace("""proj""", """projection""" ) if "blocks" in name: A__ : Optional[Any] = name.replace("""blocks""", """layer""" ) if "mlp.fc1" in name: A__ : int = name.replace("""mlp.fc1""", """intermediate.dense""" ) if "mlp.fc2" in name: A__ : List[str] = name.replace("""mlp.fc2""", """output.dense""" ) if "norm1" in name: A__ : Any = name.replace("""norm1""", """layernorm_before""" ) if "norm2" in name: A__ : List[str] = name.replace("""norm2""", """layernorm_after""" ) if "scratch.output_conv" in name: A__ : Optional[int] = name.replace("""scratch.output_conv""", """head""" ) if "scratch" in name: A__ : List[str] = name.replace("""scratch""", """neck""" ) if "layer1_rn" in name: A__ : List[str] = name.replace("""layer1_rn""", """convs.0""" ) if "layer2_rn" in name: A__ : Optional[int] = name.replace("""layer2_rn""", """convs.1""" ) if "layer3_rn" in name: A__ : Any = name.replace("""layer3_rn""", """convs.2""" ) if "layer4_rn" in name: A__ : Any = name.replace("""layer4_rn""", """convs.3""" ) if "refinenet" in name: A__ : Union[str, Any] = int(name[len("""neck.refinenet""" ) : len("""neck.refinenet""" ) + 1] ) # tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3 A__ : str = name.replace(f'refinenet{layer_idx}', f'fusion_stage.layers.{abs(layer_idx-4 )}' ) if "out_conv" in name: A__ : Optional[Any] = name.replace("""out_conv""", """projection""" ) if "resConfUnit1" in name: A__ : List[Any] = name.replace("""resConfUnit1""", """residual_layer1""" ) if "resConfUnit2" in name: A__ : Tuple = name.replace("""resConfUnit2""", """residual_layer2""" ) if "conv1" in name: A__ : Tuple = name.replace("""conv1""", """convolution1""" ) if "conv2" in name: A__ : List[Any] = name.replace("""conv2""", """convolution2""" ) # readout blocks if "pretrained.act_postprocess1.0.project.0" in name: A__ : Union[str, Any] = name.replace("""pretrained.act_postprocess1.0.project.0""", """neck.reassemble_stage.readout_projects.0.0""" ) if "pretrained.act_postprocess2.0.project.0" in name: A__ : Tuple = name.replace("""pretrained.act_postprocess2.0.project.0""", """neck.reassemble_stage.readout_projects.1.0""" ) if "pretrained.act_postprocess3.0.project.0" in name: A__ : Optional[Any] = name.replace("""pretrained.act_postprocess3.0.project.0""", """neck.reassemble_stage.readout_projects.2.0""" ) if "pretrained.act_postprocess4.0.project.0" in name: A__ : Optional[Any] = name.replace("""pretrained.act_postprocess4.0.project.0""", """neck.reassemble_stage.readout_projects.3.0""" ) # resize blocks if "pretrained.act_postprocess1.3" in name: A__ : Any = name.replace("""pretrained.act_postprocess1.3""", """neck.reassemble_stage.layers.0.projection""" ) if "pretrained.act_postprocess1.4" in name: A__ : List[Any] = name.replace("""pretrained.act_postprocess1.4""", """neck.reassemble_stage.layers.0.resize""" ) if "pretrained.act_postprocess2.3" in name: A__ : Dict = name.replace("""pretrained.act_postprocess2.3""", """neck.reassemble_stage.layers.1.projection""" ) if "pretrained.act_postprocess2.4" in name: A__ : Optional[Any] = name.replace("""pretrained.act_postprocess2.4""", """neck.reassemble_stage.layers.1.resize""" ) if "pretrained.act_postprocess3.3" in name: A__ : Union[str, Any] = name.replace("""pretrained.act_postprocess3.3""", """neck.reassemble_stage.layers.2.projection""" ) if "pretrained.act_postprocess4.3" in name: A__ : Optional[int] = name.replace("""pretrained.act_postprocess4.3""", """neck.reassemble_stage.layers.3.projection""" ) if "pretrained.act_postprocess4.4" in name: A__ : Dict = name.replace("""pretrained.act_postprocess4.4""", """neck.reassemble_stage.layers.3.resize""" ) if "pretrained" in name: A__ : Union[str, Any] = name.replace("""pretrained""", """dpt""" ) if "bn" in name: A__ : Union[str, Any] = name.replace("""bn""", """batch_norm""" ) if "head" in name: A__ : Dict = name.replace("""head""", """head.head""" ) if "encoder.norm" in name: A__ : Optional[int] = name.replace("""encoder.norm""", """layernorm""" ) if "auxlayer" in name: A__ : List[str] = name.replace("""auxlayer""", """auxiliary_head.head""" ) return name def _lowerCAmelCase ( UpperCAmelCase__ : int, UpperCAmelCase__ : Dict ) ->str: for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) A__ : Any = state_dict.pop(f'dpt.encoder.layer.{i}.attn.qkv.weight' ) A__ : Tuple = state_dict.pop(f'dpt.encoder.layer.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict A__ : List[str] = in_proj_weight[: config.hidden_size, :] A__ : int = in_proj_bias[: config.hidden_size] A__ : Tuple = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] A__ : Any = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] A__ : str = in_proj_weight[ -config.hidden_size :, : ] A__ : Optional[Any] = in_proj_bias[-config.hidden_size :] def _lowerCAmelCase ( ) ->List[str]: A__ : int = """http://images.cocodataset.org/val2017/000000039769.jpg""" A__ : int = Image.open(requests.get(UpperCAmelCase__, stream=UpperCAmelCase__ ).raw ) return im @torch.no_grad() def _lowerCAmelCase ( UpperCAmelCase__ : int, UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : str, UpperCAmelCase__ : int ) ->str: A__ , A__ : Dict = get_dpt_config(UpperCAmelCase__ ) # load original state_dict from URL A__ : Any = torch.hub.load_state_dict_from_url(UpperCAmelCase__, map_location="""cpu""" ) # remove certain keys remove_ignore_keys_(UpperCAmelCase__ ) # rename keys for key in state_dict.copy().keys(): A__ : int = state_dict.pop(UpperCAmelCase__ ) A__ : str = val # read in qkv matrices read_in_q_k_v(UpperCAmelCase__, UpperCAmelCase__ ) # load HuggingFace model A__ : Optional[Any] = DPTForSemanticSegmentation(UpperCAmelCase__ ) if """ade""" in checkpoint_url else DPTForDepthEstimation(UpperCAmelCase__ ) model.load_state_dict(UpperCAmelCase__ ) model.eval() # Check outputs on an image A__ : Optional[Any] = 4_8_0 if """ade""" in checkpoint_url else 3_8_4 A__ : Dict = DPTImageProcessor(size=UpperCAmelCase__ ) A__ : Optional[int] = prepare_img() A__ : Any = image_processor(UpperCAmelCase__, return_tensors="""pt""" ) # forward pass A__ : List[str] = model(**UpperCAmelCase__ ).logits if """ade""" in checkpoint_url else model(**UpperCAmelCase__ ).predicted_depth # Assert logits A__ : Optional[Any] = torch.tensor([[6.3199, 6.3629, 6.4148], [6.3850, 6.3615, 6.4166], [6.3519, 6.3176, 6.3575]] ) if "ade" in checkpoint_url: A__ : Optional[int] = torch.tensor([[4.0480, 4.2420, 4.4360], [4.3124, 4.5693, 4.8261], [4.5768, 4.8965, 5.2163]] ) assert outputs.shape == torch.Size(UpperCAmelCase__ ) assert ( torch.allclose(outputs[0, 0, :3, :3], UpperCAmelCase__, atol=1e-4 ) if "ade" in checkpoint_url else torch.allclose(outputs[0, :3, :3], UpperCAmelCase__ ) ) Path(UpperCAmelCase__ ).mkdir(exist_ok=UpperCAmelCase__ ) print(f'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(UpperCAmelCase__ ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(UpperCAmelCase__ ) if push_to_hub: print("""Pushing model to hub...""" ) model.push_to_hub( repo_path_or_name=Path(UpperCAmelCase__, UpperCAmelCase__ ), organization="""nielsr""", commit_message="""Add model""", use_temp_dir=UpperCAmelCase__, ) image_processor.push_to_hub( repo_path_or_name=Path(UpperCAmelCase__, UpperCAmelCase__ ), organization="""nielsr""", commit_message="""Add image processor""", use_temp_dir=UpperCAmelCase__, ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt''', type=str, help='''URL of the original DPT checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', action='''store_true''', ) parser.add_argument( '''--model_name''', default='''dpt-large''', type=str, help='''Name of the model, in case you\'re pushing to the hub.''', ) A_ = parser.parse_args() convert_dpt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
296
0
"""simple docstring""" import argparse import torch from torch import nn from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration def _lowerCAmelCase ( UpperCAmelCase__ : Optional[Any] ) ->int: A__ : Optional[int] = [ """encoder.version""", """decoder.version""", """model.encoder.version""", """model.decoder.version""", """decoder.output_projection.weight""", """_float_tensor""", """encoder.embed_positions._float_tensor""", """decoder.embed_positions._float_tensor""", ] for k in ignore_keys: state_dict.pop(__lowerCAmelCase, __lowerCAmelCase ) def _lowerCAmelCase ( UpperCAmelCase__ : Dict ) ->Optional[Any]: A__ : Any = list(s_dict.keys() ) for key in keys: if "transformer_layers" in key: A__ : Optional[int] = s_dict.pop(__lowerCAmelCase ) elif "subsample" in key: A__ : Dict = s_dict.pop(__lowerCAmelCase ) def _lowerCAmelCase ( UpperCAmelCase__ : List[Any] ) ->List[Any]: A__ : int = emb.weight.shape A__ : List[str] = nn.Linear(__lowerCAmelCase, __lowerCAmelCase, bias=__lowerCAmelCase ) A__ : int = emb.weight.data return lin_layer def _lowerCAmelCase ( UpperCAmelCase__ : str, UpperCAmelCase__ : List[Any] ) ->Optional[int]: A__ : int = torch.load(__lowerCAmelCase, map_location="""cpu""" ) A__ : List[Any] = mam_aaa["""args"""] A__ : Optional[int] = mam_aaa["""model"""] A__ : Dict = state_dict["""decoder.output_projection.weight"""] remove_ignore_keys_(__lowerCAmelCase ) rename_keys(__lowerCAmelCase ) A__ : Dict = state_dict["""decoder.embed_tokens.weight"""].shape[0] A__ : List[str] = args.share_decoder_input_output_embed A__ : Optional[int] = [int(__lowerCAmelCase ) for i in args.conv_kernel_sizes.split(""",""" )] A__ : str = SpeechaTextConfig( vocab_size=__lowerCAmelCase, max_source_positions=args.max_source_positions, max_target_positions=args.max_target_positions, encoder_layers=args.encoder_layers, decoder_layers=args.decoder_layers, encoder_attention_heads=args.encoder_attention_heads, decoder_attention_heads=args.decoder_attention_heads, encoder_ffn_dim=args.encoder_ffn_embed_dim, decoder_ffn_dim=args.decoder_ffn_embed_dim, d_model=args.encoder_embed_dim, dropout=args.dropout, attention_dropout=args.attention_dropout, activation_dropout=args.activation_dropout, activation_function="""relu""", num_conv_layers=len(__lowerCAmelCase ), conv_channels=args.conv_channels, conv_kernel_sizes=__lowerCAmelCase, input_feat_per_channel=args.input_feat_per_channel, input_channels=args.input_channels, tie_word_embeddings=__lowerCAmelCase, num_beams=5, max_length=2_0_0, use_cache=__lowerCAmelCase, decoder_start_token_id=2, early_stopping=__lowerCAmelCase, ) A__ : Optional[Any] = SpeechaTextForConditionalGeneration(__lowerCAmelCase ) A__ : Optional[Any] = model.model.load_state_dict(__lowerCAmelCase, strict=__lowerCAmelCase ) if len(__lowerCAmelCase ) > 0 and not set(__lowerCAmelCase ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,""" f' but all the following weights are missing {missing}' ) if tie_embeds: A__ : Optional[int] = make_linear_from_emb(model.model.decoder.embed_tokens ) else: A__ : int = lm_head_weights model.save_pretrained(__lowerCAmelCase ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument('''--fairseq_path''', type=str, help='''Path to the fairseq model (.pt) file.''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') A_ = parser.parse_args() convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)
362
"""simple docstring""" import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py A_ = '''src/diffusers''' A_ = '''.''' # This is to make sure the diffusers module imported is the one in the repo. A_ = importlib.util.spec_from_file_location( '''diffusers''', os.path.join(DIFFUSERS_PATH, '''__init__.py'''), submodule_search_locations=[DIFFUSERS_PATH], ) A_ = spec.loader.load_module() def _lowerCAmelCase ( UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : Optional[Any] ) ->Any: return line.startswith(UpperCAmelCase__ ) or len(UpperCAmelCase__ ) <= 1 or re.search(R"""^\s*\)(\s*->.*:|:)\s*$""", UpperCAmelCase__ ) is not None def _lowerCAmelCase ( UpperCAmelCase__ : List[str] ) ->Union[str, Any]: A__ : Any = object_name.split(""".""" ) A__ : int = 0 # First let's find the module where our object lives. A__ : str = parts[i] while i < len(UpperCAmelCase__ ) and not os.path.isfile(os.path.join(UpperCAmelCase__, f'{module}.py' ) ): i += 1 if i < len(UpperCAmelCase__ ): A__ : Union[str, Any] = os.path.join(UpperCAmelCase__, parts[i] ) if i >= len(UpperCAmelCase__ ): raise ValueError(f'`object_name` should begin with the name of a module of diffusers but got {object_name}.' ) with open(os.path.join(UpperCAmelCase__, f'{module}.py' ), """r""", encoding="""utf-8""", newline="""\n""" ) as f: A__ : List[Any] = f.readlines() # Now let's find the class / func in the code! A__ : Optional[Any] = """""" A__ : Any = 0 for name in parts[i + 1 :]: while ( line_index < len(UpperCAmelCase__ ) and re.search(Rf'^{indent}(class|def)\s+{name}(\(|\:)', lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(UpperCAmelCase__ ): raise ValueError(f' {object_name} does not match any function or class in {module}.' ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). A__ : List[Any] = line_index while line_index < len(UpperCAmelCase__ ) and _should_continue(lines[line_index], UpperCAmelCase__ ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 A__ : List[Any] = lines[start_index:line_index] return "".join(UpperCAmelCase__ ) A_ = re.compile(r'''^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)''') A_ = re.compile(r'''^\s*(\S+)->(\S+)(\s+.*|$)''') A_ = re.compile(r'''<FILL\s+[^>]*>''') def _lowerCAmelCase ( UpperCAmelCase__ : List[str] ) ->Optional[Any]: A__ : Dict = code.split("""\n""" ) A__ : List[Any] = 0 while idx < len(UpperCAmelCase__ ) and len(lines[idx] ) == 0: idx += 1 if idx < len(UpperCAmelCase__ ): return re.search(R"""^(\s*)\S""", lines[idx] ).groups()[0] return "" def _lowerCAmelCase ( UpperCAmelCase__ : Optional[Any] ) ->int: A__ : str = len(get_indent(UpperCAmelCase__ ) ) > 0 if has_indent: A__ : Union[str, Any] = f'class Bla:\n{code}' A__ : Optional[Any] = black.Mode(target_versions={black.TargetVersion.PYaa}, line_length=1_1_9, preview=UpperCAmelCase__ ) A__ : Tuple = black.format_str(UpperCAmelCase__, mode=UpperCAmelCase__ ) A__ , A__ : List[Any] = style_docstrings_in_code(UpperCAmelCase__ ) return result[len("""class Bla:\n""" ) :] if has_indent else result def _lowerCAmelCase ( UpperCAmelCase__ : Any, UpperCAmelCase__ : Dict=False ) ->List[Any]: with open(UpperCAmelCase__, """r""", encoding="""utf-8""", newline="""\n""" ) as f: A__ : int = f.readlines() A__ : Dict = [] A__ : List[str] = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(UpperCAmelCase__ ): A__ : Dict = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. A__ , A__ , A__ : Dict = search.groups() A__ : Tuple = find_code_in_diffusers(UpperCAmelCase__ ) A__ : int = get_indent(UpperCAmelCase__ ) A__ : List[str] = line_index + 1 if indent == theoretical_indent else line_index + 2 A__ : Tuple = theoretical_indent A__ : Optional[Any] = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. A__ : Tuple = True while line_index < len(UpperCAmelCase__ ) and should_continue: line_index += 1 if line_index >= len(UpperCAmelCase__ ): break A__ : Optional[int] = lines[line_index] A__ : Tuple = _should_continue(UpperCAmelCase__, UpperCAmelCase__ ) and re.search(f'^{indent}# End copy', UpperCAmelCase__ ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 A__ : Dict = lines[start_index:line_index] A__ : Tuple = """""".join(UpperCAmelCase__ ) # Remove any nested `Copied from` comments to avoid circular copies A__ : Optional[int] = [line for line in theoretical_code.split("""\n""" ) if _re_copy_warning.search(UpperCAmelCase__ ) is None] A__ : Optional[Any] = """\n""".join(UpperCAmelCase__ ) # Before comparing, use the `replace_pattern` on the original code. if len(UpperCAmelCase__ ) > 0: A__ : int = replace_pattern.replace("""with""", """""" ).split(""",""" ) A__ : List[Any] = [_re_replace_pattern.search(UpperCAmelCase__ ) for p in patterns] for pattern in patterns: if pattern is None: continue A__ , A__ , A__ : Union[str, Any] = pattern.groups() A__ : Union[str, Any] = re.sub(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) if option.strip() == "all-casing": A__ : List[Any] = re.sub(obja.lower(), obja.lower(), UpperCAmelCase__ ) A__ : Tuple = re.sub(obja.upper(), obja.upper(), UpperCAmelCase__ ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line A__ : Optional[int] = blackify(lines[start_index - 1] + theoretical_code ) A__ : List[Any] = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: A__ : List[Any] = lines[:start_index] + [theoretical_code] + lines[line_index:] A__ : Tuple = start_index + 1 if overwrite and len(UpperCAmelCase__ ) > 0: # Warn the user a file has been modified. print(f'Detected changes, rewriting {filename}.' ) with open(UpperCAmelCase__, """w""", encoding="""utf-8""", newline="""\n""" ) as f: f.writelines(UpperCAmelCase__ ) return diffs def _lowerCAmelCase ( UpperCAmelCase__ : bool = False ) ->Any: A__ : Dict = glob.glob(os.path.join(UpperCAmelCase__, """**/*.py""" ), recursive=UpperCAmelCase__ ) A__ : str = [] for filename in all_files: A__ : Any = is_copy_consistent(UpperCAmelCase__, UpperCAmelCase__ ) diffs += [f'- {filename}: copy does not match {d[0]} at line {d[1]}' for d in new_diffs] if not overwrite and len(UpperCAmelCase__ ) > 0: A__ : Any = """\n""".join(UpperCAmelCase__ ) raise Exception( """Found the following copy inconsistencies:\n""" + diff + """\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.""" ) if __name__ == "__main__": A_ = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') A_ = parser.parse_args() check_copies(args.fix_and_overwrite)
296
0
"""simple docstring""" import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) A_ = { 'sample_size': 32, 'in_channels': 3, 'out_channels': 3, 'layers_per_block': 2, 'num_class_embeds': 1000, 'block_out_channels': [32, 64], 'attention_head_dim': 8, 'down_block_types': [ 'ResnetDownsampleBlock2D', 'AttnDownBlock2D', ], 'up_block_types': [ 'AttnUpBlock2D', 'ResnetUpsampleBlock2D', ], 'resnet_time_scale_shift': 'scale_shift', 'upsample_type': 'resnet', 'downsample_type': 'resnet', } A_ = { 'sample_size': 64, 'in_channels': 3, 'out_channels': 3, 'layers_per_block': 3, 'num_class_embeds': 1000, 'block_out_channels': [192, 192 * 2, 192 * 3, 192 * 4], 'attention_head_dim': 64, 'down_block_types': [ 'ResnetDownsampleBlock2D', 'AttnDownBlock2D', 'AttnDownBlock2D', 'AttnDownBlock2D', ], 'up_block_types': [ 'AttnUpBlock2D', 'AttnUpBlock2D', 'AttnUpBlock2D', 'ResnetUpsampleBlock2D', ], 'resnet_time_scale_shift': 'scale_shift', 'upsample_type': 'resnet', 'downsample_type': 'resnet', } A_ = { 'sample_size': 256, 'in_channels': 3, 'out_channels': 3, 'layers_per_block': 2, 'num_class_embeds': None, 'block_out_channels': [256, 256, 256 * 2, 256 * 2, 256 * 4, 256 * 4], 'attention_head_dim': 64, 'down_block_types': [ 'ResnetDownsampleBlock2D', 'ResnetDownsampleBlock2D', 'ResnetDownsampleBlock2D', 'AttnDownBlock2D', 'AttnDownBlock2D', 'AttnDownBlock2D', ], 'up_block_types': [ 'AttnUpBlock2D', 'AttnUpBlock2D', 'AttnUpBlock2D', 'ResnetUpsampleBlock2D', 'ResnetUpsampleBlock2D', 'ResnetUpsampleBlock2D', ], 'resnet_time_scale_shift': 'default', 'upsample_type': 'resnet', 'downsample_type': 'resnet', } A_ = { 'num_train_timesteps': 40, 'sigma_min': 0.002, 'sigma_max': 80.0, } A_ = { 'num_train_timesteps': 201, 'sigma_min': 0.002, 'sigma_max': 80.0, } A_ = { 'num_train_timesteps': 151, 'sigma_min': 0.002, 'sigma_max': 80.0, } def _lowerCAmelCase ( UpperCAmelCase__ : Any ) ->Tuple: if isinstance(lowercase__, lowercase__ ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise argparse.ArgumentTypeError("""boolean value expected""" ) def _lowerCAmelCase ( UpperCAmelCase__ : Any, UpperCAmelCase__ : str, UpperCAmelCase__ : Any, UpperCAmelCase__ : Dict, UpperCAmelCase__ : str=False ) ->Optional[int]: A__ : List[str] = checkpoint[f'{old_prefix}.in_layers.0.weight'] A__ : Optional[int] = checkpoint[f'{old_prefix}.in_layers.0.bias'] A__ : List[Any] = checkpoint[f'{old_prefix}.in_layers.2.weight'] A__ : str = checkpoint[f'{old_prefix}.in_layers.2.bias'] A__ : Union[str, Any] = checkpoint[f'{old_prefix}.emb_layers.1.weight'] A__ : str = checkpoint[f'{old_prefix}.emb_layers.1.bias'] A__ : Optional[int] = checkpoint[f'{old_prefix}.out_layers.0.weight'] A__ : Dict = checkpoint[f'{old_prefix}.out_layers.0.bias'] A__ : List[str] = checkpoint[f'{old_prefix}.out_layers.3.weight'] A__ : Union[str, Any] = checkpoint[f'{old_prefix}.out_layers.3.bias'] if has_skip: A__ : Dict = checkpoint[f'{old_prefix}.skip_connection.weight'] A__ : Union[str, Any] = checkpoint[f'{old_prefix}.skip_connection.bias'] return new_checkpoint def _lowerCAmelCase ( UpperCAmelCase__ : Tuple, UpperCAmelCase__ : int, UpperCAmelCase__ : Tuple, UpperCAmelCase__ : Union[str, Any], UpperCAmelCase__ : str=None ) ->Any: A__ , A__ , A__ : Union[str, Any] = checkpoint[f'{old_prefix}.qkv.weight'].chunk(3, dim=0 ) A__ , A__ , A__ : Optional[Any] = checkpoint[f'{old_prefix}.qkv.bias'].chunk(3, dim=0 ) A__ : List[Any] = checkpoint[f'{old_prefix}.norm.weight'] A__ : Tuple = checkpoint[f'{old_prefix}.norm.bias'] A__ : List[str] = weight_q.squeeze(-1 ).squeeze(-1 ) A__ : str = bias_q.squeeze(-1 ).squeeze(-1 ) A__ : Tuple = weight_k.squeeze(-1 ).squeeze(-1 ) A__ : List[Any] = bias_k.squeeze(-1 ).squeeze(-1 ) A__ : Tuple = weight_v.squeeze(-1 ).squeeze(-1 ) A__ : Dict = bias_v.squeeze(-1 ).squeeze(-1 ) A__ : List[Any] = ( checkpoint[f'{old_prefix}.proj_out.weight'].squeeze(-1 ).squeeze(-1 ) ) A__ : Union[str, Any] = checkpoint[f'{old_prefix}.proj_out.bias'].squeeze(-1 ).squeeze(-1 ) return new_checkpoint def _lowerCAmelCase ( UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : List[str] ) ->Optional[int]: A__ : Optional[int] = torch.load(lowercase__, map_location="""cpu""" ) A__ : Any = {} A__ : Tuple = checkpoint["""time_embed.0.weight"""] A__ : Optional[Any] = checkpoint["""time_embed.0.bias"""] A__ : Tuple = checkpoint["""time_embed.2.weight"""] A__ : Optional[int] = checkpoint["""time_embed.2.bias"""] if unet_config["num_class_embeds"] is not None: A__ : List[Any] = checkpoint["""label_emb.weight"""] A__ : Tuple = checkpoint["""input_blocks.0.0.weight"""] A__ : Dict = checkpoint["""input_blocks.0.0.bias"""] A__ : List[str] = unet_config["""down_block_types"""] A__ : Dict = unet_config["""layers_per_block"""] A__ : Dict = unet_config["""attention_head_dim"""] A__ : Union[str, Any] = unet_config["""block_out_channels"""] A__ : int = 1 A__ : Optional[Any] = channels_list[0] for i, layer_type in enumerate(lowercase__ ): A__ : int = channels_list[i] A__ : Optional[Any] = current_channels != prev_channels if layer_type == "ResnetDownsampleBlock2D": for j in range(lowercase__ ): A__ : int = f'down_blocks.{i}.resnets.{j}' A__ : Optional[Any] = f'input_blocks.{current_layer}.0' A__ : Optional[int] = True if j == 0 and downsample_block_has_skip else False A__ : Optional[Any] = convert_resnet(lowercase__, lowercase__, lowercase__, lowercase__, has_skip=lowercase__ ) current_layer += 1 elif layer_type == "AttnDownBlock2D": for j in range(lowercase__ ): A__ : Tuple = f'down_blocks.{i}.resnets.{j}' A__ : List[str] = f'input_blocks.{current_layer}.0' A__ : Any = True if j == 0 and downsample_block_has_skip else False A__ : Tuple = convert_resnet(lowercase__, lowercase__, lowercase__, lowercase__, has_skip=lowercase__ ) A__ : str = f'down_blocks.{i}.attentions.{j}' A__ : str = f'input_blocks.{current_layer}.1' A__ : Tuple = convert_attention( lowercase__, lowercase__, lowercase__, lowercase__, lowercase__ ) current_layer += 1 if i != len(lowercase__ ) - 1: A__ : str = f'down_blocks.{i}.downsamplers.0' A__ : Tuple = f'input_blocks.{current_layer}.0' A__ : str = convert_resnet(lowercase__, lowercase__, lowercase__, lowercase__ ) current_layer += 1 A__ : Tuple = current_channels # hardcoded the mid-block for now A__ : Optional[int] = """mid_block.resnets.0""" A__ : Tuple = """middle_block.0""" A__ : Dict = convert_resnet(lowercase__, lowercase__, lowercase__, lowercase__ ) A__ : Tuple = """mid_block.attentions.0""" A__ : str = """middle_block.1""" A__ : List[str] = convert_attention(lowercase__, lowercase__, lowercase__, lowercase__, lowercase__ ) A__ : Any = """mid_block.resnets.1""" A__ : int = """middle_block.2""" A__ : Tuple = convert_resnet(lowercase__, lowercase__, lowercase__, lowercase__ ) A__ : Optional[Any] = 0 A__ : str = unet_config["""up_block_types"""] for i, layer_type in enumerate(lowercase__ ): if layer_type == "ResnetUpsampleBlock2D": for j in range(layers_per_block + 1 ): A__ : Tuple = f'up_blocks.{i}.resnets.{j}' A__ : str = f'output_blocks.{current_layer}.0' A__ : Union[str, Any] = convert_resnet(lowercase__, lowercase__, lowercase__, lowercase__, has_skip=lowercase__ ) current_layer += 1 if i != len(lowercase__ ) - 1: A__ : List[Any] = f'up_blocks.{i}.upsamplers.0' A__ : Any = f'output_blocks.{current_layer-1}.1' A__ : List[Any] = convert_resnet(lowercase__, lowercase__, lowercase__, lowercase__ ) elif layer_type == "AttnUpBlock2D": for j in range(layers_per_block + 1 ): A__ : List[str] = f'up_blocks.{i}.resnets.{j}' A__ : Union[str, Any] = f'output_blocks.{current_layer}.0' A__ : Dict = convert_resnet(lowercase__, lowercase__, lowercase__, lowercase__, has_skip=lowercase__ ) A__ : Any = f'up_blocks.{i}.attentions.{j}' A__ : str = f'output_blocks.{current_layer}.1' A__ : Optional[Any] = convert_attention( lowercase__, lowercase__, lowercase__, lowercase__, lowercase__ ) current_layer += 1 if i != len(lowercase__ ) - 1: A__ : int = f'up_blocks.{i}.upsamplers.0' A__ : List[str] = f'output_blocks.{current_layer-1}.2' A__ : Union[str, Any] = convert_resnet(lowercase__, lowercase__, lowercase__, lowercase__ ) A__ : Any = checkpoint["""out.0.weight"""] A__ : Optional[Any] = checkpoint["""out.0.bias"""] A__ : Any = checkpoint["""out.2.weight"""] A__ : List[Any] = checkpoint["""out.2.bias"""] return new_checkpoint if __name__ == "__main__": A_ = argparse.ArgumentParser() parser.add_argument('''--unet_path''', default=None, type=str, required=True, help='''Path to the unet.pt to convert.''') parser.add_argument( '''--dump_path''', default=None, type=str, required=True, help='''Path to output the converted UNet model.''' ) parser.add_argument('''--class_cond''', default=True, type=str, help='''Whether the model is class-conditional.''') A_ = parser.parse_args() A_ = strabool(args.class_cond) A_ = os.path.basename(args.unet_path) print(F'Checkpoint: {ckpt_name}') # Get U-Net config if "imagenet64" in ckpt_name: A_ = IMAGENET_64_UNET_CONFIG elif "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): A_ = LSUN_256_UNET_CONFIG elif "test" in ckpt_name: A_ = TEST_UNET_CONFIG else: raise ValueError(F'Checkpoint type {ckpt_name} is not currently supported.') if not args.class_cond: A_ = None A_ = con_pt_to_diffuser(args.unet_path, unet_config) A_ = UNetaDModel(**unet_config) image_unet.load_state_dict(converted_unet_ckpt) # Get scheduler config if "cd" in ckpt_name or "test" in ckpt_name: A_ = CD_SCHEDULER_CONFIG elif "ct" in ckpt_name and "imagenet64" in ckpt_name: A_ = CT_IMAGENET_64_SCHEDULER_CONFIG elif "ct" in ckpt_name and "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): A_ = CT_LSUN_256_SCHEDULER_CONFIG else: raise ValueError(F'Checkpoint type {ckpt_name} is not currently supported.') A_ = CMStochasticIterativeScheduler(**scheduler_config) A_ = ConsistencyModelPipeline(unet=image_unet, scheduler=cm_scheduler) consistency_model.save_pretrained(args.dump_path)
363
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) A_ = { '''configuration_llama''': ['''LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LlamaConfig'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ['''LlamaTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ['''LlamaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''LlamaForCausalLM''', '''LlamaModel''', '''LlamaPreTrainedModel''', '''LlamaForSequenceClassification''', ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
296
0
"""simple docstring""" import unittest from transformers import AutoTokenizer, NystromformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerModel, ) from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST class __SCREAMING_SNAKE_CASE : def __init__( self : List[Any] , snake_case : List[str] , snake_case : List[str]=13 , snake_case : List[Any]=7 , snake_case : Any=True , snake_case : int=True , snake_case : Optional[Any]=True , snake_case : Tuple=True , snake_case : Optional[int]=99 , snake_case : str=32 , snake_case : Optional[int]=5 , snake_case : List[Any]=4 , snake_case : List[Any]=37 , snake_case : Optional[Any]="gelu" , snake_case : Dict=0.1 , snake_case : Optional[int]=0.1 , snake_case : Any=512 , snake_case : Dict=16 , snake_case : List[Any]=2 , snake_case : Union[str, Any]=0.02 , snake_case : List[Any]=3 , snake_case : str=4 , snake_case : Optional[int]=None , ): '''simple docstring''' A__ : Optional[Any] = parent A__ : Optional[int] = batch_size A__ : List[Any] = seq_length A__ : List[str] = is_training A__ : Any = use_input_mask A__ : Union[str, Any] = use_token_type_ids A__ : Tuple = use_labels A__ : Any = vocab_size A__ : Tuple = hidden_size A__ : int = num_hidden_layers A__ : Union[str, Any] = num_attention_heads A__ : int = intermediate_size A__ : str = hidden_act A__ : Optional[int] = hidden_dropout_prob A__ : Union[str, Any] = attention_probs_dropout_prob A__ : Dict = max_position_embeddings A__ : str = type_vocab_size A__ : Union[str, Any] = type_sequence_label_size A__ : Dict = initializer_range A__ : Dict = num_labels A__ : List[str] = num_choices A__ : List[str] = scope def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Optional[Any] = None if self.use_input_mask: A__ : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) A__ : List[str] = None if self.use_token_type_ids: A__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A__ : List[str] = None A__ : int = None A__ : str = None if self.use_labels: A__ : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : Optional[int] = ids_tensor([self.batch_size] , self.num_choices ) A__ : List[str] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return NystromformerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) def _UpperCamelCase ( self : Dict , snake_case : Any , snake_case : List[str] , snake_case : int , snake_case : List[Any] , snake_case : Tuple , snake_case : int , snake_case : List[str] ): '''simple docstring''' A__ : List[str] = NystromformerModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() A__ : Tuple = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE ) A__ : List[str] = model(_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE ) A__ : Optional[int] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : List[str] , snake_case : Union[str, Any] , snake_case : List[str] , snake_case : Any , snake_case : Dict , snake_case : Optional[Any] , snake_case : Any , snake_case : Union[str, Any] ): '''simple docstring''' A__ : Union[str, Any] = NystromformerForMaskedLM(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() A__ : List[Any] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCamelCase ( self : Tuple , snake_case : int , snake_case : Tuple , snake_case : Union[str, Any] , snake_case : List[str] , snake_case : int , snake_case : Optional[Any] , snake_case : int ): '''simple docstring''' A__ : Tuple = NystromformerForQuestionAnswering(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() A__ : Union[str, Any] = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , start_positions=_SCREAMING_SNAKE_CASE , end_positions=_SCREAMING_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 _UpperCamelCase ( self : Any , snake_case : Optional[int] , snake_case : List[Any] , snake_case : Optional[int] , snake_case : Tuple , snake_case : int , snake_case : Dict , snake_case : Union[str, Any] ): '''simple docstring''' A__ : List[Any] = self.num_labels A__ : List[str] = NystromformerForSequenceClassification(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() A__ : Tuple = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _UpperCamelCase ( self : Tuple , snake_case : int , snake_case : str , snake_case : Tuple , snake_case : Dict , snake_case : Union[str, Any] , snake_case : List[str] , snake_case : Any ): '''simple docstring''' A__ : Union[str, Any] = self.num_labels A__ : Tuple = NystromformerForTokenClassification(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() A__ : Dict = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self : Dict , snake_case : List[str] , snake_case : Any , snake_case : Optional[Any] , snake_case : int , snake_case : str , snake_case : int , snake_case : Tuple ): '''simple docstring''' A__ : List[str] = self.num_choices A__ : int = NystromformerForMultipleChoice(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() A__ : Any = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : Optional[int] = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : int = self.prepare_config_and_inputs() ( A__ ) : List[Any] = config_and_inputs A__ : Any = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): snake_case_ = ( ( NystromformerModel, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, ) if is_torch_available() else () ) snake_case_ = ( { 'feature-extraction': NystromformerModel, 'fill-mask': NystromformerForMaskedLM, 'question-answering': NystromformerForQuestionAnswering, 'text-classification': NystromformerForSequenceClassification, 'token-classification': NystromformerForTokenClassification, 'zero-shot': NystromformerForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = False snake_case_ = False def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Tuple = NystromformerModelTester(self ) A__ : Union[str, Any] = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A__ : Optional[Any] = type self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_SCREAMING_SNAKE_CASE ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_SCREAMING_SNAKE_CASE ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_SCREAMING_SNAKE_CASE ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_SCREAMING_SNAKE_CASE ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_SCREAMING_SNAKE_CASE ) @slow def _UpperCamelCase ( self : Any ): '''simple docstring''' for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ : Any = NystromformerModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : Any = NystromformerModel.from_pretrained("""uw-madison/nystromformer-512""" ) A__ : Dict = torch.tensor([[0, 1, 2, 3, 4, 5]] ) with torch.no_grad(): A__ : str = model(_SCREAMING_SNAKE_CASE )[0] A__ : str = torch.Size((1, 6, 768) ) self.assertEqual(output.shape , _SCREAMING_SNAKE_CASE ) A__ : str = torch.tensor( [[[-0.4532, -0.0936, 0.5137], [-0.2676, 0.0628, 0.6186], [-0.3629, -0.1726, 0.4716]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @slow def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : Any = "the [MASK] of Belgium is Brussels" A__ : Union[str, Any] = AutoTokenizer.from_pretrained("""uw-madison/nystromformer-512""" ) A__ : List[str] = NystromformerForMaskedLM.from_pretrained("""uw-madison/nystromformer-512""" ) A__ : Dict = tokenizer(_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) with torch.no_grad(): A__ : str = model(encoding.input_ids ).logits A__ : Any = token_logits[:, 2, :].argmax(-1 )[0] self.assertEqual(tokenizer.decode(_SCREAMING_SNAKE_CASE ) , """capital""" )
364
"""simple docstring""" import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels A_ = object() # For specifying empty leaf dict `{}` A_ = object() def _lowerCAmelCase ( UpperCAmelCase__ : Tuple, UpperCAmelCase__ : List[Any] ) ->Dict: A__ : Union[str, Any] = tuple((re.compile(x + """$""" ) for x in qs) ) for i in range(len(UpperCAmelCase__ ) - len(UpperCAmelCase__ ) + 1 ): A__ : Optional[Any] = [x.match(UpperCAmelCase__ ) for x, y in zip(UpperCAmelCase__, ks[i:] )] if matches and all(UpperCAmelCase__ ): return True return False def _lowerCAmelCase ( UpperCAmelCase__ : List[Any] ) ->Dict: def replace(UpperCAmelCase__ : int, UpperCAmelCase__ : List[str] ): for rule, replacement in rules: if _match(UpperCAmelCase__, UpperCAmelCase__ ): return replacement return val return replace def _lowerCAmelCase ( ) ->Tuple: return [ # embeddings (("transformer", "wpe", "embedding"), P("""mp""", UpperCAmelCase__ )), (("transformer", "wte", "embedding"), P("""mp""", UpperCAmelCase__ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(UpperCAmelCase__, """mp""" )), (("attention", "out_proj", "kernel"), P("""mp""", UpperCAmelCase__ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(UpperCAmelCase__, """mp""" )), (("mlp", "c_fc", "bias"), P("""mp""" )), (("mlp", "c_proj", "kernel"), P("""mp""", UpperCAmelCase__ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def _lowerCAmelCase ( UpperCAmelCase__ : Tuple ) ->Any: A__ : Union[str, Any] = _get_partition_rules() A__ : int = _replacement_rules(UpperCAmelCase__ ) A__ : Tuple = {k: _unmatched for k in flatten_dict(UpperCAmelCase__ )} A__ : Optional[int] = {k: replace(UpperCAmelCase__, UpperCAmelCase__ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(UpperCAmelCase__ ) )
296
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 __SCREAMING_SNAKE_CASE : @staticmethod def _UpperCamelCase ( *snake_case : List[Any] , **snake_case : Tuple ): '''simple docstring''' pass def _lowerCAmelCase ( UpperCAmelCase__ : Image ) ->List[Any]: A__ : Tuple = hashlib.mda(image.tobytes() ) return m.hexdigest() @is_pipeline_test @require_vision @require_timm @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): snake_case_ = MODEL_FOR_DEPTH_ESTIMATION_MAPPING def _UpperCamelCase ( self : Dict , snake_case : Union[str, Any] , snake_case : Optional[int] , snake_case : Union[str, Any] ): '''simple docstring''' A__ : Union[str, Any] = DepthEstimationPipeline(model=lowerCamelCase_ , image_processor=lowerCamelCase_ ) return depth_estimator, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def _UpperCamelCase ( self : Tuple , snake_case : Tuple , snake_case : str ): '''simple docstring''' A__ : Tuple = depth_estimator("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) self.assertEqual({"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )} , lowerCamelCase_ ) import datasets A__ : Union[str, Any] = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) A__ : List[str] = 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 )}, ] , lowerCamelCase_ , ) @require_tf @unittest.skip("""Depth estimation is not implemented in TF""" ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' pass @slow @require_torch def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Optional[int] = """Intel/dpt-large""" A__ : str = pipeline("""depth-estimation""" , model=lowerCamelCase_ ) A__ : Dict = depth_estimator("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) A__ : Dict = 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 : List[str] ): '''simple docstring''' self.skipTest("""There is not hf-internal-testing tiny model for either GLPN nor DPT""" )
365
"""simple docstring""" import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class __SCREAMING_SNAKE_CASE : def __init__( self : List[str] , snake_case : Tuple , snake_case : List[str]=2 , snake_case : List[str]=8 , snake_case : List[Any]=True , snake_case : Optional[Any]=True , snake_case : List[Any]=True , snake_case : Dict=True , snake_case : Tuple=99 , snake_case : Dict=16 , snake_case : Dict=5 , snake_case : int=2 , snake_case : Any=36 , snake_case : str="gelu" , snake_case : Dict=0.0 , snake_case : List[Any]=0.0 , snake_case : int=512 , snake_case : List[Any]=16 , snake_case : Tuple=2 , snake_case : Any=0.02 , snake_case : Optional[Any]=3 , snake_case : List[Any]=4 , snake_case : str=None , ): '''simple docstring''' A__ : Union[str, Any] = parent A__ : Optional[Any] = batch_size A__ : Dict = seq_length A__ : str = is_training A__ : Tuple = use_input_mask A__ : Dict = use_token_type_ids A__ : Dict = use_labels A__ : int = vocab_size A__ : List[str] = hidden_size A__ : Union[str, Any] = num_hidden_layers A__ : int = num_attention_heads A__ : List[str] = intermediate_size A__ : int = hidden_act A__ : str = hidden_dropout_prob A__ : Tuple = attention_probs_dropout_prob A__ : Any = max_position_embeddings A__ : Optional[int] = type_vocab_size A__ : int = type_sequence_label_size A__ : Optional[Any] = initializer_range A__ : int = num_labels A__ : Optional[int] = num_choices A__ : Optional[int] = scope def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Any = None if self.use_input_mask: A__ : Any = random_attention_mask([self.batch_size, self.seq_length] ) A__ : Optional[int] = None if self.use_token_type_ids: A__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A__ : Dict = None A__ : List[str] = None A__ : Union[str, Any] = None if self.use_labels: A__ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : Any = ids_tensor([self.batch_size] , self.num_choices ) A__ : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case , initializer_range=self.initializer_range , ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Any = self.get_config() A__ : List[str] = 300 return config def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) : Tuple = self.prepare_config_and_inputs() A__ : List[str] = True A__ : List[str] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) A__ : int = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def _UpperCamelCase ( self : Any , snake_case : Any , snake_case : Tuple , snake_case : Any , snake_case : Optional[int] , snake_case : Optional[int] , snake_case : Optional[int] , snake_case : Dict ): '''simple docstring''' A__ : List[str] = MraModel(config=snake_case ) model.to(snake_case ) model.eval() A__ : Dict = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case ) A__ : List[str] = model(snake_case , token_type_ids=snake_case ) A__ : Union[str, Any] = model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : Optional[Any] , snake_case : List[Any] , snake_case : Any , snake_case : Optional[Any] , snake_case : Union[str, Any] , snake_case : Tuple , snake_case : Dict , snake_case : str , snake_case : Dict , snake_case : str , ): '''simple docstring''' A__ : Dict = True A__ : Optional[Any] = MraModel(snake_case ) model.to(snake_case ) model.eval() A__ : Union[str, Any] = model( snake_case , attention_mask=snake_case , token_type_ids=snake_case , encoder_hidden_states=snake_case , encoder_attention_mask=snake_case , ) A__ : str = model( snake_case , attention_mask=snake_case , token_type_ids=snake_case , encoder_hidden_states=snake_case , ) A__ : Optional[int] = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : int , snake_case : Optional[Any] , snake_case : Optional[int] , snake_case : int , snake_case : str , snake_case : Union[str, Any] , snake_case : Dict , snake_case : List[str] ): '''simple docstring''' A__ : Union[str, Any] = MraForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() A__ : List[Any] = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Dict , snake_case : Dict , snake_case : Dict , snake_case : List[str] , snake_case : List[str] , snake_case : Tuple , snake_case : Union[str, Any] ): '''simple docstring''' A__ : Dict = MraForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() A__ : str = model( 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 _UpperCamelCase ( self : Tuple , snake_case : List[Any] , snake_case : Optional[Any] , snake_case : Optional[Any] , snake_case : List[str] , snake_case : Optional[int] , snake_case : List[str] , snake_case : Union[str, Any] ): '''simple docstring''' A__ : str = self.num_labels A__ : Optional[Any] = MraForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : str = model(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 _UpperCamelCase ( self : Union[str, Any] , snake_case : Dict , snake_case : str , snake_case : List[Any] , snake_case : Any , snake_case : Dict , snake_case : Tuple , snake_case : Optional[Any] ): '''simple docstring''' A__ : str = self.num_labels A__ : Union[str, Any] = MraForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() A__ : str = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self : Tuple , snake_case : Optional[Any] , snake_case : Optional[int] , snake_case : int , snake_case : Optional[Any] , snake_case : List[str] , snake_case : Dict , snake_case : Optional[Any] ): '''simple docstring''' A__ : List[str] = self.num_choices A__ : str = MraForMultipleChoice(config=snake_case ) model.to(snake_case ) model.eval() A__ : int = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : str = model( 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_choices) ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : List[str] = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) : Dict = config_and_inputs A__ : Optional[int] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( UpperCamelCase , unittest.TestCase ): snake_case_ = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = () def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Optional[Any] = MraModelTester(self ) A__ : List[str] = ConfigTester(self , config_class=snake_case , hidden_size=37 ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A__ : List[str] = type self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case ) @slow def _UpperCamelCase ( self : Any ): '''simple docstring''' for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ : str = MraModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @unittest.skip(reason="""MRA does not output attentions""" ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' return @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : str = MraModel.from_pretrained("""uw-madison/mra-base-512-4""" ) A__ : Any = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): A__ : List[Any] = model(snake_case )[0] A__ : List[Any] = torch.Size((1, 256, 768) ) self.assertEqual(output.shape , snake_case ) A__ : int = torch.tensor( [[[-0.0140, 0.0830, -0.0381], [0.1546, 0.1402, 0.0220], [0.1162, 0.0851, 0.0165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) ) @slow def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : Union[str, Any] = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-512-4""" ) A__ : Tuple = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): A__ : List[Any] = model(snake_case )[0] A__ : Dict = 5_0265 A__ : List[str] = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape , snake_case ) A__ : List[Any] = torch.tensor( [[[9.2595, -3.6038, 11.8819], [9.3869, -3.2693, 11.0956], [11.8524, -3.4938, 13.1210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) ) @slow def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : Any = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-4096-8-d3""" ) A__ : List[Any] = torch.arange(4096 ).unsqueeze(0 ) with torch.no_grad(): A__ : List[Any] = model(snake_case )[0] A__ : Union[str, Any] = 5_0265 A__ : Optional[Any] = torch.Size((1, 4096, vocab_size) ) self.assertEqual(output.shape , snake_case ) A__ : Optional[int] = torch.tensor( [[[5.4789, -2.3564, 7.5064], [7.9067, -1.3369, 9.9668], [9.0712, -1.8106, 7.0380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) )
296
0
from typing import List import datasets from datasets.tasks import AudioClassification from ..folder_based_builder import folder_based_builder A_ = datasets.utils.logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE ( folder_based_builder.FolderBasedBuilderConfig ): snake_case_ = None snake_case_ = None class __SCREAMING_SNAKE_CASE ( folder_based_builder.FolderBasedBuilder ): snake_case_ = datasets.Audio() snake_case_ = """audio""" snake_case_ = AudioFolderConfig snake_case_ = 42 # definition at the bottom of the script snake_case_ = AudioClassification(audio_column='audio' , label_column='label' ) A_ = [ """.aiff""", """.au""", """.avr""", """.caf""", """.flac""", """.htk""", """.svx""", """.mat4""", """.mat5""", """.mpc2k""", """.ogg""", """.paf""", """.pvf""", """.raw""", """.rf64""", """.sd2""", """.sds""", """.ircam""", """.voc""", """.w64""", """.wav""", """.nist""", """.wavex""", """.wve""", """.xi""", """.mp3""", """.opus""", ] A_ = AUDIO_EXTENSIONS
366
"""simple docstring""" from sklearn.metrics import mean_squared_error import datasets A_ = '''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' A_ = '''\ Mean Squared Error(MSE) is the average of the square of difference between the predicted and actual values. ''' A_ = ''' Args: predictions: array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. references: array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. sample_weight: array-like of shape (n_samples,), default=None Sample weights. multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average" Defines aggregating of multiple output values. Array-like value defines weights used to average errors. "raw_values" : Returns a full set of errors in case of multioutput input. "uniform_average" : Errors of all outputs are averaged with uniform weight. squared : bool, default=True If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value. Returns: mse : mean squared error. Examples: >>> mse_metric = datasets.load_metric("mse") >>> predictions = [2.5, 0.0, 2, 8] >>> references = [3, -0.5, 2, 7] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {\'mse\': 0.375} >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False) >>> print(rmse_result) {\'mse\': 0.6123724356957945} If you\'re using multi-dimensional lists, then set the config as follows : >>> mse_metric = datasets.load_metric("mse", "multilist") >>> predictions = [[0.5, 1], [-1, 1], [7, -6]] >>> references = [[0, 2], [-1, 2], [8, -5]] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {\'mse\': 0.7083333333333334} >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\') >>> print(results) # doctest: +NORMALIZE_WHITESPACE {\'mse\': array([0.41666667, 1. ])} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE ( datasets.Metric ): def _UpperCamelCase ( self : Dict ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html""" ] , ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value("""float""" ) ), "references": datasets.Sequence(datasets.Value("""float""" ) ), } else: return { "predictions": datasets.Value("""float""" ), "references": datasets.Value("""float""" ), } def _UpperCamelCase ( self : List[str] , snake_case : Dict , snake_case : List[Any] , snake_case : List[str]=None , snake_case : List[Any]="uniform_average" , snake_case : int=True ): '''simple docstring''' A__ : Optional[int] = mean_squared_error( snake_case , snake_case , sample_weight=snake_case , multioutput=snake_case , squared=snake_case ) return {"mse": mse}
296
0
"""simple docstring""" from __future__ import annotations class __SCREAMING_SNAKE_CASE : def __init__( self : str , snake_case : int ): '''simple docstring''' A__ : List[str] = data A__ : Union[str, Any] = None A__ : Optional[int] = None def _lowerCAmelCase ( UpperCAmelCase__ : Node | None ) ->Any: # In Order traversal of the tree if tree: display(tree.left ) print(tree.data ) display(tree.right ) def _lowerCAmelCase ( UpperCAmelCase__ : Node | None ) ->List[Any]: return 1 + max(depth_of_tree(tree.left ), depth_of_tree(tree.right ) ) if tree else 0 def _lowerCAmelCase ( UpperCAmelCase__ : Node ) ->List[Any]: if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left ) and is_full_binary_tree(tree.right ) else: return not tree.left and not tree.right def _lowerCAmelCase ( ) ->Dict: # Main function for testing. A__ : Union[str, Any] = Node(1 ) A__ : str = Node(2 ) A__ : List[Any] = Node(3 ) A__ : List[str] = Node(4 ) A__ : List[Any] = Node(5 ) A__ : List[Any] = Node(6 ) A__ : Tuple = Node(7 ) A__ : Optional[int] = Node(8 ) A__ : Any = Node(9 ) print(is_full_binary_tree(SCREAMING_SNAKE_CASE__ ) ) print(depth_of_tree(SCREAMING_SNAKE_CASE__ ) ) print("""Tree is: """ ) display(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
367
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging A_ = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): def __init__( self : Optional[int] , snake_case : List[str]=None , **snake_case : Any ): '''simple docstring''' warnings.warn( """`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` """ """instead.""" , snake_case , ) super().__init__(args=snake_case , **snake_case )
296
0
def _lowerCAmelCase ( UpperCAmelCase__ : int = 1_0**1_2 ) ->int: A__ : Tuple = 1 A__ : str = 0 A__ : Optional[int] = 1 A__ : List[str] = 1 while numerator <= 2 * min_total - 1: prev_numerator += 2 * numerator numerator += 2 * prev_numerator prev_denominator += 2 * denominator denominator += 2 * prev_denominator return (denominator + 1) // 2 if __name__ == "__main__": print(F'{solution() = }')
368
"""simple docstring""" import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch A_ = random.Random() def _lowerCAmelCase ( UpperCAmelCase__ : Dict, UpperCAmelCase__ : Tuple=1.0, UpperCAmelCase__ : Optional[int]=None, UpperCAmelCase__ : str=None ) ->Union[str, Any]: if rng is None: A__ : Optional[int] = global_rng A__ : Optional[Any] = [] 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 __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : Union[str, Any] , snake_case : str , snake_case : List[str]=7 , snake_case : str=400 , snake_case : Optional[Any]=2000 , snake_case : Union[str, Any]=10 , snake_case : str=160 , snake_case : List[str]=8 , snake_case : List[Any]=0.0 , snake_case : Optional[Any]=4000 , snake_case : Any=False , snake_case : int=True , ): '''simple docstring''' A__ : Any = parent A__ : str = batch_size A__ : List[str] = min_seq_length A__ : Dict = max_seq_length A__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) A__ : Dict = padding_value A__ : Optional[Any] = sampling_rate A__ : Any = return_attention_mask A__ : Optional[int] = do_normalize A__ : Tuple = feature_size A__ : Optional[Any] = chunk_length A__ : Union[str, Any] = hop_length def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _UpperCamelCase ( self : Union[str, Any] , snake_case : Dict=False , snake_case : Optional[Any]=False ): '''simple docstring''' def _flatten(snake_case : Dict ): return list(itertools.chain(*snake_case ) ) if equal_length: A__ : Dict = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size A__ : Optional[int] = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: A__ : List[str] = [np.asarray(snake_case ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __SCREAMING_SNAKE_CASE ( UpperCamelCase , unittest.TestCase ): snake_case_ = WhisperFeatureExtractor if is_speech_available() else None def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : str = WhisperFeatureExtractionTester(self ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Any = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: A__ : List[Any] = feat_extract_first.save_pretrained(snake_case )[0] check_json_file_has_correct_format(snake_case ) A__ : Union[str, Any] = self.feature_extraction_class.from_pretrained(snake_case ) A__ : str = feat_extract_first.to_dict() A__ : Union[str, Any] = feat_extract_second.to_dict() A__ : List[Any] = feat_extract_first.mel_filters A__ : Optional[Any] = feat_extract_second.mel_filters self.assertTrue(np.allclose(snake_case , snake_case ) ) self.assertEqual(snake_case , snake_case ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Any = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: A__ : Any = os.path.join(snake_case , """feat_extract.json""" ) feat_extract_first.to_json_file(snake_case ) A__ : int = self.feature_extraction_class.from_json_file(snake_case ) A__ : Dict = feat_extract_first.to_dict() A__ : str = feat_extract_second.to_dict() A__ : str = feat_extract_first.mel_filters A__ : Dict = feat_extract_second.mel_filters self.assertTrue(np.allclose(snake_case , snake_case ) ) self.assertEqual(snake_case , snake_case ) def _UpperCamelCase ( self : Any ): '''simple docstring''' A__ : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 A__ : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] A__ : Union[str, Any] = [np.asarray(snake_case ) for speech_input in speech_inputs] # Test feature size A__ : Dict = feature_extractor(snake_case , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input A__ : str = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features A__ : Optional[int] = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(snake_case , snake_case , atol=1e-3 ) ) # Test batched A__ : List[str] = feature_extractor(snake_case , return_tensors="""np""" ).input_features A__ : List[str] = feature_extractor(snake_case , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(snake_case , snake_case ): self.assertTrue(np.allclose(snake_case , snake_case , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. A__ : Tuple = [floats_list((1, x) )[0] for x in (800, 800, 800)] A__ : str = np.asarray(snake_case ) A__ : List[str] = feature_extractor(snake_case , return_tensors="""np""" ).input_features A__ : Optional[int] = feature_extractor(snake_case , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(snake_case , snake_case ): self.assertTrue(np.allclose(snake_case , snake_case , atol=1e-3 ) ) # Test truncation required A__ : Optional[Any] = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] A__ : Union[str, Any] = [np.asarray(snake_case ) for speech_input in speech_inputs] A__ : Union[str, Any] = [x[: feature_extractor.n_samples] for x in speech_inputs] A__ : str = [np.asarray(snake_case ) for speech_input in speech_inputs_truncated] A__ : Optional[int] = feature_extractor(snake_case , return_tensors="""np""" ).input_features A__ : str = feature_extractor(snake_case , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(snake_case , snake_case ): self.assertTrue(np.allclose(snake_case , snake_case , atol=1e-3 ) ) def _UpperCamelCase ( self : str ): '''simple docstring''' import torch A__ : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A__ : List[str] = np.random.rand(100 , 32 ).astype(np.floataa ) A__ : Tuple = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: A__ : Optional[Any] = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) A__ : Optional[int] = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Optional[int] ): '''simple docstring''' A__ : int = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech A__ : Union[str, Any] = ds.sort("""id""" ).select(range(snake_case ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : str = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on A__ : Optional[Any] = self._load_datasamples(1 ) A__ : Union[str, Any] = WhisperFeatureExtractor() A__ : List[str] = feature_extractor(snake_case , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 80, 3000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , snake_case , atol=1e-4 ) ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A__ : Union[str, Any] = self._load_datasamples(1 )[0] A__ : Any = ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535 # Rescale to [0, 65535] to show issue A__ : str = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=snake_case )[0] self.assertTrue(np.all(np.mean(snake_case ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(snake_case ) - 1 ) < 1e-3 ) )
296
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available A_ = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ['''BartphoTokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
369
"""simple docstring""" import numpy as np class __SCREAMING_SNAKE_CASE : def __init__( self : List[str] ): '''simple docstring''' A__ : Optional[int] = (0, 0) A__ : Dict = None A__ : int = 0 A__ : str = 0 A__ : Optional[Any] = 0 def __eq__( self : str , snake_case : Optional[int] ): '''simple docstring''' return self.position == cell.position def _UpperCamelCase ( self : List[str] ): '''simple docstring''' print(self.position ) class __SCREAMING_SNAKE_CASE : def __init__( self : int , snake_case : Any=(5, 5) ): '''simple docstring''' A__ : Optional[int] = np.zeros(snake_case ) A__ : List[Any] = world_size[0] A__ : Dict = world_size[1] def _UpperCamelCase ( self : Any ): '''simple docstring''' print(self.w ) def _UpperCamelCase ( self : Optional[int] , snake_case : List[Any] ): '''simple docstring''' A__ : int = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] A__ : int = cell.position[0] A__ : str = cell.position[1] A__ : Any = [] for n in neughbour_cord: A__ : List[Any] = current_x + n[0] A__ : Tuple = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: A__ : List[Any] = Cell() A__ : str = (x, y) A__ : Optional[Any] = cell neighbours.append(snake_case ) return neighbours def _lowerCAmelCase ( UpperCAmelCase__ : List[str], UpperCAmelCase__ : Optional[Any], UpperCAmelCase__ : Dict ) ->Dict: A__ : Union[str, Any] = [] A__ : Optional[int] = [] _open.append(UpperCAmelCase__ ) while _open: A__ : List[Any] = np.argmin([n.f for n in _open] ) A__ : Union[str, Any] = _open[min_f] _closed.append(_open.pop(UpperCAmelCase__ ) ) if current == goal: break for n in world.get_neigbours(UpperCAmelCase__ ): for c in _closed: if c == n: continue A__ : Dict = current.g + 1 A__ , A__ : int = n.position A__ , A__ : Optional[int] = goal.position A__ : Union[str, Any] = (ya - ya) ** 2 + (xa - xa) ** 2 A__ : Optional[int] = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(UpperCAmelCase__ ) A__ : List[str] = [] while current.parent is not None: path.append(current.position ) A__ : Union[str, Any] = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": A_ = Gridworld() # Start position and goal A_ = Cell() A_ = (0, 0) A_ = Cell() A_ = (4, 4) print(F'path from {start.position} to {goal.position}') A_ = astar(world, start, goal) # Just for visual reasons. for i in s: A_ = 1 print(world.w)
296
0
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline A_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __SCREAMING_SNAKE_CASE ( a__ ): def __init__( self : int , snake_case : List[Any] , snake_case : str ): '''simple docstring''' super().__init__() self.register_modules(unet=snake_case , scheduler=snake_case ) @torch.no_grad() def __call__( self : List[str] , snake_case : int = 1 , snake_case : int = 100 , snake_case : Optional[Union[torch.Generator, List[torch.Generator]]] = None , snake_case : Optional[float] = None , snake_case : bool = True , ): '''simple docstring''' if audio_length_in_s is None: A__ : Optional[Any] = self.unet.config.sample_size / self.unet.config.sample_rate A__ : List[Any] = audio_length_in_s * self.unet.config.sample_rate A__ : Tuple = 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}.' ) A__ : List[str] = int(snake_case ) if sample_size % down_scale_factor != 0: A__ : 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.""" ) A__ : Optional[int] = int(snake_case ) A__ : str = next(iter(self.unet.parameters() ) ).dtype A__ : Tuple = (batch_size, self.unet.config.in_channels, sample_size) if isinstance(snake_case , snake_case ) and len(snake_case ) != batch_size: raise ValueError( F'You have passed a list of generators of length {len(snake_case )}, but requested an effective batch' F' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) A__ : List[str] = randn_tensor(snake_case , generator=snake_case , device=self.device , dtype=snake_case ) # set step values self.scheduler.set_timesteps(snake_case , device=audio.device ) A__ : Tuple = self.scheduler.timesteps.to(snake_case ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output A__ : Tuple = self.unet(snake_case , snake_case ).sample # 2. compute previous image: x_t -> t_t-1 A__ : Union[str, Any] = self.scheduler.step(snake_case , snake_case , snake_case ).prev_sample A__ : Tuple = audio.clamp(-1 , 1 ).float().cpu().numpy() A__ : Union[str, Any] = audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=snake_case )
370
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) def _lowerCAmelCase ( UpperCAmelCase__ : Union[str, Any], UpperCAmelCase__ : Tuple=False ) ->str: A__ : Optional[int] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'blocks.{i}.norm1.weight', f'deit.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((f'blocks.{i}.norm1.bias', f'deit.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append((f'blocks.{i}.attn.proj.weight', f'deit.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append((f'blocks.{i}.attn.proj.bias', f'deit.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((f'blocks.{i}.norm2.weight', f'deit.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((f'blocks.{i}.norm2.bias', f'deit.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append((f'blocks.{i}.mlp.fc1.weight', f'deit.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((f'blocks.{i}.mlp.fc1.bias', f'deit.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((f'blocks.{i}.mlp.fc2.weight', f'deit.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((f'blocks.{i}.mlp.fc2.bias', f'deit.encoder.layer.{i}.output.dense.bias') ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """deit.embeddings.cls_token"""), ("""dist_token""", """deit.embeddings.distillation_token"""), ("""patch_embed.proj.weight""", """deit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """deit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """deit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" A__ : Optional[int] = [(pair[0], pair[1][4:]) if pair[1].startswith("""deit""" ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ("""norm.weight""", """deit.layernorm.weight"""), ("""norm.bias""", """deit.layernorm.bias"""), ("""head.weight""", """cls_classifier.weight"""), ("""head.bias""", """cls_classifier.bias"""), ("""head_dist.weight""", """distillation_classifier.weight"""), ("""head_dist.bias""", """distillation_classifier.bias"""), ] ) return rename_keys def _lowerCAmelCase ( UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : Tuple, UpperCAmelCase__ : List[Any]=False ) ->str: for i in range(config.num_hidden_layers ): if base_model: A__ : Any = """""" else: A__ : Tuple = """deit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) A__ : Any = state_dict.pop(f'blocks.{i}.attn.qkv.weight' ) A__ : Tuple = state_dict.pop(f'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict A__ : List[Any] = in_proj_weight[ : config.hidden_size, : ] A__ : str = in_proj_bias[: config.hidden_size] A__ : Any = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] A__ : Dict = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] A__ : Optional[Any] = in_proj_weight[ -config.hidden_size :, : ] A__ : Any = in_proj_bias[-config.hidden_size :] def _lowerCAmelCase ( UpperCAmelCase__ : List[Any], UpperCAmelCase__ : List[Any], UpperCAmelCase__ : Union[str, Any] ) ->Any: A__ : int = dct.pop(UpperCAmelCase__ ) A__ : Tuple = val def _lowerCAmelCase ( ) ->List[Any]: A__ : Optional[int] = """http://images.cocodataset.org/val2017/000000039769.jpg""" A__ : int = Image.open(requests.get(UpperCAmelCase__, stream=UpperCAmelCase__ ).raw ) return im @torch.no_grad() def _lowerCAmelCase ( UpperCAmelCase__ : Dict, UpperCAmelCase__ : Any ) ->Tuple: A__ : List[Any] = DeiTConfig() # all deit models have fine-tuned heads A__ : Tuple = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size A__ : str = 1_0_0_0 A__ : List[str] = """huggingface/label-files""" A__ : Dict = """imagenet-1k-id2label.json""" A__ : List[str] = json.load(open(hf_hub_download(UpperCAmelCase__, UpperCAmelCase__, repo_type="""dataset""" ), """r""" ) ) A__ : Dict = {int(UpperCAmelCase__ ): v for k, v in idalabel.items()} A__ : Optional[int] = idalabel A__ : Dict = {v: k for k, v in idalabel.items()} A__ : List[str] = int(deit_name[-6:-4] ) A__ : str = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith("""tiny""" ): A__ : List[str] = 1_9_2 A__ : int = 7_6_8 A__ : List[Any] = 1_2 A__ : Dict = 3 elif deit_name[9:].startswith("""small""" ): A__ : List[Any] = 3_8_4 A__ : List[str] = 1_5_3_6 A__ : Any = 1_2 A__ : Union[str, Any] = 6 if deit_name[9:].startswith("""base""" ): pass elif deit_name[4:].startswith("""large""" ): A__ : int = 1_0_2_4 A__ : str = 4_0_9_6 A__ : Any = 2_4 A__ : int = 1_6 # load original model from timm A__ : Dict = timm.create_model(UpperCAmelCase__, pretrained=UpperCAmelCase__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys A__ : Tuple = timm_model.state_dict() A__ : str = create_rename_keys(UpperCAmelCase__, UpperCAmelCase__ ) for src, dest in rename_keys: rename_key(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) read_in_q_k_v(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) # load HuggingFace model A__ : str = DeiTForImageClassificationWithTeacher(UpperCAmelCase__ ).eval() model.load_state_dict(UpperCAmelCase__ ) # Check outputs on an image, prepared by DeiTImageProcessor A__ : int = int( (2_5_6 / 2_2_4) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 A__ : Any = DeiTImageProcessor(size=UpperCAmelCase__, crop_size=config.image_size ) A__ : Union[str, Any] = image_processor(images=prepare_img(), return_tensors="""pt""" ) A__ : Optional[Any] = encoding["""pixel_values"""] A__ : Union[str, Any] = model(UpperCAmelCase__ ) A__ : Union[str, Any] = timm_model(UpperCAmelCase__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(UpperCAmelCase__, outputs.logits, atol=1e-3 ) Path(UpperCAmelCase__ ).mkdir(exist_ok=UpperCAmelCase__ ) print(f'Saving model {deit_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(UpperCAmelCase__ ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(UpperCAmelCase__ ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--deit_name''', default='''vit_deit_base_distilled_patch16_224''', type=str, help='''Name of the DeiT 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.''' ) A_ = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
296
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import 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, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class __SCREAMING_SNAKE_CASE : snake_case_ = BlenderbotSmallConfig snake_case_ = {} snake_case_ = 'gelu' def __init__( self : Tuple , snake_case : Optional[Any] , snake_case : str=13 , snake_case : Optional[int]=7 , snake_case : str=True , snake_case : List[str]=False , snake_case : List[Any]=99 , snake_case : int=32 , snake_case : int=2 , snake_case : Union[str, Any]=4 , snake_case : Union[str, Any]=37 , snake_case : List[str]=0.1 , snake_case : Dict=0.1 , snake_case : Tuple=20 , snake_case : Any=2 , snake_case : Dict=1 , snake_case : List[str]=0 , ): '''simple docstring''' A__ : Union[str, Any] = parent A__ : List[Any] = batch_size A__ : List[str] = seq_length A__ : Any = is_training A__ : Union[str, Any] = use_labels A__ : Optional[int] = vocab_size A__ : Optional[Any] = hidden_size A__ : Optional[int] = num_hidden_layers A__ : Dict = num_attention_heads A__ : Optional[Any] = intermediate_size A__ : Optional[Any] = hidden_dropout_prob A__ : Any = attention_probs_dropout_prob A__ : Optional[int] = max_position_embeddings A__ : Tuple = eos_token_id A__ : Union[str, Any] = pad_token_id A__ : Union[str, Any] = bos_token_id def _UpperCamelCase ( self : Any ): '''simple docstring''' A__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) A__ : str = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) A__ : str = tf.concat([input_ids, eos_tensor] , axis=1 ) A__ : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Dict = 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__ : List[str] = prepare_blenderbot_small_inputs_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return config, inputs_dict def _UpperCamelCase ( self : Optional[int] , snake_case : Optional[int] , snake_case : List[Any] ): '''simple docstring''' A__ : int = TFBlenderbotSmallModel(config=_SCREAMING_SNAKE_CASE ).get_decoder() A__ : Dict = inputs_dict['''input_ids'''] A__ : Any = input_ids[:1, :] A__ : Union[str, Any] = inputs_dict['''attention_mask'''][:1, :] A__ : Dict = inputs_dict['''head_mask'''] A__ : List[str] = 1 # first forward pass A__ : Optional[int] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE , use_cache=_SCREAMING_SNAKE_CASE ) A__ : List[Any] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids A__ : int = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ : Union[str, Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and A__ : Dict = tf.concat([input_ids, next_tokens] , axis=-1 ) A__ : str = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) A__ : Optional[Any] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE )[0] A__ : Optional[Any] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , past_key_values=_SCREAMING_SNAKE_CASE )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice A__ : Tuple = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) A__ : str = output_from_no_past[:, -3:, random_slice_idx] A__ : Optional[Any] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , rtol=1e-3 ) def _lowerCAmelCase ( UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : Tuple, UpperCAmelCase__ : Any, UpperCAmelCase__ : Dict=None, UpperCAmelCase__ : Tuple=None, UpperCAmelCase__ : Tuple=None, UpperCAmelCase__ : List[Any]=None, UpperCAmelCase__ : List[Any]=None, ) ->Any: if attention_mask is None: A__ : str = tf.cast(tf.math.not_equal(UpperCAmelCase__, config.pad_token_id ), tf.inta ) if decoder_attention_mask is None: A__ : Union[str, Any] = 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__ : Any = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: A__ : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: A__ : List[str] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class __SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , unittest.TestCase ): snake_case_ = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) snake_case_ = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () snake_case_ = ( { 'conversational': TFBlenderbotSmallForConditionalGeneration, 'feature-extraction': TFBlenderbotSmallModel, 'summarization': TFBlenderbotSmallForConditionalGeneration, 'text2text-generation': TFBlenderbotSmallForConditionalGeneration, 'translation': TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) snake_case_ = True snake_case_ = False snake_case_ = False def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : Dict = TFBlenderbotSmallModelTester(self ) A__ : Any = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_SCREAMING_SNAKE_CASE ) @require_tokenizers @require_tf class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): snake_case_ = [ 'Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like ' ' i\'m going to throw up.\nand why is that?' ] snake_case_ = 'facebook/blenderbot_small-90M' @cached_property def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return BlenderbotSmallTokenizer.from_pretrained("""facebook/blenderbot-90M""" ) @cached_property def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : Dict = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : List[str] = self.tokenizer(self.src_text , return_tensors="""tf""" ) A__ : List[str] = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=_SCREAMING_SNAKE_CASE , ) A__ : List[str] = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=_SCREAMING_SNAKE_CASE )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
371
"""simple docstring""" from __future__ import annotations import time from collections.abc import Sequence from random import randint from matplotlib import pyplot as plt def _lowerCAmelCase ( UpperCAmelCase__ : Sequence[float], UpperCAmelCase__ : int, UpperCAmelCase__ : int ) ->tuple[int | None, int | None, float]: if not arr: return None, None, 0 if low == high: return low, high, arr[low] A__ : Optional[int] = (low + high) // 2 A__ , A__ , A__ : List[Any] = max_subarray(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) A__ , A__ , A__ : Union[str, Any] = max_subarray(UpperCAmelCase__, mid + 1, UpperCAmelCase__ ) A__ , A__ , A__ : Union[str, Any] = max_cross_sum(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum return cross_left, cross_right, cross_sum def _lowerCAmelCase ( UpperCAmelCase__ : Sequence[float], UpperCAmelCase__ : int, UpperCAmelCase__ : int, UpperCAmelCase__ : int ) ->tuple[int, int, float]: A__ , A__ : Dict = float("""-inf""" ), -1 A__ , A__ : Optional[Any] = float("""-inf""" ), -1 A__ : int | float = 0 for i in range(UpperCAmelCase__, low - 1, -1 ): summ += arr[i] if summ > left_sum: A__ : Optional[int] = summ A__ : Union[str, Any] = i A__ : Optional[Any] = 0 for i in range(mid + 1, high + 1 ): summ += arr[i] if summ > right_sum: A__ : int = summ A__ : Union[str, Any] = i return max_left, max_right, (left_sum + right_sum) def _lowerCAmelCase ( UpperCAmelCase__ : int ) ->float: A__ : Union[str, Any] = [randint(1, UpperCAmelCase__ ) for _ in range(UpperCAmelCase__ )] A__ : Any = time.time() max_subarray(UpperCAmelCase__, 0, input_size - 1 ) A__ : List[Any] = time.time() return end - start def _lowerCAmelCase ( ) ->None: A__ : List[Any] = [1_0, 1_0_0, 1_0_0_0, 1_0_0_0_0, 5_0_0_0_0, 1_0_0_0_0_0, 2_0_0_0_0_0, 3_0_0_0_0_0, 4_0_0_0_0_0, 5_0_0_0_0_0] A__ : Any = [time_max_subarray(UpperCAmelCase__ ) for input_size in input_sizes] print("""No of Inputs\t\tTime Taken""" ) for input_size, runtime in zip(UpperCAmelCase__, UpperCAmelCase__ ): print(UpperCAmelCase__, """\t\t""", UpperCAmelCase__ ) plt.plot(UpperCAmelCase__, UpperCAmelCase__ ) plt.xlabel("""Number of Inputs""" ) plt.ylabel("""Time taken in seconds""" ) plt.show() if __name__ == "__main__": from doctest import testmod testmod()
296
0
"""simple docstring""" import inspect from typing import Callable, List, Optional, Union import torch from transformers import ( CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, WhisperForConditionalGeneration, WhisperProcessor, ) from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.utils import logging A_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __SCREAMING_SNAKE_CASE ( a_ ): def __init__( self : Any , snake_case : int , snake_case : Tuple , snake_case : Optional[Any] , snake_case : Dict , snake_case : Union[str, Any] , snake_case : Union[str, Any] , snake_case : Dict , snake_case : Tuple , snake_case : Union[str, Any] , ): '''simple docstring''' super().__init__() if safety_checker is None: logger.warning( F'You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure' """ that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered""" """ results in services or applications open to the public. Both the diffusers team and Hugging Face""" """ strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling""" """ it only for use-cases that involve analyzing network behavior or auditing its results. For more""" """ information, please have a look at https://github.com/huggingface/diffusers/pull/254 .""" ) self.register_modules( speech_model=snake_case , speech_processor=snake_case , vae=snake_case , text_encoder=snake_case , tokenizer=snake_case , unet=snake_case , scheduler=snake_case , feature_extractor=snake_case , ) def _UpperCamelCase ( self : str , snake_case : Optional[int] = "auto" ): '''simple docstring''' if slice_size == "auto": A__ : Dict = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(snake_case ) def _UpperCamelCase ( self : str ): '''simple docstring''' self.enable_attention_slicing(snake_case ) @torch.no_grad() def __call__( self : Tuple , snake_case : Any , snake_case : Dict=1_6000 , snake_case : str = 512 , snake_case : Any = 512 , snake_case : int = 50 , snake_case : str = 7.5 , snake_case : Any = None , snake_case : List[str] = 1 , snake_case : Optional[int] = 0.0 , snake_case : Tuple = None , snake_case : Union[str, Any] = None , snake_case : Tuple = "pil" , snake_case : str = True , snake_case : int = None , snake_case : List[Any] = 1 , **snake_case : Dict , ): '''simple docstring''' A__ : Union[str, Any] = self.speech_processor.feature_extractor( snake_case , return_tensors="""pt""" , sampling_rate=snake_case ).input_features.to(self.device ) A__ : List[str] = self.speech_model.generate(snake_case , max_length=48_0000 ) A__ : Tuple = self.speech_processor.tokenizer.batch_decode(snake_case , skip_special_tokens=snake_case , normalize=snake_case )[ 0 ] if isinstance(snake_case , snake_case ): A__ : str = 1 elif isinstance(snake_case , snake_case ): A__ : Tuple = len(snake_case ) else: raise ValueError(F'`prompt` has to be of type `str` or `list` but is {type(snake_case )}' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F'`height` and `width` have to be divisible by 8 but are {height} and {width}.' ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(snake_case , snake_case ) or callback_steps <= 0) ): raise ValueError( F'`callback_steps` has to be a positive integer but is {callback_steps} of type' F' {type(snake_case )}.' ) # get prompt text embeddings A__ : Any = self.tokenizer( snake_case , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) A__ : Optional[Any] = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: A__ : str = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" F' {self.tokenizer.model_max_length} tokens: {removed_text}' ) A__ : Union[str, Any] = text_input_ids[:, : self.tokenizer.model_max_length] A__ : Optional[int] = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method A__ , A__ , A__ : List[Any] = text_embeddings.shape A__ : Optional[Any] = text_embeddings.repeat(1 , snake_case , 1 ) A__ : Optional[int] = text_embeddings.view(bs_embed * num_images_per_prompt , snake_case , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. A__ : List[str] = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: A__ : int = 42 if negative_prompt is None: A__ : str = [""""""] * batch_size elif type(snake_case ) is not type(snake_case ): raise TypeError( F'`negative_prompt` should be the same type to `prompt`, but got {type(snake_case )} !=' F' {type(snake_case )}.' ) elif isinstance(snake_case , snake_case ): A__ : List[str] = [negative_prompt] elif batch_size != len(snake_case ): raise ValueError( F'`negative_prompt`: {negative_prompt} has batch size {len(snake_case )}, but `prompt`:' F' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches' """ the batch size of `prompt`.""" ) else: A__ : List[str] = negative_prompt A__ : int = text_input_ids.shape[-1] A__ : Optional[Any] = self.tokenizer( snake_case , padding="""max_length""" , max_length=snake_case , truncation=snake_case , return_tensors="""pt""" , ) A__ : str = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method A__ : Any = uncond_embeddings.shape[1] A__ : int = uncond_embeddings.repeat(1 , snake_case , 1 ) A__ : str = uncond_embeddings.view(batch_size * num_images_per_prompt , snake_case , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes A__ : List[str] = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. A__ : Optional[Any] = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) A__ : Optional[Any] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps A__ : int = torch.randn(snake_case , generator=snake_case , device="""cpu""" , dtype=snake_case ).to( self.device ) else: A__ : List[Any] = torch.randn(snake_case , generator=snake_case , device=self.device , dtype=snake_case ) else: if latents.shape != latents_shape: raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {latents_shape}' ) A__ : str = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(snake_case ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand A__ : int = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler A__ : Dict = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] A__ : Tuple = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) A__ : List[str] = {} if accepts_eta: A__ : Union[str, Any] = eta for i, t in enumerate(self.progress_bar(snake_case ) ): # expand the latents if we are doing classifier free guidance A__ : int = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents A__ : Union[str, Any] = self.scheduler.scale_model_input(snake_case , snake_case ) # predict the noise residual A__ : Optional[int] = self.unet(snake_case , snake_case , encoder_hidden_states=snake_case ).sample # perform guidance if do_classifier_free_guidance: A__ , A__ : List[Any] = noise_pred.chunk(2 ) A__ : Any = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 A__ : str = self.scheduler.step(snake_case , snake_case , snake_case , **snake_case ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(snake_case , snake_case , snake_case ) A__ : Optional[int] = 1 / 0.18215 * latents A__ : Tuple = self.vae.decode(snake_case ).sample A__ : List[str] = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 A__ : Dict = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": A__ : List[Any] = self.numpy_to_pil(snake_case ) if not return_dict: return image return StableDiffusionPipelineOutput(images=snake_case , nsfw_content_detected=snake_case )
350
"""simple docstring""" from __future__ import annotations class __SCREAMING_SNAKE_CASE : def __init__( self : Dict , snake_case : int ): '''simple docstring''' A__ : List[Any] = order # a_{0} ... a_{k} A__ : List[Any] = [1.0] + [0.0] * order # b_{0} ... b_{k} A__ : str = [1.0] + [0.0] * order # x[n-1] ... x[n-k] A__ : Union[str, Any] = [0.0] * self.order # y[n-1] ... y[n-k] A__ : List[str] = [0.0] * self.order def _UpperCamelCase ( self : Optional[int] , snake_case : list[float] , snake_case : list[float] ): '''simple docstring''' if len(snake_case ) < self.order: A__ : Any = [1.0, *a_coeffs] if len(snake_case ) != self.order + 1: A__ : str = ( F'Expected a_coeffs to have {self.order + 1} elements ' F'for {self.order}-order filter, got {len(snake_case )}' ) raise ValueError(snake_case ) if len(snake_case ) != self.order + 1: A__ : Union[str, Any] = ( F'Expected b_coeffs to have {self.order + 1} elements ' F'for {self.order}-order filter, got {len(snake_case )}' ) raise ValueError(snake_case ) A__ : Dict = a_coeffs A__ : Any = b_coeffs def _UpperCamelCase ( self : List[str] , snake_case : float ): '''simple docstring''' A__ : str = 0.0 # Start at index 1 and do index 0 at the end. for i in range(1 , self.order + 1 ): result += ( self.b_coeffs[i] * self.input_history[i - 1] - self.a_coeffs[i] * self.output_history[i - 1] ) A__ : Dict = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0] A__ : Tuple = self.input_history[:-1] A__ : int = self.output_history[:-1] A__ : Dict = sample A__ : Tuple = result return result
296
0
"""simple docstring""" def _lowerCAmelCase ( UpperCAmelCase__ : str, UpperCAmelCase__ : str ) ->str: if not (isinstance(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ) and isinstance(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE )): raise ValueError("""longest_common_substring() takes two strings for inputs""" ) A__ : Tuple = len(_SCREAMING_SNAKE_CASE ) A__ : Dict = len(_SCREAMING_SNAKE_CASE ) A__ : Tuple = [[0] * (texta_length + 1) for _ in range(texta_length + 1 )] A__ : List[Any] = 0 A__ : Any = 0 for i in range(1, texta_length + 1 ): for j in range(1, texta_length + 1 ): if texta[i - 1] == texta[j - 1]: A__ : Union[str, Any] = 1 + dp[i - 1][j - 1] if dp[i][j] > ans_length: A__ : Any = i A__ : Any = dp[i][j] return texta[ans_index - ans_length : ans_index] if __name__ == "__main__": import doctest doctest.testmod()
351
"""simple docstring""" import unittest from parameterized import parameterized from transformers import AutoTokenizer, GPTNeoXConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXModel, ) class __SCREAMING_SNAKE_CASE : def __init__( self : Optional[int] , snake_case : Optional[Any] , snake_case : Tuple=13 , snake_case : Dict=7 , snake_case : Optional[int]=True , snake_case : Union[str, Any]=True , snake_case : Dict=True , snake_case : Any=True , snake_case : List[str]=99 , snake_case : str=64 , snake_case : Optional[int]=5 , snake_case : str=4 , snake_case : List[Any]=37 , snake_case : Optional[Any]="gelu" , snake_case : List[str]=0.1 , snake_case : str=0.1 , snake_case : Optional[int]=512 , snake_case : Dict=16 , snake_case : List[Any]=2 , snake_case : Optional[int]=0.02 , snake_case : Any=3 , snake_case : Union[str, Any]=4 , snake_case : Dict=None , ): '''simple docstring''' A__ : Tuple = parent A__ : Union[str, Any] = batch_size A__ : List[str] = seq_length A__ : Optional[int] = is_training A__ : Dict = use_input_mask A__ : Any = use_token_type_ids A__ : Optional[Any] = use_labels A__ : List[str] = vocab_size A__ : Optional[int] = hidden_size A__ : Optional[Any] = num_hidden_layers A__ : Any = num_attention_heads A__ : List[Any] = intermediate_size A__ : Optional[Any] = hidden_act A__ : Optional[int] = hidden_dropout_prob A__ : Tuple = attention_probs_dropout_prob A__ : str = max_position_embeddings A__ : List[str] = type_vocab_size A__ : Union[str, Any] = type_sequence_label_size A__ : List[Any] = initializer_range A__ : Optional[int] = num_labels A__ : Dict = num_choices A__ : Dict = scope A__ : List[Any] = vocab_size - 1 def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : List[Any] = None if self.use_input_mask: A__ : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) A__ : Union[str, Any] = None if self.use_labels: A__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : Tuple = self.get_config() return config, input_ids, input_mask, token_labels def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' return GPTNeoXConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case , initializer_range=self.initializer_range , pad_token_id=self.pad_token_id , ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ , A__ , A__ , A__ : str = self.prepare_config_and_inputs() A__ : Union[str, Any] = True return config, input_ids, input_mask, token_labels def _UpperCamelCase ( self : Union[str, Any] , snake_case : Optional[int] , snake_case : List[str] , snake_case : int ): '''simple docstring''' A__ : Any = GPTNeoXModel(config=snake_case ) model.to(snake_case ) model.eval() A__ : int = model(snake_case , attention_mask=snake_case ) A__ : Optional[int] = model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : Union[str, Any] , snake_case : str , snake_case : Any , snake_case : Union[str, Any] ): '''simple docstring''' A__ : int = True A__ : str = GPTNeoXModel(snake_case ) model.to(snake_case ) model.eval() A__ : Tuple = model(snake_case , attention_mask=snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : Dict , snake_case : List[Any] , snake_case : str , snake_case : Optional[Any] , snake_case : Any ): '''simple docstring''' A__ : Any = GPTNeoXForCausalLM(config=snake_case ) model.to(snake_case ) model.eval() A__ : Tuple = 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 _UpperCamelCase ( self : List[str] , snake_case : Optional[Any] , snake_case : Optional[Any] , snake_case : Union[str, Any] , snake_case : Tuple ): '''simple docstring''' A__ : int = self.num_labels A__ : int = GPTNeoXForQuestionAnswering(snake_case ) model.to(snake_case ) model.eval() A__ : Optional[Any] = model(snake_case , attention_mask=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 _UpperCamelCase ( self : str , snake_case : Tuple , snake_case : int , snake_case : int , snake_case : Dict ): '''simple docstring''' A__ : List[Any] = self.num_labels A__ : Tuple = GPTNeoXForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : List[str] = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _UpperCamelCase ( self : Any , snake_case : Union[str, Any] , snake_case : int , snake_case : Tuple , snake_case : Any ): '''simple docstring''' A__ : Tuple = self.num_labels A__ : Any = GPTNeoXForTokenClassification(snake_case ) model.to(snake_case ) model.eval() A__ : Dict = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self : List[str] , snake_case : List[str] , snake_case : Tuple , snake_case : Any ): '''simple docstring''' A__ : Optional[int] = True A__ : Any = GPTNeoXForCausalLM(config=snake_case ) model.to(snake_case ) model.eval() # first forward pass A__ : Tuple = model(snake_case , attention_mask=snake_case , use_cache=snake_case ) A__ : str = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A__ : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ : Tuple = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and A__ : Any = torch.cat([input_ids, next_tokens] , dim=-1 ) A__ : Any = torch.cat([input_mask, next_mask] , dim=-1 ) A__ : Tuple = model(snake_case , attention_mask=snake_case , output_hidden_states=snake_case ) A__ : List[Any] = output_from_no_past["""hidden_states"""][0] A__ : List[str] = model( snake_case , attention_mask=snake_case , past_key_values=snake_case , output_hidden_states=snake_case , )["""hidden_states"""][0] # select random slice A__ : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() A__ : List[Any] = output_from_no_past[:, -3:, random_slice_idx].detach() A__ : Any = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(snake_case , snake_case , atol=1e-3 ) ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : str = self.prepare_config_and_inputs() A__ , A__ , A__ , A__ : Dict = config_and_inputs A__ : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase ): snake_case_ = ( ( GPTNeoXModel, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, ) if is_torch_available() else () ) snake_case_ = (GPTNeoXForCausalLM,) if is_torch_available() else () snake_case_ = ( { 'feature-extraction': GPTNeoXModel, 'question-answering': GPTNeoXForQuestionAnswering, 'text-classification': GPTNeoXForSequenceClassification, 'text-generation': GPTNeoXForCausalLM, 'token-classification': GPTNeoXForTokenClassification, 'zero-shot': GPTNeoXForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Any = GPTNeoXModelTester(self ) A__ : Any = ConfigTester(self , config_class=snake_case , hidden_size=64 , num_attention_heads=8 ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self : Any ): '''simple docstring''' A__ , A__ , A__ , A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(snake_case , snake_case , snake_case ) def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ , A__ , A__ , A__ : Dict = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(snake_case , snake_case , snake_case ) def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ , A__ , A__ , A__ : List[str] = self.model_tester.prepare_config_and_inputs_for_decoder() A__ : Optional[Any] = None self.model_tester.create_and_check_model_as_decoder(snake_case , snake_case , snake_case ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ , A__ , A__ , A__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(snake_case , snake_case , snake_case ) def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*snake_case ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case ) @unittest.skip(reason="""Feed forward chunking is not implemented""" ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' pass @parameterized.expand([("""linear""",), ("""dynamic""",)] ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Optional[Any] ): '''simple docstring''' A__ , A__ : int = self.model_tester.prepare_config_and_inputs_for_common() A__ : List[Any] = ids_tensor([1, 10] , config.vocab_size ) A__ : str = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A__ : Union[str, Any] = GPTNeoXModel(snake_case ) original_model.to(snake_case ) original_model.eval() A__ : Optional[int] = original_model(snake_case ).last_hidden_state A__ : List[str] = original_model(snake_case ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A__ : Optional[int] = {"""type""": scaling_type, """factor""": 10.0} A__ : Optional[int] = GPTNeoXModel(snake_case ) scaled_model.to(snake_case ) scaled_model.eval() A__ : List[str] = scaled_model(snake_case ).last_hidden_state A__ : Tuple = scaled_model(snake_case ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(snake_case , snake_case , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(snake_case , snake_case , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(snake_case , snake_case , atol=1e-5 ) ) @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Any = AutoTokenizer.from_pretrained("""EleutherAI/pythia-410m-deduped""" ) for checkpointing in [True, False]: A__ : Optional[Any] = GPTNeoXForCausalLM.from_pretrained("""EleutherAI/pythia-410m-deduped""" ) if checkpointing: model.gradient_checkpointing_enable() else: model.gradient_checkpointing_disable() model.to(snake_case ) A__ : Optional[Any] = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(snake_case ) # The hub repo. is updated on 2023-04-04, resulting in poor outputs. # See: https://github.com/huggingface/transformers/pull/24193 A__ : Union[str, Any] = """My favorite food is a good old-fashioned, old-fashioned, old-fashioned.\n\nI'm not sure""" A__ : Tuple = model.generate(**snake_case , do_sample=snake_case , max_new_tokens=20 ) A__ : Tuple = tokenizer.batch_decode(snake_case )[0] self.assertEqual(snake_case , snake_case )
296
0
"""simple docstring""" import os import tempfile import unittest from transformers import DistilBertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, ) class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): def __init__( self : Optional[Any] , snake_case : int , snake_case : str=13 , snake_case : List[str]=7 , snake_case : Tuple=True , snake_case : List[Any]=True , snake_case : Any=False , snake_case : str=True , snake_case : Dict=99 , snake_case : Union[str, Any]=32 , snake_case : List[str]=5 , snake_case : int=4 , snake_case : int=37 , snake_case : Optional[int]="gelu" , snake_case : Optional[int]=0.1 , snake_case : int=0.1 , snake_case : str=512 , snake_case : str=16 , snake_case : Any=2 , snake_case : Optional[Any]=0.02 , snake_case : str=3 , snake_case : int=4 , snake_case : Union[str, Any]=None , ): '''simple docstring''' A__ : Dict = parent A__ : int = batch_size A__ : Union[str, Any] = seq_length A__ : str = is_training A__ : Optional[Any] = use_input_mask A__ : List[Any] = use_token_type_ids A__ : str = use_labels A__ : List[str] = vocab_size A__ : str = hidden_size A__ : List[str] = num_hidden_layers A__ : List[str] = num_attention_heads A__ : Union[str, Any] = intermediate_size A__ : str = hidden_act A__ : Optional[int] = hidden_dropout_prob A__ : Union[str, Any] = attention_probs_dropout_prob A__ : str = max_position_embeddings A__ : Optional[int] = type_vocab_size A__ : List[str] = type_sequence_label_size A__ : Optional[Any] = initializer_range A__ : Optional[int] = num_labels A__ : int = num_choices A__ : Dict = scope def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : int = None if self.use_input_mask: A__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) A__ : int = None A__ : Optional[int] = None A__ : Optional[Any] = None if self.use_labels: A__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) A__ : List[str] = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' return DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) def _UpperCamelCase ( self : int , snake_case : Union[str, Any] , snake_case : Tuple , snake_case : int , snake_case : Optional[Any] , snake_case : Any , snake_case : int ): '''simple docstring''' A__ : int = DistilBertModel(config=snake_case ) model.to(snake_case ) model.eval() A__ : Optional[int] = model(snake_case , snake_case ) A__ : List[str] = model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : List[Any] , snake_case : Optional[int] , snake_case : Optional[int] , snake_case : Union[str, Any] , snake_case : Tuple , snake_case : List[Any] , snake_case : Optional[Any] ): '''simple docstring''' A__ : int = DistilBertForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() A__ : Any = 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 _UpperCamelCase ( self : str , snake_case : Any , snake_case : List[Any] , snake_case : Tuple , snake_case : List[Any] , snake_case : Tuple , snake_case : Any ): '''simple docstring''' A__ : Tuple = DistilBertForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() A__ : Optional[int] = model( snake_case , attention_mask=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 _UpperCamelCase ( self : List[Any] , snake_case : int , snake_case : Optional[Any] , snake_case : Optional[Any] , snake_case : List[str] , snake_case : Any , snake_case : Tuple ): '''simple docstring''' A__ : List[Any] = self.num_labels A__ : Union[str, Any] = DistilBertForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : int = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _UpperCamelCase ( self : Optional[int] , snake_case : Any , snake_case : Optional[int] , snake_case : Tuple , snake_case : str , snake_case : Dict , snake_case : Optional[int] ): '''simple docstring''' A__ : Any = self.num_labels A__ : Optional[int] = DistilBertForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() A__ : Optional[Any] = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self : List[Any] , snake_case : Union[str, Any] , snake_case : Optional[Any] , snake_case : Optional[int] , snake_case : List[str] , snake_case : List[str] , snake_case : str ): '''simple docstring''' A__ : str = self.num_choices A__ : Dict = DistilBertForMultipleChoice(config=snake_case ) model.to(snake_case ) model.eval() A__ : Tuple = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : Optional[int] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : Optional[Any] = model( snake_case , attention_mask=snake_case , labels=snake_case , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : Dict = self.prepare_config_and_inputs() (A__) : int = config_and_inputs A__ : Union[str, Any] = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , unittest.TestCase ): snake_case_ = ( ( DistilBertModel, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, ) if is_torch_available() else None ) snake_case_ = ( { 'feature-extraction': DistilBertModel, 'fill-mask': DistilBertForMaskedLM, 'question-answering': DistilBertForQuestionAnswering, 'text-classification': DistilBertForSequenceClassification, 'token-classification': DistilBertForTokenClassification, 'zero-shot': DistilBertForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = True snake_case_ = True snake_case_ = True snake_case_ = True def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Union[str, Any] = DistilBertModelTester(self ) A__ : List[Any] = ConfigTester(self , config_class=snake_case , dim=37 ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*snake_case ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*snake_case ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*snake_case ) def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*snake_case ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*snake_case ) @slow def _UpperCamelCase ( self : Tuple ): '''simple docstring''' for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ : Optional[int] = DistilBertModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @slow @require_torch_gpu def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # BertForMultipleChoice behaves incorrectly in JIT environments. if model_class == DistilBertForMultipleChoice: return A__ : Tuple = True A__ : Union[str, Any] = model_class(config=snake_case ) A__ : List[Any] = self._prepare_for_class(snake_case , snake_case ) A__ : int = torch.jit.trace( snake_case , (inputs_dict["""input_ids"""].to("""cpu""" ), inputs_dict["""attention_mask"""].to("""cpu""" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(snake_case , os.path.join(snake_case , """traced_model.pt""" ) ) A__ : Optional[int] = torch.jit.load(os.path.join(snake_case , """traced_model.pt""" ) , map_location=snake_case ) loaded(inputs_dict["""input_ids"""].to(snake_case ) , inputs_dict["""attention_mask"""].to(snake_case ) ) @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : Dict = DistilBertModel.from_pretrained("""distilbert-base-uncased""" ) A__ : List[str] = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) A__ : Optional[Any] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): A__ : str = model(snake_case , attention_mask=snake_case )[0] A__ : Dict = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , snake_case ) A__ : Any = torch.tensor( [[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , snake_case , atol=1e-4 ) )
352
"""simple docstring""" from collections import defaultdict from math import gcd def _lowerCAmelCase ( UpperCAmelCase__ : int = 1_5_0_0_0_0_0 ) ->int: A__ : defaultdict = defaultdict(UpperCAmelCase__ ) A__ : Any = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1, UpperCAmelCase__, 2 ): if gcd(UpperCAmelCase__, UpperCAmelCase__ ) > 1: continue A__ : str = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(UpperCAmelCase__, limit + 1, UpperCAmelCase__ ): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1 ) if __name__ == "__main__": print(F'{solution() = }')
296
0
"""simple docstring""" def _lowerCAmelCase ( UpperCAmelCase__ : int ) ->Tuple: A__ : Union[str, Any] = [[0 for _ in range(UpperCAmelCase_ )] for _ in range(m + 1 )] for i in range(m + 1 ): A__ : List[Any] = 1 for n in range(m + 1 ): for k in range(1, UpperCAmelCase_ ): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: A_ = int(input('''Enter a number: ''').strip()) print(partition(n)) except ValueError: print('''Please enter a number.''') else: try: A_ = int(sys.argv[1]) print(partition(n)) except ValueError: print('''Please pass a number.''')
353
"""simple docstring""" import os from distutils.util import strtobool def _lowerCAmelCase ( UpperCAmelCase__ : List[Any], UpperCAmelCase__ : Optional[Any] ) ->List[str]: for e in env_keys: A__ : List[Any] = int(os.environ.get(UpperCAmelCase__, -1 ) ) if val >= 0: return val return default def _lowerCAmelCase ( UpperCAmelCase__ : Tuple, UpperCAmelCase__ : str=False ) ->List[str]: A__ : List[Any] = os.environ.get(UpperCAmelCase__, str(UpperCAmelCase__ ) ) return strtobool(UpperCAmelCase__ ) == 1 # As its name indicates `strtobool` actually returns an int... def _lowerCAmelCase ( UpperCAmelCase__ : Tuple, UpperCAmelCase__ : List[Any]="no" ) ->int: A__ : str = os.environ.get(UpperCAmelCase__, str(UpperCAmelCase__ ) ) return value
296
0
"""simple docstring""" from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class __SCREAMING_SNAKE_CASE : snake_case_ = 42 snake_case_ = None # Automatically constructed snake_case_ = 'dict' snake_case_ = None snake_case_ = field(default='Translation' , init=lowerCamelCase__ , repr=lowerCamelCase__ ) def __call__( self : Union[str, Any] ): '''simple docstring''' return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' from .features import Value return {k: Value("""string""" ) for k in sorted(self.languages )} @dataclass class __SCREAMING_SNAKE_CASE : snake_case_ = None snake_case_ = None snake_case_ = None # Automatically constructed snake_case_ = 'dict' snake_case_ = None snake_case_ = field(default='TranslationVariableLanguages' , init=lowerCamelCase__ , repr=lowerCamelCase__ ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Dict = sorted(set(self.languages ) ) if self.languages else None A__ : int = len(self.languages ) if self.languages else None def __call__( self : Optional[int] ): '''simple docstring''' return pa.struct({"""language""": pa.list_(pa.string() ), """translation""": pa.list_(pa.string() )} ) def _UpperCamelCase ( self : List[str] , snake_case : List[str] ): '''simple docstring''' A__ : List[Any] = set(self.languages ) if self.languages and set(snake_case ) - lang_set: raise ValueError( F'Some languages in example ({", ".join(sorted(set(snake_case ) - lang_set ) )}) are not in valid set ({", ".join(snake_case )}).' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. A__ : Union[str, Any] = [] for lang, text in translation_dict.items(): if isinstance(snake_case , snake_case ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. A__ : Optional[int] = zip(*sorted(snake_case ) ) return {"language": languages, "translation": translations} def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' from .features import Sequence, Value return { "language": Sequence(Value("""string""" ) ), "translation": Sequence(Value("""string""" ) ), }
354
"""simple docstring""" import cva import numpy as np class __SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , snake_case : float , snake_case : int ): '''simple docstring''' if k in (0.04, 0.06): A__ : Optional[int] = k A__ : int = window_size else: raise ValueError("""invalid k value""" ) def __str__( self : List[Any] ): '''simple docstring''' return str(self.k ) def _UpperCamelCase ( self : int , snake_case : str ): '''simple docstring''' A__ : List[str] = cva.imread(snake_case , 0 ) A__ , A__ : Union[str, Any] = img.shape A__ : list[list[int]] = [] A__ : Optional[Any] = img.copy() A__ : List[str] = cva.cvtColor(snake_case , cva.COLOR_GRAY2RGB ) A__ , A__ : List[Any] = np.gradient(snake_case ) A__ : List[Any] = dx**2 A__ : Any = dy**2 A__ : Dict = dx * dy A__ : Any = 0.04 A__ : Optional[Any] = self.window_size // 2 for y in range(snake_case , h - offset ): for x in range(snake_case , w - offset ): A__ : List[str] = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() A__ : Tuple = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() A__ : Optional[int] = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() A__ : int = (wxx * wyy) - (wxy**2) A__ : Any = wxx + wyy A__ : List[str] = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 255 ) return color_img, corner_list if __name__ == "__main__": A_ = HarrisCorner(0.04, 3) A_ , A_ = edge_detect.detect('''path_to_image''') cva.imwrite('''detect.png''', color_img)
296
0
"""simple docstring""" A_ = { 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f", } def _lowerCAmelCase ( UpperCAmelCase__ : float ) ->str: assert type(UpperCAmelCase__ ) in (int, float) and decimal == int(UpperCAmelCase__ ) A__ : Dict = int(UpperCAmelCase__ ) A__ : int = """""" A__ : int = False if decimal < 0: A__ : Tuple = True decimal *= -1 while decimal > 0: A__ , A__ : List[Any] = divmod(UpperCAmelCase__, 1_6 ) A__ : Tuple = values[remainder] + hexadecimal A__ : Dict = """0x""" + hexadecimal if negative: A__ : Tuple = """-""" + hexadecimal return hexadecimal if __name__ == "__main__": import doctest doctest.testmod()
355
"""simple docstring""" from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING A_ = logging.get_logger(__name__) A_ = Dict[str, Any] A_ = List[Prediction] @add_end_docstrings(UpperCamelCase ) class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): def __init__( self : str , *snake_case : Tuple , **snake_case : Tuple ): '''simple docstring''' super().__init__(*snake_case , **snake_case ) if self.framework == "tf": raise ValueError(F'The {self.__class__} is only available in PyTorch.' ) requires_backends(self , """vision""" ) self.check_model_type( dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items() ) ) def _UpperCamelCase ( self : List[Any] , **snake_case : Optional[int] ): '''simple docstring''' A__ : Dict = {} if "threshold" in kwargs: A__ : int = kwargs["""threshold"""] return {}, {}, postprocess_kwargs def __call__( self : Tuple , *snake_case : Union[str, Any] , **snake_case : Union[str, Any] ): '''simple docstring''' return super().__call__(*snake_case , **snake_case ) def _UpperCamelCase ( self : str , snake_case : int ): '''simple docstring''' A__ : List[str] = load_image(snake_case ) A__ : int = torch.IntTensor([[image.height, image.width]] ) A__ : Union[str, Any] = self.image_processor(images=[image] , return_tensors="""pt""" ) if self.tokenizer is not None: A__ : str = self.tokenizer(text=inputs["""words"""] , boxes=inputs["""boxes"""] , return_tensors="""pt""" ) A__ : List[str] = target_size return inputs def _UpperCamelCase ( self : Optional[int] , snake_case : List[Any] ): '''simple docstring''' A__ : str = model_inputs.pop("""target_size""" ) A__ : Dict = self.model(**snake_case ) A__ : Optional[Any] = outputs.__class__({"""target_size""": target_size, **outputs} ) if self.tokenizer is not None: A__ : str = model_inputs["""bbox"""] return model_outputs def _UpperCamelCase ( self : Tuple , snake_case : Optional[int] , snake_case : int=0.9 ): '''simple docstring''' A__ : Any = model_outputs["""target_size"""] if self.tokenizer is not None: # This is a LayoutLMForTokenClassification variant. # The OCR got the boxes and the model classified the words. A__ , A__ : Tuple = target_size[0].tolist() def unnormalize(snake_case : Optional[int] ): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ] ) ) A__ , A__ : Optional[int] = model_outputs["""logits"""].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 ) A__ : Optional[Any] = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] A__ : List[str] = [unnormalize(snake_case ) for bbox in model_outputs["""bbox"""].squeeze(0 )] A__ : Tuple = ["""score""", """label""", """box"""] A__ : Any = [dict(zip(snake_case , snake_case ) ) for vals in zip(scores.tolist() , snake_case , snake_case ) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel A__ : Union[str, Any] = self.image_processor.post_process_object_detection(snake_case , snake_case , snake_case ) A__ : str = raw_annotations[0] A__ : str = raw_annotation["""scores"""] A__ : List[Any] = raw_annotation["""labels"""] A__ : int = raw_annotation["""boxes"""] A__ : str = scores.tolist() A__ : Any = [self.model.config.idalabel[label.item()] for label in labels] A__ : int = [self._get_bounding_box(snake_case ) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] A__ : str = ["""score""", """label""", """box"""] A__ : Dict = [ dict(zip(snake_case , snake_case ) ) for vals in zip(raw_annotation["""scores"""] , raw_annotation["""labels"""] , raw_annotation["""boxes"""] ) ] return annotation def _UpperCamelCase ( self : Union[str, Any] , snake_case : "torch.Tensor" ): '''simple docstring''' if self.framework != "pt": raise ValueError("""The ObjectDetectionPipeline is only available in PyTorch.""" ) A__ , A__ , A__ , A__ : Any = box.int().tolist() A__ : Any = { """xmin""": xmin, """ymin""": ymin, """xmax""": xmax, """ymax""": ymax, } return bbox
296
0
"""simple docstring""" from __future__ import annotations import math def _lowerCAmelCase ( UpperCAmelCase__ : Dict, UpperCAmelCase__ : List[str] ) ->float: A__ : str = u for i in range(1, __UpperCAmelCase ): A__ : Any = temp * (u - i) return temp def _lowerCAmelCase ( ) ->None: A__ : int = int(input("""enter the numbers of values: """ ) ) A__ : Tuple = [] for _ in range(__UpperCAmelCase ): y.append([] ) for i in range(__UpperCAmelCase ): for j in range(__UpperCAmelCase ): y[i].append(__UpperCAmelCase ) A__ : str = 0 print("""enter the values of parameters in a list: """ ) A__ : Tuple = list(map(__UpperCAmelCase, input().split() ) ) print("""enter the values of corresponding parameters: """ ) for i in range(__UpperCAmelCase ): A__ : Tuple = float(input() ) A__ : str = int(input("""enter the value to interpolate: """ ) ) A__ : Union[str, Any] = (value - x[0]) / (x[1] - x[0]) # for calculating forward difference table for i in range(1, __UpperCAmelCase ): for j in range(n - i ): A__ : int = y[j + 1][i - 1] - y[j][i - 1] A__ : str = y[0][0] for i in range(1, __UpperCAmelCase ): summ += (ucal(__UpperCAmelCase, __UpperCAmelCase ) * y[0][i]) / math.factorial(__UpperCAmelCase ) print(f'the value at {value} is {summ}' ) if __name__ == "__main__": main()
356
"""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 A_ = logging.get_logger(__name__) A_ = { '''microsoft/table-transformer-detection''': ( '''https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json''' ), } class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = 'table-transformer' snake_case_ = ['past_key_values'] snake_case_ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Dict , snake_case : int=True , snake_case : Dict=None , snake_case : Union[str, Any]=3 , snake_case : Dict=100 , snake_case : Tuple=6 , snake_case : Optional[int]=2048 , snake_case : int=8 , snake_case : Dict=6 , snake_case : Any=2048 , snake_case : str=8 , snake_case : Union[str, Any]=0.0 , snake_case : List[str]=0.0 , snake_case : List[str]=True , snake_case : Any="relu" , snake_case : str=256 , snake_case : int=0.1 , snake_case : Dict=0.0 , snake_case : str=0.0 , snake_case : Union[str, Any]=0.02 , snake_case : Union[str, Any]=1.0 , snake_case : Optional[Any]=False , snake_case : int="sine" , snake_case : Optional[Any]="resnet50" , snake_case : Optional[int]=True , snake_case : Any=False , snake_case : int=1 , snake_case : Tuple=5 , snake_case : Optional[int]=2 , snake_case : Tuple=1 , snake_case : Optional[Any]=1 , snake_case : Optional[Any]=5 , snake_case : Dict=2 , snake_case : Any=0.1 , **snake_case : Any , ): '''simple docstring''' 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.""" ) A__ : Optional[Any] = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(snake_case , snake_case ): A__ : Optional[int] = backbone_config.get("""model_type""" ) A__ : Optional[int] = CONFIG_MAPPING[backbone_model_type] A__ : List[str] = config_class.from_dict(snake_case ) # set timm attributes to None A__ , A__ , A__ : str = None, None, None A__ : Tuple = use_timm_backbone A__ : str = backbone_config A__ : str = num_channels A__ : List[Any] = num_queries A__ : Optional[Any] = d_model A__ : Tuple = encoder_ffn_dim A__ : Union[str, Any] = encoder_layers A__ : List[Any] = encoder_attention_heads A__ : Optional[int] = decoder_ffn_dim A__ : Any = decoder_layers A__ : int = decoder_attention_heads A__ : Any = dropout A__ : Dict = attention_dropout A__ : Dict = activation_dropout A__ : Tuple = activation_function A__ : List[str] = init_std A__ : List[str] = init_xavier_std A__ : Any = encoder_layerdrop A__ : Optional[Any] = decoder_layerdrop A__ : Union[str, Any] = encoder_layers A__ : Dict = auxiliary_loss A__ : List[Any] = position_embedding_type A__ : Optional[Any] = backbone A__ : str = use_pretrained_backbone A__ : Union[str, Any] = dilation # Hungarian matcher A__ : Tuple = class_cost A__ : Optional[Any] = bbox_cost A__ : Dict = giou_cost # Loss coefficients A__ : Any = mask_loss_coefficient A__ : str = dice_loss_coefficient A__ : str = bbox_loss_coefficient A__ : Union[str, Any] = giou_loss_coefficient A__ : List[str] = eos_coefficient super().__init__(is_encoder_decoder=snake_case , **snake_case ) @property def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return self.encoder_attention_heads @property def _UpperCamelCase ( self : Dict ): '''simple docstring''' return self.d_model class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = version.parse('1.11' ) @property def _UpperCamelCase ( self : Any ): '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' return 1e-5 @property def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return 12
296
0
"""simple docstring""" from bisect import bisect from itertools import accumulate def _lowerCAmelCase ( UpperCAmelCase__ : Tuple, UpperCAmelCase__ : Any, UpperCAmelCase__ : List[str], UpperCAmelCase__ : str ) ->Any: A__ : int = sorted(zip(lowercase_, lowercase_ ), key=lambda UpperCAmelCase__ : x[0] / x[1], reverse=lowercase_ ) A__ , A__ : List[str] = [i[0] for i in r], [i[1] for i in r] A__ : str = list(accumulate(lowercase_ ) ) A__ : Any = bisect(lowercase_, lowercase_ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
357
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = 'Salesforce/blip-image-captioning-base' snake_case_ = ( 'This is a tool that generates a description of an image. It takes an input named `image` which should be the ' 'image to caption, and returns a text that contains the description in English.' ) snake_case_ = 'image_captioner' snake_case_ = AutoModelForVisionaSeq snake_case_ = ['image'] snake_case_ = ['text'] def __init__( self : int , *snake_case : Optional[int] , **snake_case : Optional[int] ): '''simple docstring''' requires_backends(self , ["""vision"""] ) super().__init__(*snake_case , **snake_case ) def _UpperCamelCase ( self : int , snake_case : "Image" ): '''simple docstring''' return self.pre_processor(images=snake_case , return_tensors="""pt""" ) def _UpperCamelCase ( self : int , snake_case : List[Any] ): '''simple docstring''' return self.model.generate(**snake_case ) def _UpperCamelCase ( self : Optional[int] , snake_case : Any ): '''simple docstring''' return self.pre_processor.batch_decode(snake_case , skip_special_tokens=snake_case )[0].strip()
296
0
"""simple docstring""" import argparse import os from pathlib import Path import torch from bark.generation import _load_model as _bark_load_model from huggingface_hub import hf_hub_download from transformers import EncodecConfig, EncodecModel, set_seed from transformers.models.bark.configuration_bark import ( BarkCoarseConfig, BarkConfig, BarkFineConfig, BarkSemanticConfig, ) from transformers.models.bark.generation_configuration_bark import ( BarkCoarseGenerationConfig, BarkFineGenerationConfig, BarkGenerationConfig, BarkSemanticGenerationConfig, ) from transformers.models.bark.modeling_bark import BarkCoarseModel, BarkFineModel, BarkModel, BarkSemanticModel from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) set_seed(770) A_ = { '''c_attn''': '''att_proj''', '''c_proj''': '''out_proj''', '''c_fc''': '''in_proj''', '''transformer.''': '''''', '''h.''': '''layers.''', '''ln_1''': '''layernorm_1''', '''ln_2''': '''layernorm_2''', '''ln_f''': '''layernorm_final''', '''wpe''': '''position_embeds_layer''', '''wte''': '''input_embeds_layer''', } A_ = { '''text_small''': { '''repo_id''': '''suno/bark''', '''file_name''': '''text.pt''', }, '''coarse_small''': { '''repo_id''': '''suno/bark''', '''file_name''': '''coarse.pt''', }, '''fine_small''': { '''repo_id''': '''suno/bark''', '''file_name''': '''fine.pt''', }, '''text''': { '''repo_id''': '''suno/bark''', '''file_name''': '''text_2.pt''', }, '''coarse''': { '''repo_id''': '''suno/bark''', '''file_name''': '''coarse_2.pt''', }, '''fine''': { '''repo_id''': '''suno/bark''', '''file_name''': '''fine_2.pt''', }, } A_ = os.path.dirname(os.path.abspath(__file__)) A_ = os.path.join(os.path.expanduser('''~'''), '''.cache''') A_ = os.path.join(os.getenv('''XDG_CACHE_HOME''', default_cache_dir), '''suno''', '''bark_v0''') def _lowerCAmelCase ( UpperCAmelCase__ : int, UpperCAmelCase__ : Optional[Any]=False ) ->Union[str, Any]: A__ : Optional[int] = model_type if use_small: key += "_small" return os.path.join(A_, REMOTE_MODEL_PATHS[key]["""file_name"""] ) def _lowerCAmelCase ( UpperCAmelCase__ : Any, UpperCAmelCase__ : Optional[int] ) ->Any: os.makedirs(A_, exist_ok=A_ ) hf_hub_download(repo_id=A_, filename=A_, local_dir=A_ ) def _lowerCAmelCase ( UpperCAmelCase__ : List[Any], UpperCAmelCase__ : Optional[Any], UpperCAmelCase__ : Optional[Any]=False, UpperCAmelCase__ : Dict="text" ) ->List[Any]: if model_type == "text": A__ : Any = BarkSemanticModel A__ : str = BarkSemanticConfig A__ : Optional[int] = BarkSemanticGenerationConfig elif model_type == "coarse": A__ : Tuple = BarkCoarseModel A__ : str = BarkCoarseConfig A__ : Optional[Any] = BarkCoarseGenerationConfig elif model_type == "fine": A__ : str = BarkFineModel A__ : Dict = BarkFineConfig A__ : int = BarkFineGenerationConfig else: raise NotImplementedError() A__ : str = f'{model_type}_small' if use_small else model_type A__ : Dict = REMOTE_MODEL_PATHS[model_key] if not os.path.exists(A_ ): logger.info(f'{model_type} model not found, downloading into `{CACHE_DIR}`.' ) _download(model_info["""repo_id"""], model_info["""file_name"""] ) A__ : str = torch.load(A_, map_location=A_ ) # this is a hack A__ : Union[str, Any] = checkpoint['''model_args'''] if "input_vocab_size" not in model_args: A__ : Tuple = model_args['''vocab_size'''] A__ : Optional[Any] = model_args['''vocab_size'''] del model_args["vocab_size"] # convert Bark model arguments to HF Bark model arguments A__ : Tuple = model_args.pop("""n_head""" ) A__ : Dict = model_args.pop("""n_embd""" ) A__ : Dict = model_args.pop("""n_layer""" ) A__ : Optional[Any] = ConfigClass(**checkpoint["""model_args"""] ) A__ : int = ModelClass(config=A_ ) A__ : List[Any] = GenerationConfigClass() A__ : List[Any] = model_generation_config A__ : List[Any] = checkpoint['''model'''] # fixup checkpoint A__ : List[str] = '''_orig_mod.''' for k, v in list(state_dict.items() ): if k.startswith(A_ ): # replace part of the key with corresponding layer name in HF implementation A__ : Tuple = k[len(A_ ) :] for old_layer_name in new_layer_name_dict: A__ : str = new_k.replace(A_, new_layer_name_dict[old_layer_name] ) A__ : Any = state_dict.pop(A_ ) A__ : Tuple = set(state_dict.keys() ) - set(model.state_dict().keys() ) A__ : Dict = {k for k in extra_keys if not k.endswith(""".attn.bias""" )} A__ : List[str] = set(model.state_dict().keys() ) - set(state_dict.keys() ) A__ : Optional[int] = {k for k in missing_keys if not k.endswith(""".attn.bias""" )} if len(A_ ) != 0: raise ValueError(f'extra keys found: {extra_keys}' ) if len(A_ ) != 0: raise ValueError(f'missing keys: {missing_keys}' ) model.load_state_dict(A_, strict=A_ ) A__ : Optional[int] = model.num_parameters(exclude_embeddings=A_ ) A__ : int = checkpoint['''best_val_loss'''].item() logger.info(f'model loaded: {round(n_params/1e6, 1 )}M params, {round(A_, 3 )} loss' ) model.eval() model.to(A_ ) del checkpoint, state_dict return model def _lowerCAmelCase ( UpperCAmelCase__ : Any, UpperCAmelCase__ : List[str]=False, UpperCAmelCase__ : List[Any]="text" ) ->Any: if model_type not in ("text", "coarse", "fine"): raise NotImplementedError() A__ : Optional[Any] = '''cpu''' # do conversion on cpu A__ : Tuple = _get_ckpt_path(A_, use_small=A_ ) A__ : Dict = _load_model(A_, A_, model_type=A_, use_small=A_ ) # load bark initial model A__ : int = _bark_load_model(A_, """cpu""", model_type=A_, use_small=A_ ) if model_type == "text": A__ : Optional[Any] = bark_model['''model'''] if model.num_parameters(exclude_embeddings=A_ ) != bark_model.get_num_params(): raise ValueError("""initial and new models don\'t have the same number of parameters""" ) # check if same output as the bark model A__ : Optional[int] = 5 A__ : Any = 1_0 if model_type in ["text", "coarse"]: A__ : Optional[int] = torch.randint(2_5_6, (batch_size, sequence_length), dtype=torch.int ) A__ : Optional[Any] = bark_model(A_ )[0] A__ : List[Any] = model(A_ ) # take last logits A__ : List[str] = output_new_model_total.logits[:, [-1], :] else: A__ : Optional[Any] = 3 A__ : List[Any] = 8 A__ : Union[str, Any] = torch.randint(2_5_6, (batch_size, sequence_length, n_codes_total), dtype=torch.int ) A__ : Union[str, Any] = model(A_, A_ ) A__ : List[str] = bark_model(A_, A_ ) A__ : int = output_new_model_total.logits # output difference should come from the difference of self-attention implementation design if output_new_model.shape != output_old_model.shape: raise ValueError("""initial and new outputs don\'t have the same shape""" ) if (output_new_model - output_old_model).abs().max().item() > 1e-3: raise ValueError("""initial and new outputs are not equal""" ) Path(A_ ).mkdir(exist_ok=A_ ) model.save_pretrained(A_ ) def _lowerCAmelCase ( UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : Union[str, Any], UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : Dict, UpperCAmelCase__ : List[Any], UpperCAmelCase__ : int, ) ->Tuple: A__ : Optional[Any] = os.path.join(A_, A_ ) A__ : Optional[Any] = BarkSemanticConfig.from_pretrained(os.path.join(A_, """config.json""" ) ) A__ : int = BarkCoarseConfig.from_pretrained(os.path.join(A_, """config.json""" ) ) A__ : Union[str, Any] = BarkFineConfig.from_pretrained(os.path.join(A_, """config.json""" ) ) A__ : Optional[Any] = EncodecConfig.from_pretrained("""facebook/encodec_24khz""" ) A__ : Optional[int] = BarkSemanticModel.from_pretrained(A_ ) A__ : int = BarkCoarseModel.from_pretrained(A_ ) A__ : Dict = BarkFineModel.from_pretrained(A_ ) A__ : Union[str, Any] = EncodecModel.from_pretrained("""facebook/encodec_24khz""" ) A__ : Dict = BarkConfig.from_sub_model_configs( A_, A_, A_, A_ ) A__ : Tuple = BarkGenerationConfig.from_sub_model_configs( semantic.generation_config, coarseAcoustic.generation_config, fineAcoustic.generation_config ) A__ : Tuple = BarkModel(A_ ) A__ : List[str] = semantic A__ : Optional[int] = coarseAcoustic A__ : int = fineAcoustic A__ : int = codec A__ : List[Any] = bark_generation_config Path(A_ ).mkdir(exist_ok=A_ ) bark.save_pretrained(A_, repo_id=A_, push_to_hub=A_ ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument('''model_type''', type=str, help='''text, coarse or fine.''') parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--is_small''', action='''store_true''', help='''convert the small version instead of the large.''') A_ = parser.parse_args() load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
358
"""simple docstring""" import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : List[Any] ): '''simple docstring''' super().__init__() A__ : int = nn.Linear(3 , 4 ) A__ : Union[str, Any] = nn.BatchNormad(4 ) A__ : Union[str, Any] = nn.Linear(4 , 5 ) def _UpperCamelCase ( self : str , snake_case : List[str] ): '''simple docstring''' return self.lineara(self.batchnorm(self.lineara(snake_case ) ) ) class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : int = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(snake_case , model.state_dict() ) A__ : List[str] = os.path.join(snake_case , """index.json""" ) self.assertTrue(os.path.isfile(snake_case ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: A__ : List[str] = os.path.join(snake_case , F'{key}.dat' ) self.assertTrue(os.path.isfile(snake_case ) ) # TODO: add tests on the fact weights are properly loaded def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Union[str, Any] = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: A__ : str = torch.randn(2 , 3 , dtype=snake_case ) with TemporaryDirectory() as tmp_dir: A__ : List[str] = offload_weight(snake_case , """weight""" , snake_case , {} ) A__ : Union[str, Any] = os.path.join(snake_case , """weight.dat""" ) self.assertTrue(os.path.isfile(snake_case ) ) self.assertDictEqual(snake_case , {"""weight""": {"""shape""": [2, 3], """dtype""": str(snake_case ).split(""".""" )[1]}} ) A__ : str = load_offloaded_weight(snake_case , index["""weight"""] ) self.assertTrue(torch.equal(snake_case , snake_case ) ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : str = ModelForTest() A__ : Union[str, Any] = model.state_dict() A__ : Optional[int] = {k: v for k, v in state_dict.items() if """linear2""" not in k} A__ : List[Any] = {k: v for k, v in state_dict.items() if """linear2""" in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(snake_case , snake_case ) A__ : Dict = OffloadedWeightsLoader(state_dict=snake_case , save_folder=snake_case ) # Every key is there with the right value self.assertEqual(sorted(snake_case ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(snake_case , weight_map[key] ) ) A__ : int = {k: v for k, v in state_dict.items() if """weight""" in k} A__ : Tuple = {k: v for k, v in state_dict.items() if """weight""" not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(snake_case , snake_case ) A__ : Optional[Any] = OffloadedWeightsLoader(state_dict=snake_case , save_folder=snake_case ) # Every key is there with the right value self.assertEqual(sorted(snake_case ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(snake_case , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(snake_case , snake_case ) # Duplicates are removed A__ : int = OffloadedWeightsLoader(state_dict=snake_case , save_folder=snake_case ) # Every key is there with the right value self.assertEqual(sorted(snake_case ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(snake_case , weight_map[key] ) ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : List[str] = {"""a.1""": 0, """a.10""": 1, """a.2""": 2} A__ : str = extract_submodules_state_dict(snake_case , ["""a.1""", """a.2"""] ) self.assertDictEqual(snake_case , {"""a.1""": 0, """a.2""": 2} ) A__ : Dict = {"""a.1.a""": 0, """a.10.a""": 1, """a.2.a""": 2} A__ : int = extract_submodules_state_dict(snake_case , ["""a.1""", """a.2"""] ) self.assertDictEqual(snake_case , {"""a.1.a""": 0, """a.2.a""": 2} )
296
0
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 __SCREAMING_SNAKE_CASE : def __init__( self : List[Any] , snake_case : List[Any] , snake_case : Dict=3 , snake_case : Optional[int]=32 , snake_case : List[Any]=3 , snake_case : Optional[int]=10 , snake_case : str=[8, 16, 32, 64] , snake_case : int=[1, 1, 2, 1] , snake_case : str=True , snake_case : List[str]=True , snake_case : Optional[int]="relu" , snake_case : List[Any]=3 , snake_case : List[Any]=None , snake_case : int=["stage2", "stage3", "stage4"] , snake_case : List[Any]=[2, 3, 4] , snake_case : Optional[Any]=1 , ): '''simple docstring''' A__ : Optional[Any] = parent A__ : int = batch_size A__ : Tuple = image_size A__ : Any = num_channels A__ : Dict = embeddings_size A__ : List[str] = hidden_sizes A__ : Union[str, Any] = depths A__ : str = is_training A__ : Union[str, Any] = use_labels A__ : Tuple = hidden_act A__ : Any = num_labels A__ : Union[str, Any] = scope A__ : Tuple = len(__A ) A__ : Optional[int] = out_features A__ : List[Any] = out_indices A__ : Tuple = num_groups def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A__ : str = None if self.use_labels: A__ : Dict = ids_tensor([self.batch_size] , self.num_labels ) A__ : int = self.get_config() return config, pixel_values, labels def _UpperCamelCase ( self : str ): '''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 _UpperCamelCase ( self : Union[str, Any] , snake_case : Optional[Any] , snake_case : Optional[int] , snake_case : Dict ): '''simple docstring''' A__ : int = BitModel(config=__A ) model.to(__A ) model.eval() A__ : Union[str, Any] = model(__A ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def _UpperCamelCase ( self : Any , snake_case : Union[str, Any] , snake_case : str , snake_case : str ): '''simple docstring''' A__ : Dict = self.num_labels A__ : Optional[Any] = BitForImageClassification(__A ) model.to(__A ) model.eval() A__ : Optional[int] = model(__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _UpperCamelCase ( self : Dict , snake_case : Optional[Any] , snake_case : Optional[int] , snake_case : str ): '''simple docstring''' A__ : str = BitBackbone(config=__A ) model.to(__A ) model.eval() A__ : str = model(__A ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.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 A__ : Dict = None A__ : str = BitBackbone(config=__A ) model.to(__A ) model.eval() A__ : str = model(__A ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Any = self.prepare_config_and_inputs() A__ , A__ , A__ : Optional[Any] = config_and_inputs A__ : Any = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , unittest.TestCase ): snake_case_ = (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else () snake_case_ = ( {'feature-extraction': BitModel, 'image-classification': BitForImageClassification} if is_torch_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : List[str] = BitModelTester(self ) A__ : Any = ConfigTester(self , config_class=__A , has_text_modality=__A ) def _UpperCamelCase ( self : Dict ): '''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 _UpperCamelCase ( self : str ): '''simple docstring''' return @unittest.skip(reason="""Bit does not output attentions""" ) def _UpperCamelCase ( self : Any ): '''simple docstring''' pass @unittest.skip(reason="""Bit does not use inputs_embeds""" ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' pass @unittest.skip(reason="""Bit does not support input and output embeddings""" ) def _UpperCamelCase ( self : Dict ): '''simple docstring''' pass def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ , A__ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ : Union[str, Any] = model_class(__A ) A__ : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A__ : Optional[Any] = [*signature.parameters.keys()] A__ : str = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __A ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*__A ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ , A__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ : Dict = model_class(config=__A ) for name, module in model.named_modules(): if isinstance(__A , (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 _UpperCamelCase ( self : Tuple ): '''simple docstring''' def check_hidden_states_output(snake_case : List[str] , snake_case : Dict , snake_case : Any ): A__ : Union[str, Any] = model_class(__A ) model.to(__A ) model.eval() with torch.no_grad(): A__ : List[str] = model(**self._prepare_for_class(__A , __A ) ) A__ : List[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states A__ : int = self.model_tester.num_stages self.assertEqual(len(__A ) , 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] , ) A__ , A__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() A__ : List[Any] = ["""preactivation""", """bottleneck"""] for model_class in self.all_model_classes: for layer_type in layers_type: A__ : int = layer_type A__ : Union[str, Any] = True check_hidden_states_output(__A , __A , __A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A__ : List[str] = True check_hidden_states_output(__A , __A , __A ) @unittest.skip(reason="""Bit does not use feedforward chunking""" ) def _UpperCamelCase ( self : Dict ): '''simple docstring''' pass def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__A ) @slow def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ : Optional[Any] = BitModel.from_pretrained(__A ) self.assertIsNotNone(__A ) def _lowerCAmelCase ( ) ->str: A__ : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def _UpperCamelCase ( self : Any ): '''simple docstring''' return ( BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : int = BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(__A ) A__ : Any = self.default_image_processor A__ : int = prepare_img() A__ : Any = image_processor(images=__A , return_tensors="""pt""" ).to(__A ) # forward pass with torch.no_grad(): A__ : Any = model(**__A ) # verify the logits A__ : List[str] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __A ) A__ : Optional[int] = torch.tensor([[-0.6526, -0.5263, -1.4398]] ).to(__A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __A , atol=1e-4 ) ) @require_torch class __SCREAMING_SNAKE_CASE ( UpperCamelCase , unittest.TestCase ): snake_case_ = (BitBackbone,) if is_torch_available() else () snake_case_ = BitConfig snake_case_ = False def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : str = BitModelTester(self )
359
"""simple docstring""" import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class __SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , snake_case : str , snake_case : List[Any]=13 , snake_case : Union[str, Any]=7 , snake_case : Optional[Any]=True , snake_case : str=True , snake_case : Dict=False , snake_case : Union[str, Any]=True , snake_case : Optional[Any]=99 , snake_case : str=32 , snake_case : Tuple=5 , snake_case : List[str]=4 , snake_case : Optional[int]=37 , snake_case : str="gelu" , snake_case : Tuple=0.1 , snake_case : Optional[int]=0.1 , snake_case : int=512 , snake_case : List[str]=16 , snake_case : str=2 , snake_case : Optional[int]=0.02 , snake_case : str=3 , snake_case : Dict=4 , snake_case : Optional[Any]=None , ): '''simple docstring''' A__ : int = parent A__ : Union[str, Any] = batch_size A__ : Optional[int] = seq_length A__ : List[Any] = is_training A__ : List[str] = use_input_mask A__ : Optional[Any] = use_token_type_ids A__ : List[Any] = use_labels A__ : Union[str, Any] = vocab_size A__ : List[Any] = hidden_size A__ : Any = num_hidden_layers A__ : Any = num_attention_heads A__ : Optional[int] = intermediate_size A__ : Any = hidden_act A__ : Tuple = hidden_dropout_prob A__ : Dict = attention_probs_dropout_prob A__ : Optional[int] = max_position_embeddings A__ : Tuple = type_vocab_size A__ : Union[str, Any] = type_sequence_label_size A__ : List[str] = initializer_range A__ : Any = num_labels A__ : Any = num_choices A__ : int = scope def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Tuple = None if self.use_input_mask: A__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) A__ : Union[str, Any] = None if self.use_token_type_ids: A__ : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A__ : int = None A__ : int = None A__ : List[str] = None if self.use_labels: A__ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : Dict = ids_tensor([self.batch_size] , self.num_choices ) A__ : Union[str, Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCamelCase ( self : Tuple ): '''simple docstring''' return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case , initializer_range=self.initializer_range , ) def _UpperCamelCase ( self : Optional[int] , snake_case : Dict , snake_case : Any , snake_case : Dict , snake_case : Any , snake_case : Union[str, Any] , snake_case : Tuple , snake_case : Optional[Any] ): '''simple docstring''' A__ : Optional[Any] = BioGptModel(config=snake_case ) model.to(snake_case ) model.eval() A__ : List[Any] = model(snake_case , attention_mask=snake_case ) A__ : Dict = model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : Optional[int] , snake_case : Dict , snake_case : Optional[int] , snake_case : List[str] , snake_case : str , snake_case : Optional[Any] , snake_case : List[str] , snake_case : List[Any] , snake_case : Tuple , snake_case : Optional[Any] , ): '''simple docstring''' A__ : List[str] = BioGptForCausalLM(config=snake_case ) model.to(snake_case ) model.eval() A__ : Union[str, Any] = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCamelCase ( self : Any , snake_case : str , snake_case : Tuple , snake_case : int , snake_case : Optional[Any] , snake_case : Any , *snake_case : Dict ): '''simple docstring''' A__ : Union[str, Any] = BioGptModel(config=snake_case ) model.to(snake_case ) model.eval() # create attention mask A__ : List[Any] = torch.ones(input_ids.shape , dtype=torch.long , device=snake_case ) A__ : Any = self.seq_length // 2 A__ : str = 0 # first forward pass A__ , A__ : List[Any] = model(snake_case , attention_mask=snake_case ).to_tuple() # create hypothetical next token and extent to next_input_ids A__ : int = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids A__ : List[str] = ids_tensor((1,) , snake_case ).item() + 1 A__ : Optional[int] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) A__ : int = random_other_next_tokens # append to next input_ids and attn_mask A__ : str = torch.cat([input_ids, next_tokens] , dim=-1 ) A__ : List[Any] = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=snake_case )] , dim=1 , ) # get two different outputs A__ : Union[str, Any] = model(snake_case , attention_mask=snake_case )["""last_hidden_state"""] A__ : Optional[int] = model(snake_case , past_key_values=snake_case , attention_mask=snake_case )["""last_hidden_state"""] # select random slice A__ : List[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() A__ : List[str] = output_from_no_past[:, -1, random_slice_idx].detach() A__ : Any = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(snake_case , snake_case , atol=1e-3 ) ) def _UpperCamelCase ( self : int , snake_case : Optional[Any] , snake_case : Optional[Any] , snake_case : str , snake_case : int , snake_case : Optional[Any] , *snake_case : str ): '''simple docstring''' A__ : Dict = BioGptModel(config=snake_case ).to(snake_case ).eval() A__ : Tuple = torch.ones(input_ids.shape , dtype=torch.long , device=snake_case ) # first forward pass A__ : Dict = model(snake_case , attention_mask=snake_case , use_cache=snake_case ) A__ , A__ : List[Any] = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids A__ : Union[str, Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ : int = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and A__ : str = torch.cat([input_ids, next_tokens] , dim=-1 ) A__ : Optional[int] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) A__ : Any = model(snake_case , attention_mask=snake_case )["""last_hidden_state"""] A__ : Union[str, Any] = model(snake_case , attention_mask=snake_case , past_key_values=snake_case )[ """last_hidden_state""" ] # select random slice A__ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() A__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() A__ : List[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(snake_case , snake_case , atol=1e-3 ) ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Tuple , snake_case : Union[str, Any] , snake_case : Optional[Any] , snake_case : Any , snake_case : Tuple , *snake_case : Union[str, Any] , snake_case : Union[str, Any]=False ): '''simple docstring''' A__ : Tuple = BioGptForCausalLM(snake_case ) model.to(snake_case ) if gradient_checkpointing: model.gradient_checkpointing_enable() A__ : Optional[Any] = model(snake_case , labels=snake_case ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def _UpperCamelCase ( self : int , snake_case : Optional[Any] , *snake_case : Optional[int] ): '''simple docstring''' A__ : int = BioGptModel(snake_case ) A__ : Union[str, Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def _UpperCamelCase ( self : Any , snake_case : Dict , snake_case : Tuple , snake_case : int , snake_case : Union[str, Any] , snake_case : Dict , *snake_case : Any ): '''simple docstring''' A__ : Union[str, Any] = self.num_labels A__ : int = BioGptForTokenClassification(snake_case ) model.to(snake_case ) model.eval() A__ : str = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : List[str] = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) : str = config_and_inputs A__ : Union[str, Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase ): snake_case_ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) snake_case_ = (BioGptForCausalLM,) if is_torch_available() else () snake_case_ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = False def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : List[str] = BioGptModelTester(self ) A__ : List[Any] = ConfigTester(self , config_class=snake_case , hidden_size=37 ) def _UpperCamelCase ( self : int ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Any ): '''simple docstring''' A__ : int = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A__ : str = type self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*snake_case ) def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*snake_case , gradient_checkpointing=snake_case ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*snake_case ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*snake_case ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*snake_case ) @slow def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : Tuple = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(snake_case ) A__ : Optional[int] = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) A__ : Any = """left""" # Define PAD Token = EOS Token = 50256 A__ : Optional[int] = tokenizer.eos_token A__ : Dict = model.config.eos_token_id # use different length sentences to test batching A__ : Union[str, Any] = [ """Hello, my dog is a little""", """Today, I""", ] A__ : List[str] = tokenizer(snake_case , return_tensors="""pt""" , padding=snake_case ) A__ : str = inputs["""input_ids"""].to(snake_case ) A__ : Dict = model.generate( input_ids=snake_case , attention_mask=inputs["""attention_mask"""].to(snake_case ) , ) A__ : Optional[int] = tokenizer(sentences[0] , return_tensors="""pt""" ).input_ids.to(snake_case ) A__ : Any = model.generate(input_ids=snake_case ) A__ : List[str] = inputs_non_padded.shape[-1] - inputs["""attention_mask"""][-1].long().sum().cpu().item() A__ : str = tokenizer(sentences[1] , return_tensors="""pt""" ).input_ids.to(snake_case ) A__ : Dict = model.generate(input_ids=snake_case , max_length=model.config.max_length - num_paddings ) A__ : Optional[Any] = tokenizer.batch_decode(snake_case , skip_special_tokens=snake_case ) A__ : List[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=snake_case ) A__ : str = tokenizer.decode(output_padded[0] , skip_special_tokens=snake_case ) A__ : Optional[int] = [ """Hello, my dog is a little bit bigger than a little bit.""", """Today, I have a good idea of how to use the information""", ] self.assertListEqual(snake_case , snake_case ) self.assertListEqual(snake_case , [non_padded_sentence, padded_sentence] ) @slow def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ : Optional[Any] = BioGptModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ , A__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() A__ : Optional[int] = 3 A__ : List[Any] = input_dict["""input_ids"""] A__ : Dict = input_ids.ne(1 ).to(snake_case ) A__ : Optional[Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) A__ : Union[str, Any] = BioGptForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : int = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ , A__ : str = self.model_tester.prepare_config_and_inputs_for_common() A__ : Any = 3 A__ : List[Any] = """multi_label_classification""" A__ : Dict = input_dict["""input_ids"""] A__ : Tuple = input_ids.ne(1 ).to(snake_case ) A__ : Any = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) A__ : Tuple = BioGptForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : List[str] = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : Optional[Any] = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) A__ : str = torch.tensor([[2, 4805, 9, 656, 21]] ) A__ : Dict = model(snake_case )[0] A__ : Tuple = 4_2384 A__ : str = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , snake_case ) A__ : str = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) ) @slow def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : Tuple = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) A__ : Any = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(snake_case ) torch.manual_seed(0 ) A__ : Tuple = tokenizer("""COVID-19 is""" , return_tensors="""pt""" ).to(snake_case ) A__ : Optional[int] = model.generate( **snake_case , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=snake_case , ) A__ : Optional[int] = tokenizer.decode(output_ids[0] , skip_special_tokens=snake_case ) A__ : List[str] = ( """COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the""" """ causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and""" """ territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),""" """ and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and""" """ more than 800,000 deaths.""" ) self.assertEqual(snake_case , snake_case )
296
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A_ = { "configuration_groupvit": [ "GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "GroupViTConfig", "GroupViTOnnxConfig", "GroupViTTextConfig", "GroupViTVisionConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "GroupViTModel", "GroupViTPreTrainedModel", "GroupViTTextModel", "GroupViTVisionModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFGroupViTModel", "TFGroupViTPreTrainedModel", "TFGroupViTTextModel", "TFGroupViTVisionModel", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
360
"""simple docstring""" 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 SPIECE_UNDERLINE, logging A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''spiece.model'''} A_ = { '''vocab_file''': { '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model''', '''xlnet-large-cased''': '''https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model''', } } A_ = { '''xlnet-base-cased''': None, '''xlnet-large-cased''': None, } # Segments (not really needed) A_ = 0 A_ = 1 A_ = 2 A_ = 3 A_ = 4 class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = 'left' def __init__( self : Dict , snake_case : int , snake_case : List[Any]=False , snake_case : List[str]=True , snake_case : Dict=False , snake_case : Optional[Any]="<s>" , snake_case : List[str]="</s>" , snake_case : Tuple="<unk>" , snake_case : Tuple="<sep>" , snake_case : Union[str, Any]="<pad>" , snake_case : Dict="<cls>" , snake_case : Optional[Any]="<mask>" , snake_case : Optional[int]=["<eop>", "<eod>"] , snake_case : Optional[Dict[str, Any]] = None , **snake_case : Dict , ): '''simple docstring''' A__ : Optional[int] = AddedToken(snake_case , lstrip=snake_case , rstrip=snake_case ) if isinstance(snake_case , snake_case ) else mask_token A__ : Union[str, Any] = {} 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 , additional_special_tokens=snake_case , sp_model_kwargs=self.sp_model_kwargs , **snake_case , ) A__ : str = 3 A__ : str = do_lower_case A__ : Optional[Any] = remove_space A__ : List[Any] = keep_accents A__ : Union[str, Any] = vocab_file A__ : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(snake_case ) @property def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' return len(self.sp_model ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : 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 : str ): '''simple docstring''' A__ : int = self.__dict__.copy() A__ : int = None return state def __setstate__( self : Tuple , snake_case : Union[str, Any] ): '''simple docstring''' A__ : int = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): A__ : Optional[int] = {} A__ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _UpperCamelCase ( self : List[str] , snake_case : Optional[Any] ): '''simple docstring''' if self.remove_space: A__ : Optional[Any] = """ """.join(inputs.strip().split() ) else: A__ : Dict = inputs A__ : str = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: A__ : Any = unicodedata.normalize("""NFKD""" , snake_case ) A__ : Optional[int] = """""".join([c for c in outputs if not unicodedata.combining(snake_case )] ) if self.do_lower_case: A__ : Any = outputs.lower() return outputs def _UpperCamelCase ( self : Union[str, Any] , snake_case : str ): '''simple docstring''' A__ : Dict = self.preprocess_text(snake_case ) A__ : Dict = self.sp_model.encode(snake_case , out_type=snake_case ) A__ : Optional[int] = [] for piece in pieces: if len(snake_case ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): A__ : Optional[Any] = 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__ : Any = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(snake_case ) else: new_pieces.append(snake_case ) return new_pieces def _UpperCamelCase ( self : List[str] , snake_case : Tuple ): '''simple docstring''' return self.sp_model.PieceToId(snake_case ) def _UpperCamelCase ( self : List[str] , snake_case : Any ): '''simple docstring''' return self.sp_model.IdToPiece(snake_case ) def _UpperCamelCase ( self : Optional[int] , snake_case : Any ): '''simple docstring''' A__ : Union[str, Any] = """""".join(snake_case ).replace(snake_case , """ """ ).strip() return out_string def _UpperCamelCase ( self : int , snake_case : List[int] , snake_case : bool = False , snake_case : bool = None , snake_case : bool = True , **snake_case : Union[str, Any] , ): '''simple docstring''' A__ : List[str] = kwargs.pop("""use_source_tokenizer""" , snake_case ) A__ : Any = self.convert_ids_to_tokens(snake_case , skip_special_tokens=snake_case ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 A__ : Any = [] A__ : Any = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(snake_case ) ) A__ : str = [] sub_texts.append(snake_case ) else: current_sub_text.append(snake_case ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(snake_case ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens A__ : Dict = """""".join(snake_case ) A__ : int = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: A__ : Tuple = self.clean_up_tokenization(snake_case ) return clean_text else: return text def _UpperCamelCase ( self : str , snake_case : List[int] , snake_case : Optional[List[int]] = None ): '''simple docstring''' A__ : Tuple = [self.sep_token_id] A__ : Dict = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _UpperCamelCase ( self : Dict , snake_case : List[int] , snake_case : Optional[List[int]] = None , snake_case : bool = False ): '''simple docstring''' 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 ([0] * len(snake_case )) + [1] + ([0] * len(snake_case )) + [1, 1] return ([0] * len(snake_case )) + [1, 1] def _UpperCamelCase ( self : str , snake_case : List[int] , snake_case : Optional[List[int]] = None ): '''simple docstring''' A__ : Any = [self.sep_token_id] A__ : int = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _UpperCamelCase ( self : Optional[Any] , snake_case : str , snake_case : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(snake_case ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A__ : List[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__ : Optional[Any] = self.sp_model.serialized_model_proto() fi.write(snake_case ) return (out_vocab_file,)
296
0
"""simple docstring""" from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class __SCREAMING_SNAKE_CASE : snake_case_ = 42 snake_case_ = None snake_case_ = None def _lowerCAmelCase ( ) ->List[Any]: A__ : Optional[int] = Node(1 ) A__ : Optional[int] = Node(2 ) A__ : Tuple = Node(3 ) A__ : Any = Node(4 ) A__ : str = Node(5 ) return tree def _lowerCAmelCase ( UpperCAmelCase__ : Node | None ) ->Optional[Any]: return [root.data, *preorder(root.left ), *preorder(root.right )] if root else [] def _lowerCAmelCase ( UpperCAmelCase__ : Node | None ) ->List[str]: return postorder(root.left ) + postorder(root.right ) + [root.data] if root else [] def _lowerCAmelCase ( UpperCAmelCase__ : Node | None ) ->Optional[int]: return [*inorder(root.left ), root.data, *inorder(root.right )] if root else [] def _lowerCAmelCase ( UpperCAmelCase__ : Node | None ) ->Union[str, Any]: return (max(height(root.left ), height(root.right ) ) + 1) if root else 0 def _lowerCAmelCase ( UpperCAmelCase__ : Node | None ) ->Any: A__ : Any = [] if root is None: return output A__ : str = deque([root] ) while process_queue: A__ : str = process_queue.popleft() output.append(node.data ) if node.left: process_queue.append(node.left ) if node.right: process_queue.append(node.right ) return output def _lowerCAmelCase ( UpperCAmelCase__ : Node | None, UpperCAmelCase__ : int ) ->Union[str, Any]: A__ : Any = [] def populate_output(UpperCAmelCase__ : Node | None, UpperCAmelCase__ : int ) -> None: if not root: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.left, level - 1 ) populate_output(root.right, level - 1 ) populate_output(_a, _a ) return output def _lowerCAmelCase ( UpperCAmelCase__ : Node | None, UpperCAmelCase__ : int ) ->int: A__ : List[Any] = [] def populate_output(UpperCAmelCase__ : Node | None, UpperCAmelCase__ : int ) -> None: if root is None: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.right, level - 1 ) populate_output(root.left, level - 1 ) populate_output(_a, _a ) return output def _lowerCAmelCase ( UpperCAmelCase__ : Node | None ) ->Any: if root is None: return [] A__ : Union[str, Any] = [] A__ : List[Any] = 0 A__ : Dict = height(_a ) for h in range(1, height_tree + 1 ): if not flag: output.append(get_nodes_from_left_to_right(_a, _a ) ) A__ : str = 1 else: output.append(get_nodes_from_right_to_left(_a, _a ) ) A__ : Union[str, Any] = 0 return output def _lowerCAmelCase ( ) ->List[str]: # Main function for testing. A__ : int = make_tree() print(f'In-order Traversal: {inorder(_a )}' ) print(f'Pre-order Traversal: {preorder(_a )}' ) print(f'Post-order Traversal: {postorder(_a )}', """\n""" ) print(f'Height of Tree: {height(_a )}', """\n""" ) print("""Complete Level Order Traversal: """ ) print(level_order(_a ), """\n""" ) print("""Level-wise order Traversal: """ ) for level in range(1, height(_a ) + 1 ): print(f'Level {level}:', get_nodes_from_left_to_right(_a, level=_a ) ) print("""\nZigZag order Traversal: """ ) print(zigzag(_a ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
361
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) def _lowerCAmelCase ( UpperCAmelCase__ : List[Any] ) ->List[str]: A__ : Union[str, Any] = DPTConfig() if "large" in checkpoint_url: A__ : int = 1_0_2_4 A__ : Union[str, Any] = 4_0_9_6 A__ : Optional[int] = 2_4 A__ : int = 1_6 A__ : Union[str, Any] = [5, 1_1, 1_7, 2_3] A__ : Tuple = [2_5_6, 5_1_2, 1_0_2_4, 1_0_2_4] A__ : Tuple = (1, 3_8_4, 3_8_4) if "ade" in checkpoint_url: A__ : Optional[int] = True A__ : int = 1_5_0 A__ : Union[str, Any] = """huggingface/label-files""" A__ : List[Any] = """ade20k-id2label.json""" A__ : Union[str, Any] = json.load(open(cached_download(hf_hub_url(UpperCAmelCase__, UpperCAmelCase__, repo_type="""dataset""" ) ), """r""" ) ) A__ : List[Any] = {int(UpperCAmelCase__ ): v for k, v in idalabel.items()} A__ : Dict = idalabel A__ : List[Any] = {v: k for k, v in idalabel.items()} A__ : Optional[Any] = [1, 1_5_0, 4_8_0, 4_8_0] return config, expected_shape def _lowerCAmelCase ( UpperCAmelCase__ : int ) ->Any: A__ : List[Any] = ["""pretrained.model.head.weight""", """pretrained.model.head.bias"""] for k in ignore_keys: state_dict.pop(UpperCAmelCase__, UpperCAmelCase__ ) def _lowerCAmelCase ( UpperCAmelCase__ : Union[str, Any] ) ->List[str]: if ( "pretrained.model" in name and "cls_token" not in name and "pos_embed" not in name and "patch_embed" not in name ): A__ : str = name.replace("""pretrained.model""", """dpt.encoder""" ) if "pretrained.model" in name: A__ : Dict = name.replace("""pretrained.model""", """dpt.embeddings""" ) if "patch_embed" in name: A__ : List[Any] = name.replace("""patch_embed""", """patch_embeddings""" ) if "pos_embed" in name: A__ : int = name.replace("""pos_embed""", """position_embeddings""" ) if "attn.proj" in name: A__ : Tuple = name.replace("""attn.proj""", """attention.output.dense""" ) if "proj" in name and "project" not in name: A__ : List[Any] = name.replace("""proj""", """projection""" ) if "blocks" in name: A__ : Optional[Any] = name.replace("""blocks""", """layer""" ) if "mlp.fc1" in name: A__ : int = name.replace("""mlp.fc1""", """intermediate.dense""" ) if "mlp.fc2" in name: A__ : List[str] = name.replace("""mlp.fc2""", """output.dense""" ) if "norm1" in name: A__ : Any = name.replace("""norm1""", """layernorm_before""" ) if "norm2" in name: A__ : List[str] = name.replace("""norm2""", """layernorm_after""" ) if "scratch.output_conv" in name: A__ : Optional[int] = name.replace("""scratch.output_conv""", """head""" ) if "scratch" in name: A__ : List[str] = name.replace("""scratch""", """neck""" ) if "layer1_rn" in name: A__ : List[str] = name.replace("""layer1_rn""", """convs.0""" ) if "layer2_rn" in name: A__ : Optional[int] = name.replace("""layer2_rn""", """convs.1""" ) if "layer3_rn" in name: A__ : Any = name.replace("""layer3_rn""", """convs.2""" ) if "layer4_rn" in name: A__ : Any = name.replace("""layer4_rn""", """convs.3""" ) if "refinenet" in name: A__ : Union[str, Any] = int(name[len("""neck.refinenet""" ) : len("""neck.refinenet""" ) + 1] ) # tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3 A__ : str = name.replace(f'refinenet{layer_idx}', f'fusion_stage.layers.{abs(layer_idx-4 )}' ) if "out_conv" in name: A__ : Optional[Any] = name.replace("""out_conv""", """projection""" ) if "resConfUnit1" in name: A__ : List[Any] = name.replace("""resConfUnit1""", """residual_layer1""" ) if "resConfUnit2" in name: A__ : Tuple = name.replace("""resConfUnit2""", """residual_layer2""" ) if "conv1" in name: A__ : Tuple = name.replace("""conv1""", """convolution1""" ) if "conv2" in name: A__ : List[Any] = name.replace("""conv2""", """convolution2""" ) # readout blocks if "pretrained.act_postprocess1.0.project.0" in name: A__ : Union[str, Any] = name.replace("""pretrained.act_postprocess1.0.project.0""", """neck.reassemble_stage.readout_projects.0.0""" ) if "pretrained.act_postprocess2.0.project.0" in name: A__ : Tuple = name.replace("""pretrained.act_postprocess2.0.project.0""", """neck.reassemble_stage.readout_projects.1.0""" ) if "pretrained.act_postprocess3.0.project.0" in name: A__ : Optional[Any] = name.replace("""pretrained.act_postprocess3.0.project.0""", """neck.reassemble_stage.readout_projects.2.0""" ) if "pretrained.act_postprocess4.0.project.0" in name: A__ : Optional[Any] = name.replace("""pretrained.act_postprocess4.0.project.0""", """neck.reassemble_stage.readout_projects.3.0""" ) # resize blocks if "pretrained.act_postprocess1.3" in name: A__ : Any = name.replace("""pretrained.act_postprocess1.3""", """neck.reassemble_stage.layers.0.projection""" ) if "pretrained.act_postprocess1.4" in name: A__ : List[Any] = name.replace("""pretrained.act_postprocess1.4""", """neck.reassemble_stage.layers.0.resize""" ) if "pretrained.act_postprocess2.3" in name: A__ : Dict = name.replace("""pretrained.act_postprocess2.3""", """neck.reassemble_stage.layers.1.projection""" ) if "pretrained.act_postprocess2.4" in name: A__ : Optional[Any] = name.replace("""pretrained.act_postprocess2.4""", """neck.reassemble_stage.layers.1.resize""" ) if "pretrained.act_postprocess3.3" in name: A__ : Union[str, Any] = name.replace("""pretrained.act_postprocess3.3""", """neck.reassemble_stage.layers.2.projection""" ) if "pretrained.act_postprocess4.3" in name: A__ : Optional[int] = name.replace("""pretrained.act_postprocess4.3""", """neck.reassemble_stage.layers.3.projection""" ) if "pretrained.act_postprocess4.4" in name: A__ : Dict = name.replace("""pretrained.act_postprocess4.4""", """neck.reassemble_stage.layers.3.resize""" ) if "pretrained" in name: A__ : Union[str, Any] = name.replace("""pretrained""", """dpt""" ) if "bn" in name: A__ : Union[str, Any] = name.replace("""bn""", """batch_norm""" ) if "head" in name: A__ : Dict = name.replace("""head""", """head.head""" ) if "encoder.norm" in name: A__ : Optional[int] = name.replace("""encoder.norm""", """layernorm""" ) if "auxlayer" in name: A__ : List[str] = name.replace("""auxlayer""", """auxiliary_head.head""" ) return name def _lowerCAmelCase ( UpperCAmelCase__ : int, UpperCAmelCase__ : Dict ) ->str: for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) A__ : Any = state_dict.pop(f'dpt.encoder.layer.{i}.attn.qkv.weight' ) A__ : Tuple = state_dict.pop(f'dpt.encoder.layer.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict A__ : List[str] = in_proj_weight[: config.hidden_size, :] A__ : int = in_proj_bias[: config.hidden_size] A__ : Tuple = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] A__ : Any = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] A__ : str = in_proj_weight[ -config.hidden_size :, : ] A__ : Optional[Any] = in_proj_bias[-config.hidden_size :] def _lowerCAmelCase ( ) ->List[str]: A__ : int = """http://images.cocodataset.org/val2017/000000039769.jpg""" A__ : int = Image.open(requests.get(UpperCAmelCase__, stream=UpperCAmelCase__ ).raw ) return im @torch.no_grad() def _lowerCAmelCase ( UpperCAmelCase__ : int, UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : str, UpperCAmelCase__ : int ) ->str: A__ , A__ : Dict = get_dpt_config(UpperCAmelCase__ ) # load original state_dict from URL A__ : Any = torch.hub.load_state_dict_from_url(UpperCAmelCase__, map_location="""cpu""" ) # remove certain keys remove_ignore_keys_(UpperCAmelCase__ ) # rename keys for key in state_dict.copy().keys(): A__ : int = state_dict.pop(UpperCAmelCase__ ) A__ : str = val # read in qkv matrices read_in_q_k_v(UpperCAmelCase__, UpperCAmelCase__ ) # load HuggingFace model A__ : Optional[Any] = DPTForSemanticSegmentation(UpperCAmelCase__ ) if """ade""" in checkpoint_url else DPTForDepthEstimation(UpperCAmelCase__ ) model.load_state_dict(UpperCAmelCase__ ) model.eval() # Check outputs on an image A__ : Optional[Any] = 4_8_0 if """ade""" in checkpoint_url else 3_8_4 A__ : Dict = DPTImageProcessor(size=UpperCAmelCase__ ) A__ : Optional[int] = prepare_img() A__ : Any = image_processor(UpperCAmelCase__, return_tensors="""pt""" ) # forward pass A__ : List[str] = model(**UpperCAmelCase__ ).logits if """ade""" in checkpoint_url else model(**UpperCAmelCase__ ).predicted_depth # Assert logits A__ : Optional[Any] = torch.tensor([[6.3199, 6.3629, 6.4148], [6.3850, 6.3615, 6.4166], [6.3519, 6.3176, 6.3575]] ) if "ade" in checkpoint_url: A__ : Optional[int] = torch.tensor([[4.0480, 4.2420, 4.4360], [4.3124, 4.5693, 4.8261], [4.5768, 4.8965, 5.2163]] ) assert outputs.shape == torch.Size(UpperCAmelCase__ ) assert ( torch.allclose(outputs[0, 0, :3, :3], UpperCAmelCase__, atol=1e-4 ) if "ade" in checkpoint_url else torch.allclose(outputs[0, :3, :3], UpperCAmelCase__ ) ) Path(UpperCAmelCase__ ).mkdir(exist_ok=UpperCAmelCase__ ) print(f'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(UpperCAmelCase__ ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(UpperCAmelCase__ ) if push_to_hub: print("""Pushing model to hub...""" ) model.push_to_hub( repo_path_or_name=Path(UpperCAmelCase__, UpperCAmelCase__ ), organization="""nielsr""", commit_message="""Add model""", use_temp_dir=UpperCAmelCase__, ) image_processor.push_to_hub( repo_path_or_name=Path(UpperCAmelCase__, UpperCAmelCase__ ), organization="""nielsr""", commit_message="""Add image processor""", use_temp_dir=UpperCAmelCase__, ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt''', type=str, help='''URL of the original DPT checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', action='''store_true''', ) parser.add_argument( '''--model_name''', default='''dpt-large''', type=str, help='''Name of the model, in case you\'re pushing to the hub.''', ) A_ = parser.parse_args() convert_dpt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
296
0
"""simple docstring""" from functools import lru_cache @lru_cache def _lowerCAmelCase ( UpperCAmelCase__ : Optional[Any] ) ->int: if num < 0: raise ValueError("""Number should not be negative.""" ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
362
"""simple docstring""" import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py A_ = '''src/diffusers''' A_ = '''.''' # This is to make sure the diffusers module imported is the one in the repo. A_ = importlib.util.spec_from_file_location( '''diffusers''', os.path.join(DIFFUSERS_PATH, '''__init__.py'''), submodule_search_locations=[DIFFUSERS_PATH], ) A_ = spec.loader.load_module() def _lowerCAmelCase ( UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : Optional[Any] ) ->Any: return line.startswith(UpperCAmelCase__ ) or len(UpperCAmelCase__ ) <= 1 or re.search(R"""^\s*\)(\s*->.*:|:)\s*$""", UpperCAmelCase__ ) is not None def _lowerCAmelCase ( UpperCAmelCase__ : List[str] ) ->Union[str, Any]: A__ : Any = object_name.split(""".""" ) A__ : int = 0 # First let's find the module where our object lives. A__ : str = parts[i] while i < len(UpperCAmelCase__ ) and not os.path.isfile(os.path.join(UpperCAmelCase__, f'{module}.py' ) ): i += 1 if i < len(UpperCAmelCase__ ): A__ : Union[str, Any] = os.path.join(UpperCAmelCase__, parts[i] ) if i >= len(UpperCAmelCase__ ): raise ValueError(f'`object_name` should begin with the name of a module of diffusers but got {object_name}.' ) with open(os.path.join(UpperCAmelCase__, f'{module}.py' ), """r""", encoding="""utf-8""", newline="""\n""" ) as f: A__ : List[Any] = f.readlines() # Now let's find the class / func in the code! A__ : Optional[Any] = """""" A__ : Any = 0 for name in parts[i + 1 :]: while ( line_index < len(UpperCAmelCase__ ) and re.search(Rf'^{indent}(class|def)\s+{name}(\(|\:)', lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(UpperCAmelCase__ ): raise ValueError(f' {object_name} does not match any function or class in {module}.' ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). A__ : List[Any] = line_index while line_index < len(UpperCAmelCase__ ) and _should_continue(lines[line_index], UpperCAmelCase__ ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 A__ : List[Any] = lines[start_index:line_index] return "".join(UpperCAmelCase__ ) A_ = re.compile(r'''^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)''') A_ = re.compile(r'''^\s*(\S+)->(\S+)(\s+.*|$)''') A_ = re.compile(r'''<FILL\s+[^>]*>''') def _lowerCAmelCase ( UpperCAmelCase__ : List[str] ) ->Optional[Any]: A__ : Dict = code.split("""\n""" ) A__ : List[Any] = 0 while idx < len(UpperCAmelCase__ ) and len(lines[idx] ) == 0: idx += 1 if idx < len(UpperCAmelCase__ ): return re.search(R"""^(\s*)\S""", lines[idx] ).groups()[0] return "" def _lowerCAmelCase ( UpperCAmelCase__ : Optional[Any] ) ->int: A__ : str = len(get_indent(UpperCAmelCase__ ) ) > 0 if has_indent: A__ : Union[str, Any] = f'class Bla:\n{code}' A__ : Optional[Any] = black.Mode(target_versions={black.TargetVersion.PYaa}, line_length=1_1_9, preview=UpperCAmelCase__ ) A__ : Tuple = black.format_str(UpperCAmelCase__, mode=UpperCAmelCase__ ) A__ , A__ : List[Any] = style_docstrings_in_code(UpperCAmelCase__ ) return result[len("""class Bla:\n""" ) :] if has_indent else result def _lowerCAmelCase ( UpperCAmelCase__ : Any, UpperCAmelCase__ : Dict=False ) ->List[Any]: with open(UpperCAmelCase__, """r""", encoding="""utf-8""", newline="""\n""" ) as f: A__ : int = f.readlines() A__ : Dict = [] A__ : List[str] = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(UpperCAmelCase__ ): A__ : Dict = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. A__ , A__ , A__ : Dict = search.groups() A__ : Tuple = find_code_in_diffusers(UpperCAmelCase__ ) A__ : int = get_indent(UpperCAmelCase__ ) A__ : List[str] = line_index + 1 if indent == theoretical_indent else line_index + 2 A__ : Tuple = theoretical_indent A__ : Optional[Any] = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. A__ : Tuple = True while line_index < len(UpperCAmelCase__ ) and should_continue: line_index += 1 if line_index >= len(UpperCAmelCase__ ): break A__ : Optional[int] = lines[line_index] A__ : Tuple = _should_continue(UpperCAmelCase__, UpperCAmelCase__ ) and re.search(f'^{indent}# End copy', UpperCAmelCase__ ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 A__ : Dict = lines[start_index:line_index] A__ : Tuple = """""".join(UpperCAmelCase__ ) # Remove any nested `Copied from` comments to avoid circular copies A__ : Optional[int] = [line for line in theoretical_code.split("""\n""" ) if _re_copy_warning.search(UpperCAmelCase__ ) is None] A__ : Optional[Any] = """\n""".join(UpperCAmelCase__ ) # Before comparing, use the `replace_pattern` on the original code. if len(UpperCAmelCase__ ) > 0: A__ : int = replace_pattern.replace("""with""", """""" ).split(""",""" ) A__ : List[Any] = [_re_replace_pattern.search(UpperCAmelCase__ ) for p in patterns] for pattern in patterns: if pattern is None: continue A__ , A__ , A__ : Union[str, Any] = pattern.groups() A__ : Union[str, Any] = re.sub(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) if option.strip() == "all-casing": A__ : List[Any] = re.sub(obja.lower(), obja.lower(), UpperCAmelCase__ ) A__ : Tuple = re.sub(obja.upper(), obja.upper(), UpperCAmelCase__ ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line A__ : Optional[int] = blackify(lines[start_index - 1] + theoretical_code ) A__ : List[Any] = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: A__ : List[Any] = lines[:start_index] + [theoretical_code] + lines[line_index:] A__ : Tuple = start_index + 1 if overwrite and len(UpperCAmelCase__ ) > 0: # Warn the user a file has been modified. print(f'Detected changes, rewriting {filename}.' ) with open(UpperCAmelCase__, """w""", encoding="""utf-8""", newline="""\n""" ) as f: f.writelines(UpperCAmelCase__ ) return diffs def _lowerCAmelCase ( UpperCAmelCase__ : bool = False ) ->Any: A__ : Dict = glob.glob(os.path.join(UpperCAmelCase__, """**/*.py""" ), recursive=UpperCAmelCase__ ) A__ : str = [] for filename in all_files: A__ : Any = is_copy_consistent(UpperCAmelCase__, UpperCAmelCase__ ) diffs += [f'- {filename}: copy does not match {d[0]} at line {d[1]}' for d in new_diffs] if not overwrite and len(UpperCAmelCase__ ) > 0: A__ : Any = """\n""".join(UpperCAmelCase__ ) raise Exception( """Found the following copy inconsistencies:\n""" + diff + """\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.""" ) if __name__ == "__main__": A_ = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') A_ = parser.parse_args() check_copies(args.fix_and_overwrite)
296
0
"""simple docstring""" import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values A_ = argparse.ArgumentParser() parser.add_argument('''--user''', type=str, default='''ubuntu''') parser.add_argument('''--host''', type=str, default='''localhost''') parser.add_argument('''--key_path''', type=str, default=None) parser.add_argument('''--instance''', type=str, default='''V100:1''') parser.add_argument('''--provider''', type=str, default='''cheapest''') parser.add_argument('''--use_spot''', type=bool, default=False) parser.add_argument('''--example''', type=str, default='''pytorch/text-generation/run_generation.py''') A_ = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError('''Cannot specify both BYO and on-demand cluster args''') A_ = rh.cluster( name='''rh-cluster''', ips=[args.host], ssh_creds={'''ssh_user''': args.user, '''ssh_private_key''': args.key_path} ) else: A_ = rh.cluster( name='''rh-cluster''', instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) A_ = args.example.rsplit('''/''', 1)[0] # Set up remote environment cluster.install_packages(['''pip:./''']) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([F'pip install -r transformers/examples/{example_dir}/requirements.txt']) cluster.run(['''pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117''']) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([F'python transformers/examples/{args.example} {" ".join(shlex.quote(arg) for arg in unknown)}']) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
363
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) A_ = { '''configuration_llama''': ['''LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LlamaConfig'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ['''LlamaTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ['''LlamaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''LlamaForCausalLM''', '''LlamaModel''', '''LlamaPreTrainedModel''', '''LlamaForSequenceClassification''', ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
296
0
"""simple docstring""" def _lowerCAmelCase ( UpperCAmelCase__ : list[int] ) ->int: if not numbers: return 0 if not isinstance(UpperCAmelCase__, (list, tuple) ) or not all( isinstance(UpperCAmelCase__, UpperCAmelCase__ ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) A__ : List[Any] = numbers[0] for i in range(1, len(UpperCAmelCase__ ) ): # update the maximum and minimum subarray products A__ : Union[str, Any] = numbers[i] if number < 0: A__ , A__ : int = min_till_now, max_till_now A__ : int = max(UpperCAmelCase__, max_till_now * number ) A__ : str = min(UpperCAmelCase__, min_till_now * number ) # update the maximum product found till now A__ : Any = max(UpperCAmelCase__, UpperCAmelCase__ ) return max_prod
364
"""simple docstring""" import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels A_ = object() # For specifying empty leaf dict `{}` A_ = object() def _lowerCAmelCase ( UpperCAmelCase__ : Tuple, UpperCAmelCase__ : List[Any] ) ->Dict: A__ : Union[str, Any] = tuple((re.compile(x + """$""" ) for x in qs) ) for i in range(len(UpperCAmelCase__ ) - len(UpperCAmelCase__ ) + 1 ): A__ : Optional[Any] = [x.match(UpperCAmelCase__ ) for x, y in zip(UpperCAmelCase__, ks[i:] )] if matches and all(UpperCAmelCase__ ): return True return False def _lowerCAmelCase ( UpperCAmelCase__ : List[Any] ) ->Dict: def replace(UpperCAmelCase__ : int, UpperCAmelCase__ : List[str] ): for rule, replacement in rules: if _match(UpperCAmelCase__, UpperCAmelCase__ ): return replacement return val return replace def _lowerCAmelCase ( ) ->Tuple: return [ # embeddings (("transformer", "wpe", "embedding"), P("""mp""", UpperCAmelCase__ )), (("transformer", "wte", "embedding"), P("""mp""", UpperCAmelCase__ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(UpperCAmelCase__, """mp""" )), (("attention", "out_proj", "kernel"), P("""mp""", UpperCAmelCase__ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(UpperCAmelCase__, """mp""" )), (("mlp", "c_fc", "bias"), P("""mp""" )), (("mlp", "c_proj", "kernel"), P("""mp""", UpperCAmelCase__ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def _lowerCAmelCase ( UpperCAmelCase__ : Tuple ) ->Any: A__ : Union[str, Any] = _get_partition_rules() A__ : int = _replacement_rules(UpperCAmelCase__ ) A__ : Tuple = {k: _unmatched for k in flatten_dict(UpperCAmelCase__ )} A__ : Optional[int] = {k: replace(UpperCAmelCase__, UpperCAmelCase__ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(UpperCAmelCase__ ) )
296
0
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class __SCREAMING_SNAKE_CASE : def __init__( self : int , snake_case : str , snake_case : Union[str, Any]=13 , snake_case : List[Any]=7 , snake_case : List[str]=True , snake_case : int=True , snake_case : Optional[int]=True , snake_case : List[Any]=True , snake_case : Optional[int]=99 , snake_case : Any=24 , snake_case : Optional[Any]=2 , snake_case : Optional[Any]=6 , snake_case : Optional[int]=37 , snake_case : int="gelu" , snake_case : int=0.1 , snake_case : List[str]=0.1 , snake_case : Any=512 , snake_case : Optional[int]=16 , snake_case : int=2 , snake_case : List[Any]=0.02 , snake_case : Optional[Any]=3 , snake_case : Union[str, Any]=None , snake_case : Optional[Any]=1000 , ): '''simple docstring''' A__ : Tuple = parent A__ : str = batch_size A__ : List[Any] = seq_length A__ : Optional[Any] = is_training A__ : List[str] = use_input_mask A__ : List[Any] = use_token_type_ids A__ : List[Any] = use_labels A__ : int = vocab_size A__ : Union[str, Any] = hidden_size A__ : int = num_hidden_layers A__ : Optional[int] = num_attention_heads A__ : Tuple = intermediate_size A__ : Tuple = hidden_act A__ : str = hidden_dropout_prob A__ : Optional[int] = attention_probs_dropout_prob A__ : Dict = max_position_embeddings A__ : int = type_vocab_size A__ : int = type_sequence_label_size A__ : Union[str, Any] = initializer_range A__ : Dict = num_labels A__ : int = scope A__ : int = range_bbox def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Dict = ids_tensor([self.batch_size, self.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]: A__ : Optional[int] = bbox[i, j, 3] A__ : str = bbox[i, j, 1] A__ : Dict = t if bbox[i, j, 2] < bbox[i, j, 0]: A__ : Dict = bbox[i, j, 2] A__ : int = bbox[i, j, 0] A__ : int = t A__ : List[str] = None if self.use_input_mask: A__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) A__ : List[Any] = None if self.use_token_type_ids: A__ : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A__ : Dict = None A__ : Union[str, Any] = None if self.use_labels: A__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : Dict = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' return LiltConfig( 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 , ) def _UpperCamelCase ( self : Optional[Any] , snake_case : str , snake_case : str , snake_case : List[str] , snake_case : Any , snake_case : List[str] , snake_case : Union[str, Any] , snake_case : int , ): '''simple docstring''' A__ : Optional[int] = LiltModel(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() A__ : Any = model(lowerCAmelCase_ , bbox=lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ ) A__ : Optional[int] = model(lowerCAmelCase_ , bbox=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ ) A__ : Tuple = model(lowerCAmelCase_ , bbox=lowerCAmelCase_ ) 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 : Any , snake_case : Optional[Any] , snake_case : Any , snake_case : Dict , snake_case : int , snake_case : List[str] , snake_case : Optional[Any] , snake_case : int , ): '''simple docstring''' A__ : Union[str, Any] = self.num_labels A__ : Dict = LiltForTokenClassification(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() A__ : List[str] = model( lowerCAmelCase_ , bbox=lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , labels=lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self : Tuple , snake_case : Any , snake_case : List[Any] , snake_case : str , snake_case : Union[str, Any] , snake_case : int , snake_case : Optional[Any] , snake_case : str , ): '''simple docstring''' A__ : str = LiltForQuestionAnswering(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() A__ : Any = model( lowerCAmelCase_ , bbox=lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , start_positions=lowerCAmelCase_ , end_positions=lowerCAmelCase_ , ) 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 _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : int = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) : Tuple = config_and_inputs A__ : Union[str, Any] = { """input_ids""": input_ids, """bbox""": bbox, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , unittest.TestCase ): snake_case_ = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) snake_case_ = ( { '''feature-extraction''': LiltModel, '''question-answering''': LiltForQuestionAnswering, '''text-classification''': LiltForSequenceClassification, '''token-classification''': LiltForTokenClassification, '''zero-shot''': LiltForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = False snake_case_ = False def _UpperCamelCase ( self : List[Any] , snake_case : Tuple , snake_case : str , snake_case : Tuple , snake_case : Optional[int] , snake_case : List[str] ): '''simple docstring''' return True def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : List[str] = LiltModelTester(self ) A__ : int = ConfigTester(self , config_class=lowerCAmelCase_ , hidden_size=37 ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase_ ) def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A__ : List[Any] = type self.model_tester.create_and_check_model(*lowerCAmelCase_ ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowerCAmelCase_ ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowerCAmelCase_ ) @slow def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ : List[Any] = LiltModel.from_pretrained(lowerCAmelCase_ ) self.assertIsNotNone(lowerCAmelCase_ ) @require_torch @slow class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : int = LiltModel.from_pretrained("""SCUT-DLVCLab/lilt-roberta-en-base""" ).to(lowerCAmelCase_ ) A__ : List[Any] = torch.tensor([[1, 2]] , device=lowerCAmelCase_ ) A__ : Union[str, Any] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=lowerCAmelCase_ ) # forward pass with torch.no_grad(): A__ : Tuple = model(input_ids=lowerCAmelCase_ , bbox=lowerCAmelCase_ ) A__ : Optional[int] = torch.Size([1, 2, 768] ) A__ : Union[str, Any] = torch.tensor( [[-0.0653, 0.0950, -0.0061], [-0.0545, 0.0926, -0.0324]] , device=lowerCAmelCase_ , ) self.assertTrue(outputs.last_hidden_state.shape , lowerCAmelCase_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , lowerCAmelCase_ , atol=1e-3 ) )
365
"""simple docstring""" import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class __SCREAMING_SNAKE_CASE : def __init__( self : List[str] , snake_case : Tuple , snake_case : List[str]=2 , snake_case : List[str]=8 , snake_case : List[Any]=True , snake_case : Optional[Any]=True , snake_case : List[Any]=True , snake_case : Dict=True , snake_case : Tuple=99 , snake_case : Dict=16 , snake_case : Dict=5 , snake_case : int=2 , snake_case : Any=36 , snake_case : str="gelu" , snake_case : Dict=0.0 , snake_case : List[Any]=0.0 , snake_case : int=512 , snake_case : List[Any]=16 , snake_case : Tuple=2 , snake_case : Any=0.02 , snake_case : Optional[Any]=3 , snake_case : List[Any]=4 , snake_case : str=None , ): '''simple docstring''' A__ : Union[str, Any] = parent A__ : Optional[Any] = batch_size A__ : Dict = seq_length A__ : str = is_training A__ : Tuple = use_input_mask A__ : Dict = use_token_type_ids A__ : Dict = use_labels A__ : int = vocab_size A__ : List[str] = hidden_size A__ : Union[str, Any] = num_hidden_layers A__ : int = num_attention_heads A__ : List[str] = intermediate_size A__ : int = hidden_act A__ : str = hidden_dropout_prob A__ : Tuple = attention_probs_dropout_prob A__ : Any = max_position_embeddings A__ : Optional[int] = type_vocab_size A__ : int = type_sequence_label_size A__ : Optional[Any] = initializer_range A__ : int = num_labels A__ : Optional[int] = num_choices A__ : Optional[int] = scope def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Any = None if self.use_input_mask: A__ : Any = random_attention_mask([self.batch_size, self.seq_length] ) A__ : Optional[int] = None if self.use_token_type_ids: A__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A__ : Dict = None A__ : List[str] = None A__ : Union[str, Any] = None if self.use_labels: A__ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : Any = ids_tensor([self.batch_size] , self.num_choices ) A__ : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case , initializer_range=self.initializer_range , ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Any = self.get_config() A__ : List[str] = 300 return config def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) : Tuple = self.prepare_config_and_inputs() A__ : List[str] = True A__ : List[str] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) A__ : int = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def _UpperCamelCase ( self : Any , snake_case : Any , snake_case : Tuple , snake_case : Any , snake_case : Optional[int] , snake_case : Optional[int] , snake_case : Optional[int] , snake_case : Dict ): '''simple docstring''' A__ : List[str] = MraModel(config=snake_case ) model.to(snake_case ) model.eval() A__ : Dict = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case ) A__ : List[str] = model(snake_case , token_type_ids=snake_case ) A__ : Union[str, Any] = model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : Optional[Any] , snake_case : List[Any] , snake_case : Any , snake_case : Optional[Any] , snake_case : Union[str, Any] , snake_case : Tuple , snake_case : Dict , snake_case : str , snake_case : Dict , snake_case : str , ): '''simple docstring''' A__ : Dict = True A__ : Optional[Any] = MraModel(snake_case ) model.to(snake_case ) model.eval() A__ : Union[str, Any] = model( snake_case , attention_mask=snake_case , token_type_ids=snake_case , encoder_hidden_states=snake_case , encoder_attention_mask=snake_case , ) A__ : str = model( snake_case , attention_mask=snake_case , token_type_ids=snake_case , encoder_hidden_states=snake_case , ) A__ : Optional[int] = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : int , snake_case : Optional[Any] , snake_case : Optional[int] , snake_case : int , snake_case : str , snake_case : Union[str, Any] , snake_case : Dict , snake_case : List[str] ): '''simple docstring''' A__ : Union[str, Any] = MraForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() A__ : List[Any] = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Dict , snake_case : Dict , snake_case : Dict , snake_case : List[str] , snake_case : List[str] , snake_case : Tuple , snake_case : Union[str, Any] ): '''simple docstring''' A__ : Dict = MraForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() A__ : str = model( 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 _UpperCamelCase ( self : Tuple , snake_case : List[Any] , snake_case : Optional[Any] , snake_case : Optional[Any] , snake_case : List[str] , snake_case : Optional[int] , snake_case : List[str] , snake_case : Union[str, Any] ): '''simple docstring''' A__ : str = self.num_labels A__ : Optional[Any] = MraForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : str = model(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 _UpperCamelCase ( self : Union[str, Any] , snake_case : Dict , snake_case : str , snake_case : List[Any] , snake_case : Any , snake_case : Dict , snake_case : Tuple , snake_case : Optional[Any] ): '''simple docstring''' A__ : str = self.num_labels A__ : Union[str, Any] = MraForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() A__ : str = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self : Tuple , snake_case : Optional[Any] , snake_case : Optional[int] , snake_case : int , snake_case : Optional[Any] , snake_case : List[str] , snake_case : Dict , snake_case : Optional[Any] ): '''simple docstring''' A__ : List[str] = self.num_choices A__ : str = MraForMultipleChoice(config=snake_case ) model.to(snake_case ) model.eval() A__ : int = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : str = model( 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_choices) ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : List[str] = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) : Dict = config_and_inputs A__ : Optional[int] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( UpperCamelCase , unittest.TestCase ): snake_case_ = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = () def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Optional[Any] = MraModelTester(self ) A__ : List[str] = ConfigTester(self , config_class=snake_case , hidden_size=37 ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A__ : List[str] = type self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case ) @slow def _UpperCamelCase ( self : Any ): '''simple docstring''' for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ : str = MraModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @unittest.skip(reason="""MRA does not output attentions""" ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' return @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : str = MraModel.from_pretrained("""uw-madison/mra-base-512-4""" ) A__ : Any = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): A__ : List[Any] = model(snake_case )[0] A__ : List[Any] = torch.Size((1, 256, 768) ) self.assertEqual(output.shape , snake_case ) A__ : int = torch.tensor( [[[-0.0140, 0.0830, -0.0381], [0.1546, 0.1402, 0.0220], [0.1162, 0.0851, 0.0165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) ) @slow def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : Union[str, Any] = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-512-4""" ) A__ : Tuple = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): A__ : List[Any] = model(snake_case )[0] A__ : Dict = 5_0265 A__ : List[str] = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape , snake_case ) A__ : List[Any] = torch.tensor( [[[9.2595, -3.6038, 11.8819], [9.3869, -3.2693, 11.0956], [11.8524, -3.4938, 13.1210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) ) @slow def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : Any = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-4096-8-d3""" ) A__ : List[Any] = torch.arange(4096 ).unsqueeze(0 ) with torch.no_grad(): A__ : List[Any] = model(snake_case )[0] A__ : Union[str, Any] = 5_0265 A__ : Optional[Any] = torch.Size((1, 4096, vocab_size) ) self.assertEqual(output.shape , snake_case ) A__ : Optional[int] = torch.tensor( [[[5.4789, -2.3564, 7.5064], [7.9067, -1.3369, 9.9668], [9.0712, -1.8106, 7.0380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) )
296
0
from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging A_ = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE : snake_case_ = 42 snake_case_ = None @staticmethod def _UpperCamelCase ( ): '''simple docstring''' raise NotImplementedError def _UpperCamelCase ( self : List[str] , snake_case : Optional[Any] , snake_case : List[str] , snake_case : Tuple , **snake_case : str ): '''simple docstring''' raise NotImplementedError def _UpperCamelCase ( self : List[Any] , snake_case : List[Any] ): '''simple docstring''' raise NotImplementedError def _UpperCamelCase ( self : int ): '''simple docstring''' if not self.is_available(): raise RuntimeError( F'You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.' ) @classmethod def _UpperCamelCase ( cls : Optional[int] ): '''simple docstring''' return F'`pip install {cls.pip_package or cls.name}`' class __SCREAMING_SNAKE_CASE ( _lowerCAmelCase ): snake_case_ = 'optuna' @staticmethod def _UpperCamelCase ( ): '''simple docstring''' return is_optuna_available() def _UpperCamelCase ( self : Tuple , snake_case : Optional[Any] , snake_case : Any , snake_case : Any , **snake_case : Union[str, Any] ): '''simple docstring''' return run_hp_search_optuna(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _UpperCamelCase ( self : Any , snake_case : Union[str, Any] ): '''simple docstring''' return default_hp_space_optuna(SCREAMING_SNAKE_CASE_ ) class __SCREAMING_SNAKE_CASE ( _lowerCAmelCase ): snake_case_ = 'ray' snake_case_ = '\'ray[tune]\'' @staticmethod def _UpperCamelCase ( ): '''simple docstring''' return is_ray_available() def _UpperCamelCase ( self : Union[str, Any] , snake_case : int , snake_case : List[Any] , snake_case : Optional[int] , **snake_case : Optional[Any] ): '''simple docstring''' return run_hp_search_ray(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _UpperCamelCase ( self : List[Any] , snake_case : int ): '''simple docstring''' return default_hp_space_ray(SCREAMING_SNAKE_CASE_ ) class __SCREAMING_SNAKE_CASE ( _lowerCAmelCase ): snake_case_ = 'sigopt' @staticmethod def _UpperCamelCase ( ): '''simple docstring''' return is_sigopt_available() def _UpperCamelCase ( self : Union[str, Any] , snake_case : List[str] , snake_case : Union[str, Any] , snake_case : Dict , **snake_case : Optional[Any] ): '''simple docstring''' return run_hp_search_sigopt(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _UpperCamelCase ( self : str , snake_case : Dict ): '''simple docstring''' return default_hp_space_sigopt(SCREAMING_SNAKE_CASE_ ) class __SCREAMING_SNAKE_CASE ( _lowerCAmelCase ): snake_case_ = 'wandb' @staticmethod def _UpperCamelCase ( ): '''simple docstring''' return is_wandb_available() def _UpperCamelCase ( self : Tuple , snake_case : Optional[Any] , snake_case : Optional[Any] , snake_case : Tuple , **snake_case : List[str] ): '''simple docstring''' return run_hp_search_wandb(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _UpperCamelCase ( self : int , snake_case : Union[str, Any] ): '''simple docstring''' return default_hp_space_wandb(SCREAMING_SNAKE_CASE_ ) A_ = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def _lowerCAmelCase ( ) ->List[str]: A__ : Tuple = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(lowerCAmelCase__ ) > 0: A__ : List[str] = available_backends[0].name if len(lowerCAmelCase__ ) > 1: logger.info( f'{len(lowerCAmelCase__ )} hyperparameter search backends available. Using {name} as the default.' ) return name raise RuntimeError( """No hyperparameter search backend available.\n""" + """\n""".join( f' - To install {backend.name} run {backend.pip_install()}' for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
366
"""simple docstring""" from sklearn.metrics import mean_squared_error import datasets A_ = '''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' A_ = '''\ Mean Squared Error(MSE) is the average of the square of difference between the predicted and actual values. ''' A_ = ''' Args: predictions: array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. references: array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. sample_weight: array-like of shape (n_samples,), default=None Sample weights. multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average" Defines aggregating of multiple output values. Array-like value defines weights used to average errors. "raw_values" : Returns a full set of errors in case of multioutput input. "uniform_average" : Errors of all outputs are averaged with uniform weight. squared : bool, default=True If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value. Returns: mse : mean squared error. Examples: >>> mse_metric = datasets.load_metric("mse") >>> predictions = [2.5, 0.0, 2, 8] >>> references = [3, -0.5, 2, 7] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {\'mse\': 0.375} >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False) >>> print(rmse_result) {\'mse\': 0.6123724356957945} If you\'re using multi-dimensional lists, then set the config as follows : >>> mse_metric = datasets.load_metric("mse", "multilist") >>> predictions = [[0.5, 1], [-1, 1], [7, -6]] >>> references = [[0, 2], [-1, 2], [8, -5]] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {\'mse\': 0.7083333333333334} >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\') >>> print(results) # doctest: +NORMALIZE_WHITESPACE {\'mse\': array([0.41666667, 1. ])} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE ( datasets.Metric ): def _UpperCamelCase ( self : Dict ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html""" ] , ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value("""float""" ) ), "references": datasets.Sequence(datasets.Value("""float""" ) ), } else: return { "predictions": datasets.Value("""float""" ), "references": datasets.Value("""float""" ), } def _UpperCamelCase ( self : List[str] , snake_case : Dict , snake_case : List[Any] , snake_case : List[str]=None , snake_case : List[Any]="uniform_average" , snake_case : int=True ): '''simple docstring''' A__ : Optional[int] = mean_squared_error( snake_case , snake_case , sample_weight=snake_case , multioutput=snake_case , squared=snake_case ) return {"mse": mse}
296
0
"""simple docstring""" import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class __SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): snake_case_ = CTRLTokenizer snake_case_ = False snake_case_ = False def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt A__ : List[str] = ['''adapt''', '''re@@''', '''a@@''', '''apt''', '''c@@''', '''t''', '''<unk>'''] A__ : int = dict(zip(UpperCamelCase__ , range(len(UpperCamelCase__ ) ) ) ) A__ : str = ['''#version: 0.2''', '''a p''', '''ap t</w>''', '''r e''', '''a d''', '''ad apt</w>''', ''''''] A__ : Optional[Any] = {'''unk_token''': '''<unk>'''} A__ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) A__ : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(UpperCamelCase__ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(UpperCamelCase__ ) ) def _UpperCamelCase ( self : Dict , **snake_case : Optional[int] ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CTRLTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def _UpperCamelCase ( self : Optional[int] , snake_case : List[Any] ): '''simple docstring''' A__ : int = '''adapt react readapt apt''' A__ : str = '''adapt react readapt apt''' return input_text, output_text def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : List[str] = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) A__ : Tuple = '''adapt react readapt apt''' A__ : Tuple = '''adapt re@@ a@@ c@@ t re@@ adapt apt'''.split() A__ : Optional[Any] = tokenizer.tokenize(UpperCamelCase__ ) self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) A__ : Any = tokens + [tokenizer.unk_token] A__ : Tuple = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , UpperCamelCase__ )
367
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging A_ = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): def __init__( self : Optional[int] , snake_case : List[str]=None , **snake_case : Any ): '''simple docstring''' warnings.warn( """`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` """ """instead.""" , snake_case , ) super().__init__(args=snake_case , **snake_case )
296
0
from __future__ import annotations from collections.abc import Callable from typing import Any, Generic, TypeVar A_ = TypeVar('''T''') class __SCREAMING_SNAKE_CASE ( Generic[T] ): def __init__( self : List[Any] , snake_case : str , snake_case : str ): '''simple docstring''' A__ : Any | T = None A__ : int = len(snake_case ) A__ : list[T] = [any_type for _ in range(self.N )] + arr A__ : Optional[int] = fnc self.build() def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' for p in range(self.N - 1 , 0 , -1 ): A__ : Optional[int] = self.fn(self.st[p * 2] , self.st[p * 2 + 1] ) def _UpperCamelCase ( self : Union[str, Any] , snake_case : str , snake_case : Optional[Any] ): '''simple docstring''' p += self.N A__ : str = v while p > 1: A__ : List[Any] = p // 2 A__ : str = self.fn(self.st[p * 2] , self.st[p * 2 + 1] ) def _UpperCamelCase ( self : Optional[int] , snake_case : str , snake_case : Optional[Any] ): # noqa: E741 '''simple docstring''' A__ : List[Any] = l + self.N, r + self.N A__ : T | None = None while l <= r: if l % 2 == 1: A__ : Optional[Any] = self.st[l] if res is None else self.fn(snake_case , self.st[l] ) if r % 2 == 0: A__ : Tuple = self.st[r] if res is None else self.fn(snake_case , self.st[r] ) A__ : List[Any] = (l + 1) // 2, (r - 1) // 2 return res if __name__ == "__main__": from functools import reduce A_ = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12] A_ = { 0: 7, 1: 2, 2: 6, 3: -14, 4: 5, 5: 4, 6: 7, 7: -10, 8: 9, 9: 10, 10: 12, 11: 1, } A_ = SegmentTree(test_array, min) A_ = SegmentTree(test_array, max) A_ = SegmentTree(test_array, lambda a, b: a + b) def _lowerCAmelCase ( ) ->None: for i in range(len(lowerCamelCase_ ) ): for j in range(lowerCamelCase_, len(lowerCamelCase_ ) ): A__ : Dict = reduce(lowerCamelCase_, test_array[i : j + 1] ) A__ : int = reduce(lowerCamelCase_, test_array[i : j + 1] ) A__ : Optional[int] = reduce(lambda UpperCAmelCase__, UpperCAmelCase__ : a + b, test_array[i : j + 1] ) assert min_range == min_segment_tree.query(lowerCamelCase_, lowerCamelCase_ ) assert max_range == max_segment_tree.query(lowerCamelCase_, lowerCamelCase_ ) assert sum_range == sum_segment_tree.query(lowerCamelCase_, lowerCamelCase_ ) test_all_segments() for index, value in test_updates.items(): A_ = value min_segment_tree.update(index, value) max_segment_tree.update(index, value) sum_segment_tree.update(index, value) test_all_segments()
368
"""simple docstring""" import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch A_ = random.Random() def _lowerCAmelCase ( UpperCAmelCase__ : Dict, UpperCAmelCase__ : Tuple=1.0, UpperCAmelCase__ : Optional[int]=None, UpperCAmelCase__ : str=None ) ->Union[str, Any]: if rng is None: A__ : Optional[int] = global_rng A__ : Optional[Any] = [] 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 __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : Union[str, Any] , snake_case : str , snake_case : List[str]=7 , snake_case : str=400 , snake_case : Optional[Any]=2000 , snake_case : Union[str, Any]=10 , snake_case : str=160 , snake_case : List[str]=8 , snake_case : List[Any]=0.0 , snake_case : Optional[Any]=4000 , snake_case : Any=False , snake_case : int=True , ): '''simple docstring''' A__ : Any = parent A__ : str = batch_size A__ : List[str] = min_seq_length A__ : Dict = max_seq_length A__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) A__ : Dict = padding_value A__ : Optional[Any] = sampling_rate A__ : Any = return_attention_mask A__ : Optional[int] = do_normalize A__ : Tuple = feature_size A__ : Optional[Any] = chunk_length A__ : Union[str, Any] = hop_length def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _UpperCamelCase ( self : Union[str, Any] , snake_case : Dict=False , snake_case : Optional[Any]=False ): '''simple docstring''' def _flatten(snake_case : Dict ): return list(itertools.chain(*snake_case ) ) if equal_length: A__ : Dict = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size A__ : Optional[int] = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: A__ : List[str] = [np.asarray(snake_case ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __SCREAMING_SNAKE_CASE ( UpperCamelCase , unittest.TestCase ): snake_case_ = WhisperFeatureExtractor if is_speech_available() else None def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : str = WhisperFeatureExtractionTester(self ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Any = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: A__ : List[Any] = feat_extract_first.save_pretrained(snake_case )[0] check_json_file_has_correct_format(snake_case ) A__ : Union[str, Any] = self.feature_extraction_class.from_pretrained(snake_case ) A__ : str = feat_extract_first.to_dict() A__ : Union[str, Any] = feat_extract_second.to_dict() A__ : List[Any] = feat_extract_first.mel_filters A__ : Optional[Any] = feat_extract_second.mel_filters self.assertTrue(np.allclose(snake_case , snake_case ) ) self.assertEqual(snake_case , snake_case ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Any = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: A__ : Any = os.path.join(snake_case , """feat_extract.json""" ) feat_extract_first.to_json_file(snake_case ) A__ : int = self.feature_extraction_class.from_json_file(snake_case ) A__ : Dict = feat_extract_first.to_dict() A__ : str = feat_extract_second.to_dict() A__ : str = feat_extract_first.mel_filters A__ : Dict = feat_extract_second.mel_filters self.assertTrue(np.allclose(snake_case , snake_case ) ) self.assertEqual(snake_case , snake_case ) def _UpperCamelCase ( self : Any ): '''simple docstring''' A__ : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 A__ : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] A__ : Union[str, Any] = [np.asarray(snake_case ) for speech_input in speech_inputs] # Test feature size A__ : Dict = feature_extractor(snake_case , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input A__ : str = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features A__ : Optional[int] = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(snake_case , snake_case , atol=1e-3 ) ) # Test batched A__ : List[str] = feature_extractor(snake_case , return_tensors="""np""" ).input_features A__ : List[str] = feature_extractor(snake_case , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(snake_case , snake_case ): self.assertTrue(np.allclose(snake_case , snake_case , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. A__ : Tuple = [floats_list((1, x) )[0] for x in (800, 800, 800)] A__ : str = np.asarray(snake_case ) A__ : List[str] = feature_extractor(snake_case , return_tensors="""np""" ).input_features A__ : Optional[int] = feature_extractor(snake_case , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(snake_case , snake_case ): self.assertTrue(np.allclose(snake_case , snake_case , atol=1e-3 ) ) # Test truncation required A__ : Optional[Any] = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] A__ : Union[str, Any] = [np.asarray(snake_case ) for speech_input in speech_inputs] A__ : Union[str, Any] = [x[: feature_extractor.n_samples] for x in speech_inputs] A__ : str = [np.asarray(snake_case ) for speech_input in speech_inputs_truncated] A__ : Optional[int] = feature_extractor(snake_case , return_tensors="""np""" ).input_features A__ : str = feature_extractor(snake_case , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(snake_case , snake_case ): self.assertTrue(np.allclose(snake_case , snake_case , atol=1e-3 ) ) def _UpperCamelCase ( self : str ): '''simple docstring''' import torch A__ : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A__ : List[str] = np.random.rand(100 , 32 ).astype(np.floataa ) A__ : Tuple = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: A__ : Optional[Any] = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) A__ : Optional[int] = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Optional[int] ): '''simple docstring''' A__ : int = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech A__ : Union[str, Any] = ds.sort("""id""" ).select(range(snake_case ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : str = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on A__ : Optional[Any] = self._load_datasamples(1 ) A__ : Union[str, Any] = WhisperFeatureExtractor() A__ : List[str] = feature_extractor(snake_case , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 80, 3000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , snake_case , atol=1e-4 ) ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A__ : Union[str, Any] = self._load_datasamples(1 )[0] A__ : Any = ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535 # Rescale to [0, 65535] to show issue A__ : str = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=snake_case )[0] self.assertTrue(np.all(np.mean(snake_case ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(snake_case ) - 1 ) < 1e-3 ) )
296
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, 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_ = logging.get_logger(__name__) if is_vision_available(): import PIL class __SCREAMING_SNAKE_CASE ( __a ): snake_case_ = ['pixel_values'] def __init__( self : List[str] , snake_case : bool = True , snake_case : Dict[str, int] = None , snake_case : PILImageResampling = PILImageResampling.BICUBIC , snake_case : bool = True , snake_case : Dict[str, int] = None , snake_case : bool = True , snake_case : Union[int, float] = 1 / 255 , snake_case : bool = True , snake_case : Optional[Union[float, List[float]]] = None , snake_case : Optional[Union[float, List[float]]] = None , snake_case : bool = True , **snake_case : List[Any] , ): '''simple docstring''' super().__init__(**UpperCamelCase__ ) A__ : Optional[Any] = size if size is not None else {"""shortest_edge""": 224} A__ : str = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) A__ : Optional[Any] = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} A__ : Tuple = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ , param_name="""crop_size""" ) A__ : Dict = do_resize A__ : List[str] = size A__ : Optional[Any] = resample A__ : Optional[int] = do_center_crop A__ : str = crop_size A__ : Tuple = do_rescale A__ : List[str] = rescale_factor A__ : Tuple = do_normalize A__ : str = image_mean if image_mean is not None else OPENAI_CLIP_MEAN A__ : Union[str, Any] = image_std if image_std is not None else OPENAI_CLIP_STD A__ : int = do_convert_rgb def _UpperCamelCase ( self : List[str] , snake_case : np.ndarray , snake_case : Dict[str, int] , snake_case : PILImageResampling = PILImageResampling.BICUBIC , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : Dict , ): '''simple docstring''' A__ : int = 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()}' ) A__ : Tuple = 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] , snake_case : np.ndarray , snake_case : Dict[str, int] , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : Tuple , ): '''simple docstring''' A__ : List[str] = 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] , snake_case : np.ndarray , snake_case : Union[int, float] , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : Any , ): '''simple docstring''' return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _UpperCamelCase ( self : Any , snake_case : np.ndarray , snake_case : Union[float, List[float]] , snake_case : Union[float, List[float]] , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : Optional[int] , ): '''simple docstring''' return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def _UpperCamelCase ( self : List[str] , snake_case : ImageInput , snake_case : bool = None , snake_case : Dict[str, int] = None , snake_case : PILImageResampling = None , snake_case : bool = None , snake_case : int = None , snake_case : bool = None , snake_case : float = None , snake_case : bool = None , snake_case : Optional[Union[float, List[float]]] = None , snake_case : Optional[Union[float, List[float]]] = None , snake_case : bool = None , snake_case : Optional[Union[str, TensorType]] = None , snake_case : Optional[ChannelDimension] = ChannelDimension.FIRST , **snake_case : Tuple , ): '''simple docstring''' A__ : List[Any] = do_resize if do_resize is not None else self.do_resize A__ : Optional[int] = size if size is not None else self.size A__ : List[Any] = get_size_dict(UpperCamelCase__ , param_name="""size""" , default_to_square=UpperCamelCase__ ) A__ : Union[str, Any] = resample if resample is not None else self.resample A__ : Optional[int] = do_center_crop if do_center_crop is not None else self.do_center_crop A__ : List[Any] = crop_size if crop_size is not None else self.crop_size A__ : List[str] = get_size_dict(UpperCamelCase__ , param_name="""crop_size""" , default_to_square=UpperCamelCase__ ) A__ : Any = do_rescale if do_rescale is not None else self.do_rescale A__ : Any = rescale_factor if rescale_factor is not None else self.rescale_factor A__ : Any = do_normalize if do_normalize is not None else self.do_normalize A__ : Union[str, Any] = image_mean if image_mean is not None else self.image_mean A__ : Optional[Any] = image_std if image_std is not None else self.image_std A__ : Tuple = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb A__ : str = 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: A__ : str = [convert_to_rgb(UpperCamelCase__ ) for image in images] # All transformations expect numpy arrays. A__ : Optional[Any] = [to_numpy_array(UpperCamelCase__ ) for image in images] if do_resize: A__ : Union[str, Any] = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images] if do_center_crop: A__ : Optional[Any] = [self.center_crop(image=UpperCamelCase__ , size=UpperCamelCase__ ) for image in images] if do_rescale: A__ : List[str] = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images] if do_normalize: A__ : str = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images] A__ : List[Any] = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images] A__ : int = {"""pixel_values""": images} return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ )
369
"""simple docstring""" import numpy as np class __SCREAMING_SNAKE_CASE : def __init__( self : List[str] ): '''simple docstring''' A__ : Optional[int] = (0, 0) A__ : Dict = None A__ : int = 0 A__ : str = 0 A__ : Optional[Any] = 0 def __eq__( self : str , snake_case : Optional[int] ): '''simple docstring''' return self.position == cell.position def _UpperCamelCase ( self : List[str] ): '''simple docstring''' print(self.position ) class __SCREAMING_SNAKE_CASE : def __init__( self : int , snake_case : Any=(5, 5) ): '''simple docstring''' A__ : Optional[int] = np.zeros(snake_case ) A__ : List[Any] = world_size[0] A__ : Dict = world_size[1] def _UpperCamelCase ( self : Any ): '''simple docstring''' print(self.w ) def _UpperCamelCase ( self : Optional[int] , snake_case : List[Any] ): '''simple docstring''' A__ : int = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] A__ : int = cell.position[0] A__ : str = cell.position[1] A__ : Any = [] for n in neughbour_cord: A__ : List[Any] = current_x + n[0] A__ : Tuple = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: A__ : List[Any] = Cell() A__ : str = (x, y) A__ : Optional[Any] = cell neighbours.append(snake_case ) return neighbours def _lowerCAmelCase ( UpperCAmelCase__ : List[str], UpperCAmelCase__ : Optional[Any], UpperCAmelCase__ : Dict ) ->Dict: A__ : Union[str, Any] = [] A__ : Optional[int] = [] _open.append(UpperCAmelCase__ ) while _open: A__ : List[Any] = np.argmin([n.f for n in _open] ) A__ : Union[str, Any] = _open[min_f] _closed.append(_open.pop(UpperCAmelCase__ ) ) if current == goal: break for n in world.get_neigbours(UpperCAmelCase__ ): for c in _closed: if c == n: continue A__ : Dict = current.g + 1 A__ , A__ : int = n.position A__ , A__ : Optional[int] = goal.position A__ : Union[str, Any] = (ya - ya) ** 2 + (xa - xa) ** 2 A__ : Optional[int] = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(UpperCAmelCase__ ) A__ : List[str] = [] while current.parent is not None: path.append(current.position ) A__ : Union[str, Any] = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": A_ = Gridworld() # Start position and goal A_ = Cell() A_ = (0, 0) A_ = Cell() A_ = (4, 4) print(F'path from {start.position} to {goal.position}') A_ = astar(world, start, goal) # Just for visual reasons. for i in s: A_ = 1 print(world.w)
296
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, 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_ = logging.get_logger(__name__) if is_vision_available(): import PIL class __SCREAMING_SNAKE_CASE ( _lowerCAmelCase ): snake_case_ = ["pixel_values"] def __init__( self : Tuple , snake_case : bool = True , snake_case : Dict[str, int] = None , snake_case : PILImageResampling = PILImageResampling.BICUBIC , snake_case : bool = True , snake_case : Dict[str, int] = None , snake_case : bool = True , snake_case : Union[int, float] = 1 / 255 , snake_case : bool = True , snake_case : Optional[Union[float, List[float]]] = None , snake_case : Optional[Union[float, List[float]]] = None , snake_case : bool = True , **snake_case : int , ): '''simple docstring''' super().__init__(**_lowercase ) A__ : List[str] = size if size is not None else {"""shortest_edge""": 224} A__ : int = get_size_dict(_lowercase , default_to_square=_lowercase ) A__ : int = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} A__ : Dict = get_size_dict(_lowercase , default_to_square=_lowercase , param_name="""crop_size""" ) A__ : Any = do_resize A__ : str = size A__ : List[str] = resample A__ : int = do_center_crop A__ : int = crop_size A__ : Any = do_rescale A__ : Union[str, Any] = rescale_factor A__ : Any = do_normalize A__ : Any = image_mean if image_mean is not None else OPENAI_CLIP_MEAN A__ : Dict = image_std if image_std is not None else OPENAI_CLIP_STD A__ : Tuple = do_convert_rgb def _UpperCamelCase ( self : Union[str, Any] , snake_case : np.ndarray , snake_case : Dict[str, int] , snake_case : PILImageResampling = PILImageResampling.BICUBIC , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : Union[str, Any] , ): '''simple docstring''' A__ : Dict = get_size_dict(_lowercase , default_to_square=_lowercase ) if "shortest_edge" not in size: raise ValueError(F'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) A__ : str = get_resize_output_image_size(_lowercase , size=size["""shortest_edge"""] , default_to_square=_lowercase ) return resize(_lowercase , size=_lowercase , resample=_lowercase , data_format=_lowercase , **_lowercase ) def _UpperCamelCase ( self : Any , snake_case : np.ndarray , snake_case : Dict[str, int] , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : str , ): '''simple docstring''' A__ : Any = get_size_dict(_lowercase ) 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(_lowercase , size=(size["""height"""], size["""width"""]) , data_format=_lowercase , **_lowercase ) def _UpperCamelCase ( self : Optional[Any] , snake_case : np.ndarray , snake_case : Union[int, float] , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : Dict , ): '''simple docstring''' return rescale(_lowercase , scale=_lowercase , data_format=_lowercase , **_lowercase ) def _UpperCamelCase ( self : Any , snake_case : np.ndarray , snake_case : Union[float, List[float]] , snake_case : Union[float, List[float]] , snake_case : Optional[Union[str, ChannelDimension]] = None , **snake_case : Union[str, Any] , ): '''simple docstring''' return normalize(_lowercase , mean=_lowercase , std=_lowercase , data_format=_lowercase , **_lowercase ) def _UpperCamelCase ( self : Dict , snake_case : ImageInput , snake_case : bool = None , snake_case : Dict[str, int] = None , snake_case : PILImageResampling = None , snake_case : bool = None , snake_case : int = None , snake_case : bool = None , snake_case : float = None , snake_case : bool = None , snake_case : Optional[Union[float, List[float]]] = None , snake_case : Optional[Union[float, List[float]]] = None , snake_case : bool = None , snake_case : Optional[Union[str, TensorType]] = None , snake_case : Optional[ChannelDimension] = ChannelDimension.FIRST , **snake_case : Any , ): '''simple docstring''' A__ : Optional[int] = do_resize if do_resize is not None else self.do_resize A__ : str = size if size is not None else self.size A__ : str = get_size_dict(_lowercase , param_name="""size""" , default_to_square=_lowercase ) A__ : List[Any] = resample if resample is not None else self.resample A__ : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop A__ : Optional[int] = crop_size if crop_size is not None else self.crop_size A__ : List[str] = get_size_dict(_lowercase , param_name="""crop_size""" , default_to_square=_lowercase ) A__ : Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale A__ : Optional[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor A__ : List[str] = do_normalize if do_normalize is not None else self.do_normalize A__ : Optional[Any] = image_mean if image_mean is not None else self.image_mean A__ : Optional[Any] = image_std if image_std is not None else self.image_std A__ : Union[str, Any] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb A__ : Tuple = make_list_of_images(_lowercase ) 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.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # PIL RGBA images are converted to RGB if do_convert_rgb: A__ : Optional[int] = [convert_to_rgb(_lowercase ) for image in images] # All transformations expect numpy arrays. A__ : List[str] = [to_numpy_array(_lowercase ) for image in images] if do_resize: A__ : Tuple = [self.resize(image=_lowercase , size=_lowercase , resample=_lowercase ) for image in images] if do_center_crop: A__ : Union[str, Any] = [self.center_crop(image=_lowercase , size=_lowercase ) for image in images] if do_rescale: A__ : int = [self.rescale(image=_lowercase , scale=_lowercase ) for image in images] if do_normalize: A__ : List[Any] = [self.normalize(image=_lowercase , mean=_lowercase , std=_lowercase ) for image in images] A__ : Tuple = [to_channel_dimension_format(_lowercase , _lowercase ) for image in images] A__ : Optional[int] = {"""pixel_values""": images} return BatchFeature(data=_lowercase , tensor_type=_lowercase )
370
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) def _lowerCAmelCase ( UpperCAmelCase__ : Union[str, Any], UpperCAmelCase__ : Tuple=False ) ->str: A__ : Optional[int] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'blocks.{i}.norm1.weight', f'deit.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((f'blocks.{i}.norm1.bias', f'deit.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append((f'blocks.{i}.attn.proj.weight', f'deit.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append((f'blocks.{i}.attn.proj.bias', f'deit.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((f'blocks.{i}.norm2.weight', f'deit.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((f'blocks.{i}.norm2.bias', f'deit.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append((f'blocks.{i}.mlp.fc1.weight', f'deit.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((f'blocks.{i}.mlp.fc1.bias', f'deit.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((f'blocks.{i}.mlp.fc2.weight', f'deit.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((f'blocks.{i}.mlp.fc2.bias', f'deit.encoder.layer.{i}.output.dense.bias') ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """deit.embeddings.cls_token"""), ("""dist_token""", """deit.embeddings.distillation_token"""), ("""patch_embed.proj.weight""", """deit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """deit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """deit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" A__ : Optional[int] = [(pair[0], pair[1][4:]) if pair[1].startswith("""deit""" ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ("""norm.weight""", """deit.layernorm.weight"""), ("""norm.bias""", """deit.layernorm.bias"""), ("""head.weight""", """cls_classifier.weight"""), ("""head.bias""", """cls_classifier.bias"""), ("""head_dist.weight""", """distillation_classifier.weight"""), ("""head_dist.bias""", """distillation_classifier.bias"""), ] ) return rename_keys def _lowerCAmelCase ( UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : Tuple, UpperCAmelCase__ : List[Any]=False ) ->str: for i in range(config.num_hidden_layers ): if base_model: A__ : Any = """""" else: A__ : Tuple = """deit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) A__ : Any = state_dict.pop(f'blocks.{i}.attn.qkv.weight' ) A__ : Tuple = state_dict.pop(f'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict A__ : List[Any] = in_proj_weight[ : config.hidden_size, : ] A__ : str = in_proj_bias[: config.hidden_size] A__ : Any = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] A__ : Dict = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] A__ : Optional[Any] = in_proj_weight[ -config.hidden_size :, : ] A__ : Any = in_proj_bias[-config.hidden_size :] def _lowerCAmelCase ( UpperCAmelCase__ : List[Any], UpperCAmelCase__ : List[Any], UpperCAmelCase__ : Union[str, Any] ) ->Any: A__ : int = dct.pop(UpperCAmelCase__ ) A__ : Tuple = val def _lowerCAmelCase ( ) ->List[Any]: A__ : Optional[int] = """http://images.cocodataset.org/val2017/000000039769.jpg""" A__ : int = Image.open(requests.get(UpperCAmelCase__, stream=UpperCAmelCase__ ).raw ) return im @torch.no_grad() def _lowerCAmelCase ( UpperCAmelCase__ : Dict, UpperCAmelCase__ : Any ) ->Tuple: A__ : List[Any] = DeiTConfig() # all deit models have fine-tuned heads A__ : Tuple = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size A__ : str = 1_0_0_0 A__ : List[str] = """huggingface/label-files""" A__ : Dict = """imagenet-1k-id2label.json""" A__ : List[str] = json.load(open(hf_hub_download(UpperCAmelCase__, UpperCAmelCase__, repo_type="""dataset""" ), """r""" ) ) A__ : Dict = {int(UpperCAmelCase__ ): v for k, v in idalabel.items()} A__ : Optional[int] = idalabel A__ : Dict = {v: k for k, v in idalabel.items()} A__ : List[str] = int(deit_name[-6:-4] ) A__ : str = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith("""tiny""" ): A__ : List[str] = 1_9_2 A__ : int = 7_6_8 A__ : List[Any] = 1_2 A__ : Dict = 3 elif deit_name[9:].startswith("""small""" ): A__ : List[Any] = 3_8_4 A__ : List[str] = 1_5_3_6 A__ : Any = 1_2 A__ : Union[str, Any] = 6 if deit_name[9:].startswith("""base""" ): pass elif deit_name[4:].startswith("""large""" ): A__ : int = 1_0_2_4 A__ : str = 4_0_9_6 A__ : Any = 2_4 A__ : int = 1_6 # load original model from timm A__ : Dict = timm.create_model(UpperCAmelCase__, pretrained=UpperCAmelCase__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys A__ : Tuple = timm_model.state_dict() A__ : str = create_rename_keys(UpperCAmelCase__, UpperCAmelCase__ ) for src, dest in rename_keys: rename_key(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) read_in_q_k_v(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) # load HuggingFace model A__ : str = DeiTForImageClassificationWithTeacher(UpperCAmelCase__ ).eval() model.load_state_dict(UpperCAmelCase__ ) # Check outputs on an image, prepared by DeiTImageProcessor A__ : int = int( (2_5_6 / 2_2_4) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 A__ : Any = DeiTImageProcessor(size=UpperCAmelCase__, crop_size=config.image_size ) A__ : Union[str, Any] = image_processor(images=prepare_img(), return_tensors="""pt""" ) A__ : Optional[Any] = encoding["""pixel_values"""] A__ : Union[str, Any] = model(UpperCAmelCase__ ) A__ : Union[str, Any] = timm_model(UpperCAmelCase__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(UpperCAmelCase__, outputs.logits, atol=1e-3 ) Path(UpperCAmelCase__ ).mkdir(exist_ok=UpperCAmelCase__ ) print(f'Saving model {deit_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(UpperCAmelCase__ ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(UpperCAmelCase__ ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--deit_name''', default='''vit_deit_base_distilled_patch16_224''', type=str, help='''Name of the DeiT 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.''' ) A_ = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
296
0
"""simple docstring""" 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 ( UpperCAmelCase__ : int ) ->Any: if hor == 1_2_8: A__ : Tuple = ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""") A__ : Tuple = (3_2, 1_2_8, 2_5_6) A__ : Any = ("""UpResnetBlock1D""", """UpResnetBlock1D""") elif hor == 3_2: A__ : Union[str, Any] = ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""") A__ : Dict = (3_2, 6_4, 1_2_8, 2_5_6) A__ : Optional[int] = ("""UpResnetBlock1D""", """UpResnetBlock1D""", """UpResnetBlock1D""") A__ : Tuple = torch.load(f'/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch' ) A__ : Dict = model.state_dict() A__ : Union[str, Any] = { """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""": 1_4, """out_channels""": 1_4, """extra_in_channels""": 0, """time_embedding_type""": """positional""", """flip_sin_to_cos""": False, """freq_shift""": 1, """sample_size""": 6_5_5_3_6, """mid_block_type""": """MidResTemporalBlock1D""", """act_fn""": """mish""", } A__ : Any = UNetaDModel(**a__ ) 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__ : Optional[Any] = state_dict.pop(a__ ) hf_value_function.load_state_dict(a__ ) 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(a__, a__ ) def _lowerCAmelCase ( ) ->Tuple: A__ : List[str] = { """in_channels""": 1_4, """down_block_types""": ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D"""), """up_block_types""": (), """out_block_type""": """ValueFunction""", """mid_block_type""": """ValueFunctionMidBlock1D""", """block_out_channels""": (3_2, 6_4, 1_2_8, 2_5_6), """layers_per_block""": 1, """downsample_each_block""": True, """sample_size""": 6_5_5_3_6, """out_channels""": 1_4, """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__ : List[Any] = torch.load("""/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch""" ) A__ : Optional[int] = model A__ : Optional[int] = UNetaDModel(**a__ ) 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__ : Union[str, Any] = dict(zip(state_dict.keys(), hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): A__ : Dict = state_dict.pop(a__ ) hf_value_function.load_state_dict(a__ ) 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(a__, a__ ) if __name__ == "__main__": unet(32) # unet(128) value_function()
371
"""simple docstring""" from __future__ import annotations import time from collections.abc import Sequence from random import randint from matplotlib import pyplot as plt def _lowerCAmelCase ( UpperCAmelCase__ : Sequence[float], UpperCAmelCase__ : int, UpperCAmelCase__ : int ) ->tuple[int | None, int | None, float]: if not arr: return None, None, 0 if low == high: return low, high, arr[low] A__ : Optional[int] = (low + high) // 2 A__ , A__ , A__ : List[Any] = max_subarray(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) A__ , A__ , A__ : Union[str, Any] = max_subarray(UpperCAmelCase__, mid + 1, UpperCAmelCase__ ) A__ , A__ , A__ : Union[str, Any] = max_cross_sum(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum return cross_left, cross_right, cross_sum def _lowerCAmelCase ( UpperCAmelCase__ : Sequence[float], UpperCAmelCase__ : int, UpperCAmelCase__ : int, UpperCAmelCase__ : int ) ->tuple[int, int, float]: A__ , A__ : Dict = float("""-inf""" ), -1 A__ , A__ : Optional[Any] = float("""-inf""" ), -1 A__ : int | float = 0 for i in range(UpperCAmelCase__, low - 1, -1 ): summ += arr[i] if summ > left_sum: A__ : Optional[int] = summ A__ : Union[str, Any] = i A__ : Optional[Any] = 0 for i in range(mid + 1, high + 1 ): summ += arr[i] if summ > right_sum: A__ : int = summ A__ : Union[str, Any] = i return max_left, max_right, (left_sum + right_sum) def _lowerCAmelCase ( UpperCAmelCase__ : int ) ->float: A__ : Union[str, Any] = [randint(1, UpperCAmelCase__ ) for _ in range(UpperCAmelCase__ )] A__ : Any = time.time() max_subarray(UpperCAmelCase__, 0, input_size - 1 ) A__ : List[Any] = time.time() return end - start def _lowerCAmelCase ( ) ->None: A__ : List[Any] = [1_0, 1_0_0, 1_0_0_0, 1_0_0_0_0, 5_0_0_0_0, 1_0_0_0_0_0, 2_0_0_0_0_0, 3_0_0_0_0_0, 4_0_0_0_0_0, 5_0_0_0_0_0] A__ : Any = [time_max_subarray(UpperCAmelCase__ ) for input_size in input_sizes] print("""No of Inputs\t\tTime Taken""" ) for input_size, runtime in zip(UpperCAmelCase__, UpperCAmelCase__ ): print(UpperCAmelCase__, """\t\t""", UpperCAmelCase__ ) plt.plot(UpperCAmelCase__, UpperCAmelCase__ ) plt.xlabel("""Number of Inputs""" ) plt.ylabel("""Time taken in seconds""" ) plt.show() if __name__ == "__main__": from doctest import testmod testmod()
296
0
"""simple docstring""" import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class __SCREAMING_SNAKE_CASE ( unittest.TestCase , snake_case_ ): def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : str = load_tool("""text-classification""" ) self.tool.setup() A__ : Dict = load_tool("""text-classification""" , remote=_A ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : List[str] = self.tool("""That\'s quite cool""" , ["""positive""", """negative"""] ) self.assertEqual(_A , """positive""" ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Union[str, Any] = self.remote_tool("""That\'s quite cool""" , ["""positive""", """negative"""] ) self.assertEqual(_A , """positive""" ) def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : Dict = self.tool(text="""That\'s quite cool""" , labels=["""positive""", """negative"""] ) self.assertEqual(_A , """positive""" ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Optional[int] = self.remote_tool(text="""That\'s quite cool""" , labels=["""positive""", """negative"""] ) self.assertEqual(_A , """positive""" )
350
"""simple docstring""" from __future__ import annotations class __SCREAMING_SNAKE_CASE : def __init__( self : Dict , snake_case : int ): '''simple docstring''' A__ : List[Any] = order # a_{0} ... a_{k} A__ : List[Any] = [1.0] + [0.0] * order # b_{0} ... b_{k} A__ : str = [1.0] + [0.0] * order # x[n-1] ... x[n-k] A__ : Union[str, Any] = [0.0] * self.order # y[n-1] ... y[n-k] A__ : List[str] = [0.0] * self.order def _UpperCamelCase ( self : Optional[int] , snake_case : list[float] , snake_case : list[float] ): '''simple docstring''' if len(snake_case ) < self.order: A__ : Any = [1.0, *a_coeffs] if len(snake_case ) != self.order + 1: A__ : str = ( F'Expected a_coeffs to have {self.order + 1} elements ' F'for {self.order}-order filter, got {len(snake_case )}' ) raise ValueError(snake_case ) if len(snake_case ) != self.order + 1: A__ : Union[str, Any] = ( F'Expected b_coeffs to have {self.order + 1} elements ' F'for {self.order}-order filter, got {len(snake_case )}' ) raise ValueError(snake_case ) A__ : Dict = a_coeffs A__ : Any = b_coeffs def _UpperCamelCase ( self : List[str] , snake_case : float ): '''simple docstring''' A__ : str = 0.0 # Start at index 1 and do index 0 at the end. for i in range(1 , self.order + 1 ): result += ( self.b_coeffs[i] * self.input_history[i - 1] - self.a_coeffs[i] * self.output_history[i - 1] ) A__ : Dict = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0] A__ : Tuple = self.input_history[:-1] A__ : int = self.output_history[:-1] A__ : Dict = sample A__ : Tuple = result return result
296
0
"""simple docstring""" import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow A_ = logging.getLogger() @unittest.skip('Temporarily disable the doc tests.' ) @require_torch @require_tf @slow class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _UpperCamelCase ( self : List[Any] , snake_case : Path , snake_case : Union[str, None] = None , snake_case : Union[List[str], None] = None , snake_case : Union[str, List[str], None] = None , snake_case : bool = True , ): '''simple docstring''' A__ : Optional[int] = [file for file in os.listdir(snake_case ) if os.path.isfile(os.path.join(snake_case , snake_case ) )] if identifier is not None: A__ : Union[str, Any] = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(snake_case , snake_case ): for n_ in n_identifier: A__ : List[str] = [file for file in files if n_ not in file] else: A__ : List[Any] = [file for file in files if n_identifier not in file] A__ : Optional[Any] = ignore_files or [] ignore_files.append("""__init__.py""" ) A__ : Dict = [file for file in files if file not in ignore_files] for file in files: # Open all files print("""Testing""" , snake_case ) if only_modules: A__ : Union[str, Any] = file.split(""".""" )[0] try: A__ : Any = getattr(snake_case , snake_case ) A__ : int = doctest.DocTestSuite(snake_case ) A__ : Dict = unittest.TextTestRunner().run(snake_case ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(F'{module_identifier} is not a module.' ) else: A__ : Union[str, Any] = doctest.testfile(str("""..""" / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : List[str] = Path("""src/transformers""" ) A__ : List[str] = """modeling""" A__ : Dict = [ """modeling_ctrl.py""", """modeling_tf_ctrl.py""", ] self.analyze_directory(snake_case , identifier=snake_case , ignore_files=snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : str = Path("""src/transformers""" ) A__ : List[Any] = """tokenization""" self.analyze_directory(snake_case , identifier=snake_case ) def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : Optional[Any] = Path("""src/transformers""" ) A__ : List[Any] = """configuration""" self.analyze_directory(snake_case , identifier=snake_case ) def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : Any = Path("""src/transformers""" ) A__ : str = ["""configuration""", """modeling""", """tokenization"""] self.analyze_directory(snake_case , n_identifier=snake_case ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Optional[int] = Path("""docs/source""" ) A__ : Optional[Any] = ["""favicon.ico"""] self.analyze_directory(snake_case , ignore_files=snake_case , only_modules=snake_case )
351
"""simple docstring""" import unittest from parameterized import parameterized from transformers import AutoTokenizer, GPTNeoXConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXModel, ) class __SCREAMING_SNAKE_CASE : def __init__( self : Optional[int] , snake_case : Optional[Any] , snake_case : Tuple=13 , snake_case : Dict=7 , snake_case : Optional[int]=True , snake_case : Union[str, Any]=True , snake_case : Dict=True , snake_case : Any=True , snake_case : List[str]=99 , snake_case : str=64 , snake_case : Optional[int]=5 , snake_case : str=4 , snake_case : List[Any]=37 , snake_case : Optional[Any]="gelu" , snake_case : List[str]=0.1 , snake_case : str=0.1 , snake_case : Optional[int]=512 , snake_case : Dict=16 , snake_case : List[Any]=2 , snake_case : Optional[int]=0.02 , snake_case : Any=3 , snake_case : Union[str, Any]=4 , snake_case : Dict=None , ): '''simple docstring''' A__ : Tuple = parent A__ : Union[str, Any] = batch_size A__ : List[str] = seq_length A__ : Optional[int] = is_training A__ : Dict = use_input_mask A__ : Any = use_token_type_ids A__ : Optional[Any] = use_labels A__ : List[str] = vocab_size A__ : Optional[int] = hidden_size A__ : Optional[Any] = num_hidden_layers A__ : Any = num_attention_heads A__ : List[Any] = intermediate_size A__ : Optional[Any] = hidden_act A__ : Optional[int] = hidden_dropout_prob A__ : Tuple = attention_probs_dropout_prob A__ : str = max_position_embeddings A__ : List[str] = type_vocab_size A__ : Union[str, Any] = type_sequence_label_size A__ : List[Any] = initializer_range A__ : Optional[int] = num_labels A__ : Dict = num_choices A__ : Dict = scope A__ : List[Any] = vocab_size - 1 def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : List[Any] = None if self.use_input_mask: A__ : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) A__ : Union[str, Any] = None if self.use_labels: A__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : Tuple = self.get_config() return config, input_ids, input_mask, token_labels def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' return GPTNeoXConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case , initializer_range=self.initializer_range , pad_token_id=self.pad_token_id , ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ , A__ , A__ , A__ : str = self.prepare_config_and_inputs() A__ : Union[str, Any] = True return config, input_ids, input_mask, token_labels def _UpperCamelCase ( self : Union[str, Any] , snake_case : Optional[int] , snake_case : List[str] , snake_case : int ): '''simple docstring''' A__ : Any = GPTNeoXModel(config=snake_case ) model.to(snake_case ) model.eval() A__ : int = model(snake_case , attention_mask=snake_case ) A__ : Optional[int] = model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : Union[str, Any] , snake_case : str , snake_case : Any , snake_case : Union[str, Any] ): '''simple docstring''' A__ : int = True A__ : str = GPTNeoXModel(snake_case ) model.to(snake_case ) model.eval() A__ : Tuple = model(snake_case , attention_mask=snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : Dict , snake_case : List[Any] , snake_case : str , snake_case : Optional[Any] , snake_case : Any ): '''simple docstring''' A__ : Any = GPTNeoXForCausalLM(config=snake_case ) model.to(snake_case ) model.eval() A__ : Tuple = 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 _UpperCamelCase ( self : List[str] , snake_case : Optional[Any] , snake_case : Optional[Any] , snake_case : Union[str, Any] , snake_case : Tuple ): '''simple docstring''' A__ : int = self.num_labels A__ : int = GPTNeoXForQuestionAnswering(snake_case ) model.to(snake_case ) model.eval() A__ : Optional[Any] = model(snake_case , attention_mask=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 _UpperCamelCase ( self : str , snake_case : Tuple , snake_case : int , snake_case : int , snake_case : Dict ): '''simple docstring''' A__ : List[Any] = self.num_labels A__ : Tuple = GPTNeoXForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : List[str] = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _UpperCamelCase ( self : Any , snake_case : Union[str, Any] , snake_case : int , snake_case : Tuple , snake_case : Any ): '''simple docstring''' A__ : Tuple = self.num_labels A__ : Any = GPTNeoXForTokenClassification(snake_case ) model.to(snake_case ) model.eval() A__ : Dict = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self : List[str] , snake_case : List[str] , snake_case : Tuple , snake_case : Any ): '''simple docstring''' A__ : Optional[int] = True A__ : Any = GPTNeoXForCausalLM(config=snake_case ) model.to(snake_case ) model.eval() # first forward pass A__ : Tuple = model(snake_case , attention_mask=snake_case , use_cache=snake_case ) A__ : str = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A__ : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ : Tuple = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and A__ : Any = torch.cat([input_ids, next_tokens] , dim=-1 ) A__ : Any = torch.cat([input_mask, next_mask] , dim=-1 ) A__ : Tuple = model(snake_case , attention_mask=snake_case , output_hidden_states=snake_case ) A__ : List[Any] = output_from_no_past["""hidden_states"""][0] A__ : List[str] = model( snake_case , attention_mask=snake_case , past_key_values=snake_case , output_hidden_states=snake_case , )["""hidden_states"""][0] # select random slice A__ : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() A__ : List[Any] = output_from_no_past[:, -3:, random_slice_idx].detach() A__ : Any = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(snake_case , snake_case , atol=1e-3 ) ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : str = self.prepare_config_and_inputs() A__ , A__ , A__ , A__ : Dict = config_and_inputs A__ : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase ): snake_case_ = ( ( GPTNeoXModel, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, ) if is_torch_available() else () ) snake_case_ = (GPTNeoXForCausalLM,) if is_torch_available() else () snake_case_ = ( { 'feature-extraction': GPTNeoXModel, 'question-answering': GPTNeoXForQuestionAnswering, 'text-classification': GPTNeoXForSequenceClassification, 'text-generation': GPTNeoXForCausalLM, 'token-classification': GPTNeoXForTokenClassification, 'zero-shot': GPTNeoXForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Any = GPTNeoXModelTester(self ) A__ : Any = ConfigTester(self , config_class=snake_case , hidden_size=64 , num_attention_heads=8 ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self : Any ): '''simple docstring''' A__ , A__ , A__ , A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(snake_case , snake_case , snake_case ) def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ , A__ , A__ , A__ : Dict = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(snake_case , snake_case , snake_case ) def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ , A__ , A__ , A__ : List[str] = self.model_tester.prepare_config_and_inputs_for_decoder() A__ : Optional[Any] = None self.model_tester.create_and_check_model_as_decoder(snake_case , snake_case , snake_case ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ , A__ , A__ , A__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(snake_case , snake_case , snake_case ) def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*snake_case ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case ) @unittest.skip(reason="""Feed forward chunking is not implemented""" ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' pass @parameterized.expand([("""linear""",), ("""dynamic""",)] ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Optional[Any] ): '''simple docstring''' A__ , A__ : int = self.model_tester.prepare_config_and_inputs_for_common() A__ : List[Any] = ids_tensor([1, 10] , config.vocab_size ) A__ : str = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A__ : Union[str, Any] = GPTNeoXModel(snake_case ) original_model.to(snake_case ) original_model.eval() A__ : Optional[int] = original_model(snake_case ).last_hidden_state A__ : List[str] = original_model(snake_case ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A__ : Optional[int] = {"""type""": scaling_type, """factor""": 10.0} A__ : Optional[int] = GPTNeoXModel(snake_case ) scaled_model.to(snake_case ) scaled_model.eval() A__ : List[str] = scaled_model(snake_case ).last_hidden_state A__ : Tuple = scaled_model(snake_case ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(snake_case , snake_case , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(snake_case , snake_case , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(snake_case , snake_case , atol=1e-5 ) ) @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Any = AutoTokenizer.from_pretrained("""EleutherAI/pythia-410m-deduped""" ) for checkpointing in [True, False]: A__ : Optional[Any] = GPTNeoXForCausalLM.from_pretrained("""EleutherAI/pythia-410m-deduped""" ) if checkpointing: model.gradient_checkpointing_enable() else: model.gradient_checkpointing_disable() model.to(snake_case ) A__ : Optional[Any] = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(snake_case ) # The hub repo. is updated on 2023-04-04, resulting in poor outputs. # See: https://github.com/huggingface/transformers/pull/24193 A__ : Union[str, Any] = """My favorite food is a good old-fashioned, old-fashioned, old-fashioned.\n\nI'm not sure""" A__ : Tuple = model.generate(**snake_case , do_sample=snake_case , max_new_tokens=20 ) A__ : Tuple = tokenizer.batch_decode(snake_case )[0] self.assertEqual(snake_case , snake_case )
296
0
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} A_ = { '''tokenizer_file''': { '''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json''', }, } A_ = { '''gpt-neox-20b''': 2048, } class __SCREAMING_SNAKE_CASE ( __lowercase ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["input_ids", "attention_mask"] def __init__( self : List[Any] , snake_case : int=None , snake_case : int=None , snake_case : str=None , snake_case : Any="<|endoftext|>" , snake_case : List[Any]="<|endoftext|>" , snake_case : Union[str, Any]="<|endoftext|>" , snake_case : str=False , **snake_case : Any , ): '''simple docstring''' super().__init__( snake_case_ , snake_case_ , tokenizer_file=snake_case_ , unk_token=snake_case_ , bos_token=snake_case_ , eos_token=snake_case_ , add_prefix_space=snake_case_ , **snake_case_ , ) A__ : int = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , snake_case_ ) != add_prefix_space: A__ : Dict = getattr(snake_case_ , pre_tok_state.pop("""type""" ) ) A__ : Optional[int] = add_prefix_space A__ : int = pre_tok_class(**snake_case_ ) A__ : Optional[int] = add_prefix_space def _UpperCamelCase ( self : str , snake_case : str , snake_case : Optional[str] = None ): '''simple docstring''' A__ : List[Any] = self._tokenizer.model.save(snake_case_ , name=snake_case_ ) return tuple(snake_case_ ) def _UpperCamelCase ( self : Optional[int] , snake_case : "Conversation" ): '''simple docstring''' A__ : int = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(snake_case_ , add_special_tokens=snake_case_ ) + [self.eos_token_id] ) if len(snake_case_ ) > self.model_max_length: A__ : Dict = input_ids[-self.model_max_length :] return input_ids
352
"""simple docstring""" from collections import defaultdict from math import gcd def _lowerCAmelCase ( UpperCAmelCase__ : int = 1_5_0_0_0_0_0 ) ->int: A__ : defaultdict = defaultdict(UpperCAmelCase__ ) A__ : Any = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1, UpperCAmelCase__, 2 ): if gcd(UpperCAmelCase__, UpperCAmelCase__ ) > 1: continue A__ : str = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(UpperCAmelCase__, limit + 1, UpperCAmelCase__ ): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1 ) if __name__ == "__main__": print(F'{solution() = }')
296
0
"""simple docstring""" def _lowerCAmelCase ( UpperCAmelCase__ : str, UpperCAmelCase__ : str ) ->str: def get_matched_characters(UpperCAmelCase__ : str, UpperCAmelCase__ : str ) -> str: A__ : int = [] A__ : Any = min(len(_stra ), len(_stra ) ) // 2 for i, l in enumerate(_stra ): A__ : Union[str, Any] = int(max(0, i - limit ) ) A__ : int = int(min(i + limit + 1, len(_stra ) ) ) if l in _stra[left:right]: matched.append(UpperCAmelCase__ ) A__ : Any = f'{_stra[0:_stra.index(UpperCAmelCase__ )]} {_stra[_stra.index(UpperCAmelCase__ ) + 1:]}' return "".join(UpperCAmelCase__ ) # matching characters A__ : Union[str, Any] = get_matched_characters(UpperCAmelCase__, UpperCAmelCase__ ) A__ : int = get_matched_characters(UpperCAmelCase__, UpperCAmelCase__ ) A__ : List[Any] = len(UpperCAmelCase__ ) # transposition A__ : int = ( len([(ca, ca) for ca, ca in zip(UpperCAmelCase__, UpperCAmelCase__ ) if ca != ca] ) // 2 ) if not match_count: A__ : List[str] = 0.0 else: A__ : Dict = ( 1 / 3 * ( match_count / len(UpperCAmelCase__ ) + match_count / len(UpperCAmelCase__ ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters A__ : Tuple = 0 for ca, ca in zip(stra[:4], stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler('''hello''', '''world'''))
353
"""simple docstring""" import os from distutils.util import strtobool def _lowerCAmelCase ( UpperCAmelCase__ : List[Any], UpperCAmelCase__ : Optional[Any] ) ->List[str]: for e in env_keys: A__ : List[Any] = int(os.environ.get(UpperCAmelCase__, -1 ) ) if val >= 0: return val return default def _lowerCAmelCase ( UpperCAmelCase__ : Tuple, UpperCAmelCase__ : str=False ) ->List[str]: A__ : List[Any] = os.environ.get(UpperCAmelCase__, str(UpperCAmelCase__ ) ) return strtobool(UpperCAmelCase__ ) == 1 # As its name indicates `strtobool` actually returns an int... def _lowerCAmelCase ( UpperCAmelCase__ : Tuple, UpperCAmelCase__ : List[Any]="no" ) ->int: A__ : str = os.environ.get(UpperCAmelCase__, str(UpperCAmelCase__ ) ) return value
296
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import _LazyModule A_ = {"tokenization_wav2vec2_phoneme": ["Wav2Vec2PhonemeCTCTokenizer"]} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
354
"""simple docstring""" import cva import numpy as np class __SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , snake_case : float , snake_case : int ): '''simple docstring''' if k in (0.04, 0.06): A__ : Optional[int] = k A__ : int = window_size else: raise ValueError("""invalid k value""" ) def __str__( self : List[Any] ): '''simple docstring''' return str(self.k ) def _UpperCamelCase ( self : int , snake_case : str ): '''simple docstring''' A__ : List[str] = cva.imread(snake_case , 0 ) A__ , A__ : Union[str, Any] = img.shape A__ : list[list[int]] = [] A__ : Optional[Any] = img.copy() A__ : List[str] = cva.cvtColor(snake_case , cva.COLOR_GRAY2RGB ) A__ , A__ : List[Any] = np.gradient(snake_case ) A__ : List[Any] = dx**2 A__ : Any = dy**2 A__ : Dict = dx * dy A__ : Any = 0.04 A__ : Optional[Any] = self.window_size // 2 for y in range(snake_case , h - offset ): for x in range(snake_case , w - offset ): A__ : List[str] = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() A__ : Tuple = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() A__ : Optional[int] = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() A__ : int = (wxx * wyy) - (wxy**2) A__ : Any = wxx + wyy A__ : List[str] = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 255 ) return color_img, corner_list if __name__ == "__main__": A_ = HarrisCorner(0.04, 3) A_ , A_ = edge_detect.detect('''path_to_image''') cva.imwrite('''detect.png''', color_img)
296
0
"""simple docstring""" from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class __SCREAMING_SNAKE_CASE ( UpperCamelCase__ ): def __init__( self : List[Any] , snake_case : pyspark.sql.DataFrame , snake_case : Optional[NamedSplit] = None , snake_case : Optional[Features] = None , snake_case : bool = True , snake_case : str = None , snake_case : bool = False , snake_case : str = None , snake_case : bool = True , snake_case : str = "arrow" , **snake_case : Dict , ): '''simple docstring''' super().__init__( split=UpperCamelCase_ , features=UpperCamelCase_ , cache_dir=UpperCamelCase_ , keep_in_memory=UpperCamelCase_ , streaming=UpperCamelCase_ , **UpperCamelCase_ , ) A__ : Dict = load_from_cache_file A__ : List[str] = file_format A__ : str = Spark( df=UpperCamelCase_ , features=UpperCamelCase_ , cache_dir=UpperCamelCase_ , working_dir=UpperCamelCase_ , **UpperCamelCase_ , ) def _UpperCamelCase ( self : int ): '''simple docstring''' if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) A__ : Tuple = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=UpperCamelCase_ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
355
"""simple docstring""" from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING A_ = logging.get_logger(__name__) A_ = Dict[str, Any] A_ = List[Prediction] @add_end_docstrings(UpperCamelCase ) class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): def __init__( self : str , *snake_case : Tuple , **snake_case : Tuple ): '''simple docstring''' super().__init__(*snake_case , **snake_case ) if self.framework == "tf": raise ValueError(F'The {self.__class__} is only available in PyTorch.' ) requires_backends(self , """vision""" ) self.check_model_type( dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items() ) ) def _UpperCamelCase ( self : List[Any] , **snake_case : Optional[int] ): '''simple docstring''' A__ : Dict = {} if "threshold" in kwargs: A__ : int = kwargs["""threshold"""] return {}, {}, postprocess_kwargs def __call__( self : Tuple , *snake_case : Union[str, Any] , **snake_case : Union[str, Any] ): '''simple docstring''' return super().__call__(*snake_case , **snake_case ) def _UpperCamelCase ( self : str , snake_case : int ): '''simple docstring''' A__ : List[str] = load_image(snake_case ) A__ : int = torch.IntTensor([[image.height, image.width]] ) A__ : Union[str, Any] = self.image_processor(images=[image] , return_tensors="""pt""" ) if self.tokenizer is not None: A__ : str = self.tokenizer(text=inputs["""words"""] , boxes=inputs["""boxes"""] , return_tensors="""pt""" ) A__ : List[str] = target_size return inputs def _UpperCamelCase ( self : Optional[int] , snake_case : List[Any] ): '''simple docstring''' A__ : str = model_inputs.pop("""target_size""" ) A__ : Dict = self.model(**snake_case ) A__ : Optional[Any] = outputs.__class__({"""target_size""": target_size, **outputs} ) if self.tokenizer is not None: A__ : str = model_inputs["""bbox"""] return model_outputs def _UpperCamelCase ( self : Tuple , snake_case : Optional[int] , snake_case : int=0.9 ): '''simple docstring''' A__ : Any = model_outputs["""target_size"""] if self.tokenizer is not None: # This is a LayoutLMForTokenClassification variant. # The OCR got the boxes and the model classified the words. A__ , A__ : Tuple = target_size[0].tolist() def unnormalize(snake_case : Optional[int] ): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ] ) ) A__ , A__ : Optional[int] = model_outputs["""logits"""].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 ) A__ : Optional[Any] = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] A__ : List[str] = [unnormalize(snake_case ) for bbox in model_outputs["""bbox"""].squeeze(0 )] A__ : Tuple = ["""score""", """label""", """box"""] A__ : Any = [dict(zip(snake_case , snake_case ) ) for vals in zip(scores.tolist() , snake_case , snake_case ) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel A__ : Union[str, Any] = self.image_processor.post_process_object_detection(snake_case , snake_case , snake_case ) A__ : str = raw_annotations[0] A__ : str = raw_annotation["""scores"""] A__ : List[Any] = raw_annotation["""labels"""] A__ : int = raw_annotation["""boxes"""] A__ : str = scores.tolist() A__ : Any = [self.model.config.idalabel[label.item()] for label in labels] A__ : int = [self._get_bounding_box(snake_case ) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] A__ : str = ["""score""", """label""", """box"""] A__ : Dict = [ dict(zip(snake_case , snake_case ) ) for vals in zip(raw_annotation["""scores"""] , raw_annotation["""labels"""] , raw_annotation["""boxes"""] ) ] return annotation def _UpperCamelCase ( self : Union[str, Any] , snake_case : "torch.Tensor" ): '''simple docstring''' if self.framework != "pt": raise ValueError("""The ObjectDetectionPipeline is only available in PyTorch.""" ) A__ , A__ , A__ , A__ : Any = box.int().tolist() A__ : Any = { """xmin""": xmin, """ymin""": ymin, """xmax""": xmax, """ymax""": ymax, } return bbox
296
0
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A_ = {'configuration_van': ['VAN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VanConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ 'VAN_PRETRAINED_MODEL_ARCHIVE_LIST', 'VanForImageClassification', 'VanModel', 'VanPreTrainedModel', ] if TYPE_CHECKING: from .configuration_van import VAN_PRETRAINED_CONFIG_ARCHIVE_MAP, VanConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_van import ( VAN_PRETRAINED_MODEL_ARCHIVE_LIST, VanForImageClassification, VanModel, VanPreTrainedModel, ) else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
356
"""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 A_ = logging.get_logger(__name__) A_ = { '''microsoft/table-transformer-detection''': ( '''https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json''' ), } class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = 'table-transformer' snake_case_ = ['past_key_values'] snake_case_ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Dict , snake_case : int=True , snake_case : Dict=None , snake_case : Union[str, Any]=3 , snake_case : Dict=100 , snake_case : Tuple=6 , snake_case : Optional[int]=2048 , snake_case : int=8 , snake_case : Dict=6 , snake_case : Any=2048 , snake_case : str=8 , snake_case : Union[str, Any]=0.0 , snake_case : List[str]=0.0 , snake_case : List[str]=True , snake_case : Any="relu" , snake_case : str=256 , snake_case : int=0.1 , snake_case : Dict=0.0 , snake_case : str=0.0 , snake_case : Union[str, Any]=0.02 , snake_case : Union[str, Any]=1.0 , snake_case : Optional[Any]=False , snake_case : int="sine" , snake_case : Optional[Any]="resnet50" , snake_case : Optional[int]=True , snake_case : Any=False , snake_case : int=1 , snake_case : Tuple=5 , snake_case : Optional[int]=2 , snake_case : Tuple=1 , snake_case : Optional[Any]=1 , snake_case : Optional[Any]=5 , snake_case : Dict=2 , snake_case : Any=0.1 , **snake_case : Any , ): '''simple docstring''' 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.""" ) A__ : Optional[Any] = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(snake_case , snake_case ): A__ : Optional[int] = backbone_config.get("""model_type""" ) A__ : Optional[int] = CONFIG_MAPPING[backbone_model_type] A__ : List[str] = config_class.from_dict(snake_case ) # set timm attributes to None A__ , A__ , A__ : str = None, None, None A__ : Tuple = use_timm_backbone A__ : str = backbone_config A__ : str = num_channels A__ : List[Any] = num_queries A__ : Optional[Any] = d_model A__ : Tuple = encoder_ffn_dim A__ : Union[str, Any] = encoder_layers A__ : List[Any] = encoder_attention_heads A__ : Optional[int] = decoder_ffn_dim A__ : Any = decoder_layers A__ : int = decoder_attention_heads A__ : Any = dropout A__ : Dict = attention_dropout A__ : Dict = activation_dropout A__ : Tuple = activation_function A__ : List[str] = init_std A__ : List[str] = init_xavier_std A__ : Any = encoder_layerdrop A__ : Optional[Any] = decoder_layerdrop A__ : Union[str, Any] = encoder_layers A__ : Dict = auxiliary_loss A__ : List[Any] = position_embedding_type A__ : Optional[Any] = backbone A__ : str = use_pretrained_backbone A__ : Union[str, Any] = dilation # Hungarian matcher A__ : Tuple = class_cost A__ : Optional[Any] = bbox_cost A__ : Dict = giou_cost # Loss coefficients A__ : Any = mask_loss_coefficient A__ : str = dice_loss_coefficient A__ : str = bbox_loss_coefficient A__ : Union[str, Any] = giou_loss_coefficient A__ : List[str] = eos_coefficient super().__init__(is_encoder_decoder=snake_case , **snake_case ) @property def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return self.encoder_attention_heads @property def _UpperCamelCase ( self : Dict ): '''simple docstring''' return self.d_model class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = version.parse('1.11' ) @property def _UpperCamelCase ( self : Any ): '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' return 1e-5 @property def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return 12
296
0
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { "microsoft/unispeech-sat-base-100h-libri-ft": ( "https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json" ), # See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat } class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = """unispeech-sat""" def __init__( self : str , snake_case : Any=32 , snake_case : int=768 , snake_case : str=12 , snake_case : int=12 , snake_case : List[Any]=3072 , snake_case : Optional[Any]="gelu" , snake_case : List[Any]=0.1 , snake_case : List[str]=0.1 , snake_case : List[str]=0.1 , snake_case : List[Any]=0.0 , snake_case : int=0.0 , snake_case : Union[str, Any]=0.1 , snake_case : List[str]=0.1 , snake_case : List[Any]=0.02 , snake_case : Optional[Any]=1e-5 , snake_case : int="group" , snake_case : Any="gelu" , snake_case : Any=(512, 512, 512, 512, 512, 512, 512) , snake_case : str=(5, 2, 2, 2, 2, 2, 2) , snake_case : Tuple=(10, 3, 3, 3, 3, 2, 2) , snake_case : Optional[int]=False , snake_case : Tuple=128 , snake_case : Optional[int]=16 , snake_case : List[Any]=False , snake_case : List[str]=True , snake_case : str=0.05 , snake_case : Optional[Any]=10 , snake_case : Dict=2 , snake_case : str=0.0 , snake_case : Any=10 , snake_case : str=0 , snake_case : Union[str, Any]=320 , snake_case : List[Any]=2 , snake_case : str=0.1 , snake_case : Dict=100 , snake_case : Tuple=256 , snake_case : Any=256 , snake_case : Tuple=0.1 , snake_case : Optional[int]="mean" , snake_case : List[Any]=False , snake_case : Union[str, Any]=False , snake_case : Any=256 , snake_case : List[Any]=(512, 512, 512, 512, 1500) , snake_case : Optional[int]=(5, 3, 3, 1, 1) , snake_case : List[Any]=(1, 2, 3, 1, 1) , snake_case : List[Any]=512 , snake_case : List[str]=0 , snake_case : List[str]=1 , snake_case : List[Any]=2 , snake_case : Optional[Any]=504 , **snake_case : Dict , ): '''simple docstring''' super().__init__(**_A , pad_token_id=_A , bos_token_id=_A , eos_token_id=_A ) A__ : Any = hidden_size A__ : int = feat_extract_norm A__ : Optional[Any] = feat_extract_activation A__ : List[str] = list(_A ) A__ : Any = list(_A ) A__ : str = list(_A ) A__ : List[str] = conv_bias A__ : Union[str, Any] = num_conv_pos_embeddings A__ : List[str] = num_conv_pos_embedding_groups A__ : Any = len(self.conv_dim ) A__ : List[str] = num_hidden_layers A__ : Optional[int] = intermediate_size A__ : List[Any] = hidden_act A__ : Dict = num_attention_heads A__ : Any = hidden_dropout A__ : Dict = attention_dropout A__ : List[str] = activation_dropout A__ : str = feat_proj_dropout A__ : str = final_dropout A__ : int = layerdrop A__ : int = layer_norm_eps A__ : Any = initializer_range A__ : str = vocab_size A__ : Dict = num_clusters A__ : Optional[int] = do_stable_layer_norm A__ : List[str] = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==""" """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =""" F' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,' F' `len(config.conv_kernel) = {len(self.conv_kernel )}`.' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 A__ : Optional[int] = apply_spec_augment A__ : Dict = mask_time_prob A__ : Optional[int] = mask_time_length A__ : str = mask_time_min_masks A__ : Optional[int] = mask_feature_prob A__ : Any = mask_feature_length A__ : Tuple = mask_feature_min_masks # parameters for pretraining with codevector quantized representations A__ : List[str] = num_codevectors_per_group A__ : Dict = num_codevector_groups A__ : Tuple = contrastive_logits_temperature A__ : Optional[int] = feat_quantizer_dropout A__ : Any = num_negatives A__ : List[str] = codevector_dim A__ : Union[str, Any] = proj_codevector_dim A__ : List[Any] = diversity_loss_weight # ctc loss A__ : List[Any] = ctc_loss_reduction A__ : Optional[int] = ctc_zero_infinity # SequenceClassification-specific parameter. Feel free to ignore for other classes. A__ : Any = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. A__ : Tuple = list(_A ) A__ : Union[str, Any] = list(_A ) A__ : Dict = list(_A ) A__ : Optional[Any] = xvector_output_dim @property def _UpperCamelCase ( self : Any ): '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
357
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = 'Salesforce/blip-image-captioning-base' snake_case_ = ( 'This is a tool that generates a description of an image. It takes an input named `image` which should be the ' 'image to caption, and returns a text that contains the description in English.' ) snake_case_ = 'image_captioner' snake_case_ = AutoModelForVisionaSeq snake_case_ = ['image'] snake_case_ = ['text'] def __init__( self : int , *snake_case : Optional[int] , **snake_case : Optional[int] ): '''simple docstring''' requires_backends(self , ["""vision"""] ) super().__init__(*snake_case , **snake_case ) def _UpperCamelCase ( self : int , snake_case : "Image" ): '''simple docstring''' return self.pre_processor(images=snake_case , return_tensors="""pt""" ) def _UpperCamelCase ( self : int , snake_case : List[Any] ): '''simple docstring''' return self.model.generate(**snake_case ) def _UpperCamelCase ( self : Optional[int] , snake_case : Any ): '''simple docstring''' return self.pre_processor.batch_decode(snake_case , skip_special_tokens=snake_case )[0].strip()
296
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A_ = { 'configuration_poolformer': [ 'POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PoolFormerConfig', 'PoolFormerOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ['PoolFormerFeatureExtractor'] A_ = ['PoolFormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ 'POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'PoolFormerForImageClassification', 'PoolFormerModel', 'PoolFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_poolformer import ( POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, PoolFormerConfig, PoolFormerOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_poolformer import PoolFormerFeatureExtractor from .image_processing_poolformer import PoolFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_poolformer import ( POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, PoolFormerForImageClassification, PoolFormerModel, PoolFormerPreTrainedModel, ) else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
358
"""simple docstring""" import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : List[Any] ): '''simple docstring''' super().__init__() A__ : int = nn.Linear(3 , 4 ) A__ : Union[str, Any] = nn.BatchNormad(4 ) A__ : Union[str, Any] = nn.Linear(4 , 5 ) def _UpperCamelCase ( self : str , snake_case : List[str] ): '''simple docstring''' return self.lineara(self.batchnorm(self.lineara(snake_case ) ) ) class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : int = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(snake_case , model.state_dict() ) A__ : List[str] = os.path.join(snake_case , """index.json""" ) self.assertTrue(os.path.isfile(snake_case ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: A__ : List[str] = os.path.join(snake_case , F'{key}.dat' ) self.assertTrue(os.path.isfile(snake_case ) ) # TODO: add tests on the fact weights are properly loaded def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Union[str, Any] = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: A__ : str = torch.randn(2 , 3 , dtype=snake_case ) with TemporaryDirectory() as tmp_dir: A__ : List[str] = offload_weight(snake_case , """weight""" , snake_case , {} ) A__ : Union[str, Any] = os.path.join(snake_case , """weight.dat""" ) self.assertTrue(os.path.isfile(snake_case ) ) self.assertDictEqual(snake_case , {"""weight""": {"""shape""": [2, 3], """dtype""": str(snake_case ).split(""".""" )[1]}} ) A__ : str = load_offloaded_weight(snake_case , index["""weight"""] ) self.assertTrue(torch.equal(snake_case , snake_case ) ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : str = ModelForTest() A__ : Union[str, Any] = model.state_dict() A__ : Optional[int] = {k: v for k, v in state_dict.items() if """linear2""" not in k} A__ : List[Any] = {k: v for k, v in state_dict.items() if """linear2""" in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(snake_case , snake_case ) A__ : Dict = OffloadedWeightsLoader(state_dict=snake_case , save_folder=snake_case ) # Every key is there with the right value self.assertEqual(sorted(snake_case ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(snake_case , weight_map[key] ) ) A__ : int = {k: v for k, v in state_dict.items() if """weight""" in k} A__ : Tuple = {k: v for k, v in state_dict.items() if """weight""" not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(snake_case , snake_case ) A__ : Optional[Any] = OffloadedWeightsLoader(state_dict=snake_case , save_folder=snake_case ) # Every key is there with the right value self.assertEqual(sorted(snake_case ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(snake_case , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(snake_case , snake_case ) # Duplicates are removed A__ : int = OffloadedWeightsLoader(state_dict=snake_case , save_folder=snake_case ) # Every key is there with the right value self.assertEqual(sorted(snake_case ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(snake_case , weight_map[key] ) ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : List[str] = {"""a.1""": 0, """a.10""": 1, """a.2""": 2} A__ : str = extract_submodules_state_dict(snake_case , ["""a.1""", """a.2"""] ) self.assertDictEqual(snake_case , {"""a.1""": 0, """a.2""": 2} ) A__ : Dict = {"""a.1.a""": 0, """a.10.a""": 1, """a.2.a""": 2} A__ : int = extract_submodules_state_dict(snake_case , ["""a.1""", """a.2"""] ) self.assertDictEqual(snake_case , {"""a.1.a""": 0, """a.2.a""": 2} )
296
0
A_ = { "Pillow": "Pillow", "accelerate": "accelerate>=0.11.0", "compel": "compel==0.1.8", "black": "black~=23.1", "datasets": "datasets", "filelock": "filelock", "flax": "flax>=0.4.1", "hf-doc-builder": "hf-doc-builder>=0.3.0", "huggingface-hub": "huggingface-hub>=0.13.2", "requests-mock": "requests-mock==1.10.0", "importlib_metadata": "importlib_metadata", "invisible-watermark": "invisible-watermark", "isort": "isort>=5.5.4", "jax": "jax>=0.2.8,!=0.3.2", "jaxlib": "jaxlib>=0.1.65", "Jinja2": "Jinja2", "k-diffusion": "k-diffusion>=0.0.12", "torchsde": "torchsde", "note_seq": "note_seq", "librosa": "librosa", "numpy": "numpy", "omegaconf": "omegaconf", "parameterized": "parameterized", "protobuf": "protobuf>=3.20.3,<4", "pytest": "pytest", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "ruff": "ruff>=0.0.241", "safetensors": "safetensors", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "scipy": "scipy", "onnx": "onnx", "regex": "regex!=2019.12.17", "requests": "requests", "tensorboard": "tensorboard", "torch": "torch>=1.4", "torchvision": "torchvision", "transformers": "transformers>=4.25.1", "urllib3": "urllib3<=2.0.0", }
359
"""simple docstring""" import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class __SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , snake_case : str , snake_case : List[Any]=13 , snake_case : Union[str, Any]=7 , snake_case : Optional[Any]=True , snake_case : str=True , snake_case : Dict=False , snake_case : Union[str, Any]=True , snake_case : Optional[Any]=99 , snake_case : str=32 , snake_case : Tuple=5 , snake_case : List[str]=4 , snake_case : Optional[int]=37 , snake_case : str="gelu" , snake_case : Tuple=0.1 , snake_case : Optional[int]=0.1 , snake_case : int=512 , snake_case : List[str]=16 , snake_case : str=2 , snake_case : Optional[int]=0.02 , snake_case : str=3 , snake_case : Dict=4 , snake_case : Optional[Any]=None , ): '''simple docstring''' A__ : int = parent A__ : Union[str, Any] = batch_size A__ : Optional[int] = seq_length A__ : List[Any] = is_training A__ : List[str] = use_input_mask A__ : Optional[Any] = use_token_type_ids A__ : List[Any] = use_labels A__ : Union[str, Any] = vocab_size A__ : List[Any] = hidden_size A__ : Any = num_hidden_layers A__ : Any = num_attention_heads A__ : Optional[int] = intermediate_size A__ : Any = hidden_act A__ : Tuple = hidden_dropout_prob A__ : Dict = attention_probs_dropout_prob A__ : Optional[int] = max_position_embeddings A__ : Tuple = type_vocab_size A__ : Union[str, Any] = type_sequence_label_size A__ : List[str] = initializer_range A__ : Any = num_labels A__ : Any = num_choices A__ : int = scope def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Tuple = None if self.use_input_mask: A__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) A__ : Union[str, Any] = None if self.use_token_type_ids: A__ : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A__ : int = None A__ : int = None A__ : List[str] = None if self.use_labels: A__ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : Dict = ids_tensor([self.batch_size] , self.num_choices ) A__ : Union[str, Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCamelCase ( self : Tuple ): '''simple docstring''' return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case , initializer_range=self.initializer_range , ) def _UpperCamelCase ( self : Optional[int] , snake_case : Dict , snake_case : Any , snake_case : Dict , snake_case : Any , snake_case : Union[str, Any] , snake_case : Tuple , snake_case : Optional[Any] ): '''simple docstring''' A__ : Optional[Any] = BioGptModel(config=snake_case ) model.to(snake_case ) model.eval() A__ : List[Any] = model(snake_case , attention_mask=snake_case ) A__ : Dict = model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : Optional[int] , snake_case : Dict , snake_case : Optional[int] , snake_case : List[str] , snake_case : str , snake_case : Optional[Any] , snake_case : List[str] , snake_case : List[Any] , snake_case : Tuple , snake_case : Optional[Any] , ): '''simple docstring''' A__ : List[str] = BioGptForCausalLM(config=snake_case ) model.to(snake_case ) model.eval() A__ : Union[str, Any] = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCamelCase ( self : Any , snake_case : str , snake_case : Tuple , snake_case : int , snake_case : Optional[Any] , snake_case : Any , *snake_case : Dict ): '''simple docstring''' A__ : Union[str, Any] = BioGptModel(config=snake_case ) model.to(snake_case ) model.eval() # create attention mask A__ : List[Any] = torch.ones(input_ids.shape , dtype=torch.long , device=snake_case ) A__ : Any = self.seq_length // 2 A__ : str = 0 # first forward pass A__ , A__ : List[Any] = model(snake_case , attention_mask=snake_case ).to_tuple() # create hypothetical next token and extent to next_input_ids A__ : int = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids A__ : List[str] = ids_tensor((1,) , snake_case ).item() + 1 A__ : Optional[int] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) A__ : int = random_other_next_tokens # append to next input_ids and attn_mask A__ : str = torch.cat([input_ids, next_tokens] , dim=-1 ) A__ : List[Any] = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=snake_case )] , dim=1 , ) # get two different outputs A__ : Union[str, Any] = model(snake_case , attention_mask=snake_case )["""last_hidden_state"""] A__ : Optional[int] = model(snake_case , past_key_values=snake_case , attention_mask=snake_case )["""last_hidden_state"""] # select random slice A__ : List[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() A__ : List[str] = output_from_no_past[:, -1, random_slice_idx].detach() A__ : Any = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(snake_case , snake_case , atol=1e-3 ) ) def _UpperCamelCase ( self : int , snake_case : Optional[Any] , snake_case : Optional[Any] , snake_case : str , snake_case : int , snake_case : Optional[Any] , *snake_case : str ): '''simple docstring''' A__ : Dict = BioGptModel(config=snake_case ).to(snake_case ).eval() A__ : Tuple = torch.ones(input_ids.shape , dtype=torch.long , device=snake_case ) # first forward pass A__ : Dict = model(snake_case , attention_mask=snake_case , use_cache=snake_case ) A__ , A__ : List[Any] = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids A__ : Union[str, Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ : int = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and A__ : str = torch.cat([input_ids, next_tokens] , dim=-1 ) A__ : Optional[int] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) A__ : Any = model(snake_case , attention_mask=snake_case )["""last_hidden_state"""] A__ : Union[str, Any] = model(snake_case , attention_mask=snake_case , past_key_values=snake_case )[ """last_hidden_state""" ] # select random slice A__ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() A__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() A__ : List[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(snake_case , snake_case , atol=1e-3 ) ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Tuple , snake_case : Union[str, Any] , snake_case : Optional[Any] , snake_case : Any , snake_case : Tuple , *snake_case : Union[str, Any] , snake_case : Union[str, Any]=False ): '''simple docstring''' A__ : Tuple = BioGptForCausalLM(snake_case ) model.to(snake_case ) if gradient_checkpointing: model.gradient_checkpointing_enable() A__ : Optional[Any] = model(snake_case , labels=snake_case ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def _UpperCamelCase ( self : int , snake_case : Optional[Any] , *snake_case : Optional[int] ): '''simple docstring''' A__ : int = BioGptModel(snake_case ) A__ : Union[str, Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def _UpperCamelCase ( self : Any , snake_case : Dict , snake_case : Tuple , snake_case : int , snake_case : Union[str, Any] , snake_case : Dict , *snake_case : Any ): '''simple docstring''' A__ : Union[str, Any] = self.num_labels A__ : int = BioGptForTokenClassification(snake_case ) model.to(snake_case ) model.eval() A__ : str = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : List[str] = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) : str = config_and_inputs A__ : Union[str, Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase ): snake_case_ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) snake_case_ = (BioGptForCausalLM,) if is_torch_available() else () snake_case_ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = False def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : List[str] = BioGptModelTester(self ) A__ : List[Any] = ConfigTester(self , config_class=snake_case , hidden_size=37 ) def _UpperCamelCase ( self : int ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Any ): '''simple docstring''' A__ : int = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A__ : str = type self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*snake_case ) def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*snake_case , gradient_checkpointing=snake_case ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*snake_case ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*snake_case ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*snake_case ) @slow def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : Tuple = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(snake_case ) A__ : Optional[int] = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) A__ : Any = """left""" # Define PAD Token = EOS Token = 50256 A__ : Optional[int] = tokenizer.eos_token A__ : Dict = model.config.eos_token_id # use different length sentences to test batching A__ : Union[str, Any] = [ """Hello, my dog is a little""", """Today, I""", ] A__ : List[str] = tokenizer(snake_case , return_tensors="""pt""" , padding=snake_case ) A__ : str = inputs["""input_ids"""].to(snake_case ) A__ : Dict = model.generate( input_ids=snake_case , attention_mask=inputs["""attention_mask"""].to(snake_case ) , ) A__ : Optional[int] = tokenizer(sentences[0] , return_tensors="""pt""" ).input_ids.to(snake_case ) A__ : Any = model.generate(input_ids=snake_case ) A__ : List[str] = inputs_non_padded.shape[-1] - inputs["""attention_mask"""][-1].long().sum().cpu().item() A__ : str = tokenizer(sentences[1] , return_tensors="""pt""" ).input_ids.to(snake_case ) A__ : Dict = model.generate(input_ids=snake_case , max_length=model.config.max_length - num_paddings ) A__ : Optional[Any] = tokenizer.batch_decode(snake_case , skip_special_tokens=snake_case ) A__ : List[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=snake_case ) A__ : str = tokenizer.decode(output_padded[0] , skip_special_tokens=snake_case ) A__ : Optional[int] = [ """Hello, my dog is a little bit bigger than a little bit.""", """Today, I have a good idea of how to use the information""", ] self.assertListEqual(snake_case , snake_case ) self.assertListEqual(snake_case , [non_padded_sentence, padded_sentence] ) @slow def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ : Optional[Any] = BioGptModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ , A__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() A__ : Optional[int] = 3 A__ : List[Any] = input_dict["""input_ids"""] A__ : Dict = input_ids.ne(1 ).to(snake_case ) A__ : Optional[Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) A__ : Union[str, Any] = BioGptForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : int = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ , A__ : str = self.model_tester.prepare_config_and_inputs_for_common() A__ : Any = 3 A__ : List[Any] = """multi_label_classification""" A__ : Dict = input_dict["""input_ids"""] A__ : Tuple = input_ids.ne(1 ).to(snake_case ) A__ : Any = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) A__ : Tuple = BioGptForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : List[str] = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : Optional[Any] = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) A__ : str = torch.tensor([[2, 4805, 9, 656, 21]] ) A__ : Dict = model(snake_case )[0] A__ : Tuple = 4_2384 A__ : str = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , snake_case ) A__ : str = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) ) @slow def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : Tuple = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) A__ : Any = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(snake_case ) torch.manual_seed(0 ) A__ : Tuple = tokenizer("""COVID-19 is""" , return_tensors="""pt""" ).to(snake_case ) A__ : Optional[int] = model.generate( **snake_case , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=snake_case , ) A__ : Optional[int] = tokenizer.decode(output_ids[0] , skip_special_tokens=snake_case ) A__ : List[str] = ( """COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the""" """ causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and""" """ territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),""" """ and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and""" """ more than 800,000 deaths.""" ) self.assertEqual(snake_case , snake_case )
296
0
"""simple docstring""" import argparse import torch from huggingface_hub import hf_hub_download from transformers import AutoTokenizer, RobertaPreLayerNormConfig, RobertaPreLayerNormForMaskedLM from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) def _lowerCAmelCase ( UpperCAmelCase__ : List[Any], UpperCAmelCase__ : int ) ->Optional[Any]: A__ : int = RobertaPreLayerNormConfig.from_pretrained( UpperCAmelCase__, architectures=["""RobertaPreLayerNormForMaskedLM"""] ) # convert state_dict A__ : Optional[Any] = torch.load(hf_hub_download(repo_id=UpperCAmelCase__, filename="""pytorch_model.bin""" ) ) A__ : int = {} for tensor_key, tensor_value in original_state_dict.items(): # The transformer implementation gives the model a unique name, rather than overwiriting 'roberta' if tensor_key.startswith("""roberta.""" ): A__ : Optional[int] = """roberta_prelayernorm.""" + tensor_key[len("""roberta.""" ) :] # The original implementation contains weights which are not used, remove them from the state_dict if tensor_key.endswith(""".self.LayerNorm.weight""" ) or tensor_key.endswith(""".self.LayerNorm.bias""" ): continue A__ : str = tensor_value A__ : Optional[Any] = RobertaPreLayerNormForMaskedLM.from_pretrained( pretrained_model_name_or_path=UpperCAmelCase__, config=UpperCAmelCase__, state_dict=UpperCAmelCase__ ) model.save_pretrained(UpperCAmelCase__ ) # convert tokenizer A__ : List[str] = AutoTokenizer.from_pretrained(UpperCAmelCase__ ) tokenizer.save_pretrained(UpperCAmelCase__ ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint-repo''', default=None, type=str, required=True, help='''Path the official PyTorch dump, e.g. \'andreasmadsen/efficient_mlm_m0.40\'.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) A_ = parser.parse_args() convert_roberta_prelayernorm_checkpoint_to_pytorch(args.checkpoint_repo, args.pytorch_dump_folder_path)
360
"""simple docstring""" 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 SPIECE_UNDERLINE, logging A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''spiece.model'''} A_ = { '''vocab_file''': { '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model''', '''xlnet-large-cased''': '''https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model''', } } A_ = { '''xlnet-base-cased''': None, '''xlnet-large-cased''': None, } # Segments (not really needed) A_ = 0 A_ = 1 A_ = 2 A_ = 3 A_ = 4 class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = 'left' def __init__( self : Dict , snake_case : int , snake_case : List[Any]=False , snake_case : List[str]=True , snake_case : Dict=False , snake_case : Optional[Any]="<s>" , snake_case : List[str]="</s>" , snake_case : Tuple="<unk>" , snake_case : Tuple="<sep>" , snake_case : Union[str, Any]="<pad>" , snake_case : Dict="<cls>" , snake_case : Optional[Any]="<mask>" , snake_case : Optional[int]=["<eop>", "<eod>"] , snake_case : Optional[Dict[str, Any]] = None , **snake_case : Dict , ): '''simple docstring''' A__ : Optional[int] = AddedToken(snake_case , lstrip=snake_case , rstrip=snake_case ) if isinstance(snake_case , snake_case ) else mask_token A__ : Union[str, Any] = {} 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 , additional_special_tokens=snake_case , sp_model_kwargs=self.sp_model_kwargs , **snake_case , ) A__ : str = 3 A__ : str = do_lower_case A__ : Optional[Any] = remove_space A__ : List[Any] = keep_accents A__ : Union[str, Any] = vocab_file A__ : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(snake_case ) @property def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' return len(self.sp_model ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : 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 : str ): '''simple docstring''' A__ : int = self.__dict__.copy() A__ : int = None return state def __setstate__( self : Tuple , snake_case : Union[str, Any] ): '''simple docstring''' A__ : int = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): A__ : Optional[int] = {} A__ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _UpperCamelCase ( self : List[str] , snake_case : Optional[Any] ): '''simple docstring''' if self.remove_space: A__ : Optional[Any] = """ """.join(inputs.strip().split() ) else: A__ : Dict = inputs A__ : str = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: A__ : Any = unicodedata.normalize("""NFKD""" , snake_case ) A__ : Optional[int] = """""".join([c for c in outputs if not unicodedata.combining(snake_case )] ) if self.do_lower_case: A__ : Any = outputs.lower() return outputs def _UpperCamelCase ( self : Union[str, Any] , snake_case : str ): '''simple docstring''' A__ : Dict = self.preprocess_text(snake_case ) A__ : Dict = self.sp_model.encode(snake_case , out_type=snake_case ) A__ : Optional[int] = [] for piece in pieces: if len(snake_case ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): A__ : Optional[Any] = 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__ : Any = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(snake_case ) else: new_pieces.append(snake_case ) return new_pieces def _UpperCamelCase ( self : List[str] , snake_case : Tuple ): '''simple docstring''' return self.sp_model.PieceToId(snake_case ) def _UpperCamelCase ( self : List[str] , snake_case : Any ): '''simple docstring''' return self.sp_model.IdToPiece(snake_case ) def _UpperCamelCase ( self : Optional[int] , snake_case : Any ): '''simple docstring''' A__ : Union[str, Any] = """""".join(snake_case ).replace(snake_case , """ """ ).strip() return out_string def _UpperCamelCase ( self : int , snake_case : List[int] , snake_case : bool = False , snake_case : bool = None , snake_case : bool = True , **snake_case : Union[str, Any] , ): '''simple docstring''' A__ : List[str] = kwargs.pop("""use_source_tokenizer""" , snake_case ) A__ : Any = self.convert_ids_to_tokens(snake_case , skip_special_tokens=snake_case ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 A__ : Any = [] A__ : Any = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(snake_case ) ) A__ : str = [] sub_texts.append(snake_case ) else: current_sub_text.append(snake_case ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(snake_case ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens A__ : Dict = """""".join(snake_case ) A__ : int = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: A__ : Tuple = self.clean_up_tokenization(snake_case ) return clean_text else: return text def _UpperCamelCase ( self : str , snake_case : List[int] , snake_case : Optional[List[int]] = None ): '''simple docstring''' A__ : Tuple = [self.sep_token_id] A__ : Dict = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _UpperCamelCase ( self : Dict , snake_case : List[int] , snake_case : Optional[List[int]] = None , snake_case : bool = False ): '''simple docstring''' 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 ([0] * len(snake_case )) + [1] + ([0] * len(snake_case )) + [1, 1] return ([0] * len(snake_case )) + [1, 1] def _UpperCamelCase ( self : str , snake_case : List[int] , snake_case : Optional[List[int]] = None ): '''simple docstring''' A__ : Any = [self.sep_token_id] A__ : int = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _UpperCamelCase ( self : Optional[Any] , snake_case : str , snake_case : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(snake_case ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A__ : List[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__ : Optional[Any] = self.sp_model.serialized_model_proto() fi.write(snake_case ) return (out_vocab_file,)
296
0
"""simple docstring""" import json import os import shutil import tempfile from unittest import TestCase from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available if is_torch_available() and is_datasets_available() and is_faiss_available(): from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.tokenization_rag import RagTokenizer @require_faiss @require_torch class __SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Optional[Any] = tempfile.mkdtemp() A__ : Dict = 8 # DPR tok A__ : List[str] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] A__ : List[str] = os.path.join(self.tmpdirname , """dpr_tokenizer""" ) os.makedirs(__A , exist_ok=__A ) A__ : int = os.path.join(__A , DPR_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] ) ) # BART tok A__ : Optional[Any] = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', ] A__ : int = dict(zip(__A , range(len(__A ) ) ) ) A__ : Tuple = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] A__ : Any = {'''unk_token''': '''<unk>'''} A__ : int = os.path.join(self.tmpdirname , """bart_tokenizer""" ) os.makedirs(__A , exist_ok=__A ) A__ : int = os.path.join(__A , BART_VOCAB_FILES_NAMES["""vocab_file"""] ) A__ : List[str] = os.path.join(__A , BART_VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__A ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__A ) ) def _UpperCamelCase ( self : int ): '''simple docstring''' return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , """dpr_tokenizer""" ) ) def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , """bart_tokenizer""" ) ) def _UpperCamelCase ( self : int ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) @require_tokenizers def _UpperCamelCase ( self : Any ): '''simple docstring''' A__ : Dict = os.path.join(self.tmpdirname , """rag_tokenizer""" ) A__ : Tuple = RagConfig(question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() ) A__ : List[str] = RagTokenizer(question_encoder=self.get_dpr_tokenizer() , generator=self.get_bart_tokenizer() ) rag_config.save_pretrained(__A ) rag_tokenizer.save_pretrained(__A ) A__ : List[Any] = RagTokenizer.from_pretrained(__A , config=__A ) self.assertIsInstance(new_rag_tokenizer.question_encoder , __A ) self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab() , rag_tokenizer.question_encoder.get_vocab() ) self.assertIsInstance(new_rag_tokenizer.generator , __A ) self.assertEqual(new_rag_tokenizer.generator.get_vocab() , rag_tokenizer.generator.get_vocab() ) @slow def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : int = RagTokenizer.from_pretrained("""facebook/rag-token-nq""" ) A__ : Optional[int] = [ '''who got the first nobel prize in physics''', '''when is the next deadpool movie being released''', '''which mode is used for short wave broadcast service''', '''who is the owner of reading football club''', '''when is the next scandal episode coming out''', '''when is the last time the philadelphia won the superbowl''', '''what is the most current adobe flash player version''', '''how many episodes are there in dragon ball z''', '''what is the first step in the evolution of the eye''', '''where is gall bladder situated in human body''', '''what is the main mineral in lithium batteries''', '''who is the president of usa right now''', '''where do the greasers live in the outsiders''', '''panda is a national animal of which country''', '''what is the name of manchester united stadium''', ] A__ : Optional[Any] = tokenizer(__A ) self.assertIsNotNone(__A ) @slow def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Any = RagTokenizer.from_pretrained("""facebook/rag-sequence-nq""" ) A__ : List[Any] = [ '''who got the first nobel prize in physics''', '''when is the next deadpool movie being released''', '''which mode is used for short wave broadcast service''', '''who is the owner of reading football club''', '''when is the next scandal episode coming out''', '''when is the last time the philadelphia won the superbowl''', '''what is the most current adobe flash player version''', '''how many episodes are there in dragon ball z''', '''what is the first step in the evolution of the eye''', '''where is gall bladder situated in human body''', '''what is the main mineral in lithium batteries''', '''who is the president of usa right now''', '''where do the greasers live in the outsiders''', '''panda is a national animal of which country''', '''what is the name of manchester united stadium''', ] A__ : Optional[int] = tokenizer(__A ) self.assertIsNotNone(__A )
361
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) def _lowerCAmelCase ( UpperCAmelCase__ : List[Any] ) ->List[str]: A__ : Union[str, Any] = DPTConfig() if "large" in checkpoint_url: A__ : int = 1_0_2_4 A__ : Union[str, Any] = 4_0_9_6 A__ : Optional[int] = 2_4 A__ : int = 1_6 A__ : Union[str, Any] = [5, 1_1, 1_7, 2_3] A__ : Tuple = [2_5_6, 5_1_2, 1_0_2_4, 1_0_2_4] A__ : Tuple = (1, 3_8_4, 3_8_4) if "ade" in checkpoint_url: A__ : Optional[int] = True A__ : int = 1_5_0 A__ : Union[str, Any] = """huggingface/label-files""" A__ : List[Any] = """ade20k-id2label.json""" A__ : Union[str, Any] = json.load(open(cached_download(hf_hub_url(UpperCAmelCase__, UpperCAmelCase__, repo_type="""dataset""" ) ), """r""" ) ) A__ : List[Any] = {int(UpperCAmelCase__ ): v for k, v in idalabel.items()} A__ : Dict = idalabel A__ : List[Any] = {v: k for k, v in idalabel.items()} A__ : Optional[Any] = [1, 1_5_0, 4_8_0, 4_8_0] return config, expected_shape def _lowerCAmelCase ( UpperCAmelCase__ : int ) ->Any: A__ : List[Any] = ["""pretrained.model.head.weight""", """pretrained.model.head.bias"""] for k in ignore_keys: state_dict.pop(UpperCAmelCase__, UpperCAmelCase__ ) def _lowerCAmelCase ( UpperCAmelCase__ : Union[str, Any] ) ->List[str]: if ( "pretrained.model" in name and "cls_token" not in name and "pos_embed" not in name and "patch_embed" not in name ): A__ : str = name.replace("""pretrained.model""", """dpt.encoder""" ) if "pretrained.model" in name: A__ : Dict = name.replace("""pretrained.model""", """dpt.embeddings""" ) if "patch_embed" in name: A__ : List[Any] = name.replace("""patch_embed""", """patch_embeddings""" ) if "pos_embed" in name: A__ : int = name.replace("""pos_embed""", """position_embeddings""" ) if "attn.proj" in name: A__ : Tuple = name.replace("""attn.proj""", """attention.output.dense""" ) if "proj" in name and "project" not in name: A__ : List[Any] = name.replace("""proj""", """projection""" ) if "blocks" in name: A__ : Optional[Any] = name.replace("""blocks""", """layer""" ) if "mlp.fc1" in name: A__ : int = name.replace("""mlp.fc1""", """intermediate.dense""" ) if "mlp.fc2" in name: A__ : List[str] = name.replace("""mlp.fc2""", """output.dense""" ) if "norm1" in name: A__ : Any = name.replace("""norm1""", """layernorm_before""" ) if "norm2" in name: A__ : List[str] = name.replace("""norm2""", """layernorm_after""" ) if "scratch.output_conv" in name: A__ : Optional[int] = name.replace("""scratch.output_conv""", """head""" ) if "scratch" in name: A__ : List[str] = name.replace("""scratch""", """neck""" ) if "layer1_rn" in name: A__ : List[str] = name.replace("""layer1_rn""", """convs.0""" ) if "layer2_rn" in name: A__ : Optional[int] = name.replace("""layer2_rn""", """convs.1""" ) if "layer3_rn" in name: A__ : Any = name.replace("""layer3_rn""", """convs.2""" ) if "layer4_rn" in name: A__ : Any = name.replace("""layer4_rn""", """convs.3""" ) if "refinenet" in name: A__ : Union[str, Any] = int(name[len("""neck.refinenet""" ) : len("""neck.refinenet""" ) + 1] ) # tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3 A__ : str = name.replace(f'refinenet{layer_idx}', f'fusion_stage.layers.{abs(layer_idx-4 )}' ) if "out_conv" in name: A__ : Optional[Any] = name.replace("""out_conv""", """projection""" ) if "resConfUnit1" in name: A__ : List[Any] = name.replace("""resConfUnit1""", """residual_layer1""" ) if "resConfUnit2" in name: A__ : Tuple = name.replace("""resConfUnit2""", """residual_layer2""" ) if "conv1" in name: A__ : Tuple = name.replace("""conv1""", """convolution1""" ) if "conv2" in name: A__ : List[Any] = name.replace("""conv2""", """convolution2""" ) # readout blocks if "pretrained.act_postprocess1.0.project.0" in name: A__ : Union[str, Any] = name.replace("""pretrained.act_postprocess1.0.project.0""", """neck.reassemble_stage.readout_projects.0.0""" ) if "pretrained.act_postprocess2.0.project.0" in name: A__ : Tuple = name.replace("""pretrained.act_postprocess2.0.project.0""", """neck.reassemble_stage.readout_projects.1.0""" ) if "pretrained.act_postprocess3.0.project.0" in name: A__ : Optional[Any] = name.replace("""pretrained.act_postprocess3.0.project.0""", """neck.reassemble_stage.readout_projects.2.0""" ) if "pretrained.act_postprocess4.0.project.0" in name: A__ : Optional[Any] = name.replace("""pretrained.act_postprocess4.0.project.0""", """neck.reassemble_stage.readout_projects.3.0""" ) # resize blocks if "pretrained.act_postprocess1.3" in name: A__ : Any = name.replace("""pretrained.act_postprocess1.3""", """neck.reassemble_stage.layers.0.projection""" ) if "pretrained.act_postprocess1.4" in name: A__ : List[Any] = name.replace("""pretrained.act_postprocess1.4""", """neck.reassemble_stage.layers.0.resize""" ) if "pretrained.act_postprocess2.3" in name: A__ : Dict = name.replace("""pretrained.act_postprocess2.3""", """neck.reassemble_stage.layers.1.projection""" ) if "pretrained.act_postprocess2.4" in name: A__ : Optional[Any] = name.replace("""pretrained.act_postprocess2.4""", """neck.reassemble_stage.layers.1.resize""" ) if "pretrained.act_postprocess3.3" in name: A__ : Union[str, Any] = name.replace("""pretrained.act_postprocess3.3""", """neck.reassemble_stage.layers.2.projection""" ) if "pretrained.act_postprocess4.3" in name: A__ : Optional[int] = name.replace("""pretrained.act_postprocess4.3""", """neck.reassemble_stage.layers.3.projection""" ) if "pretrained.act_postprocess4.4" in name: A__ : Dict = name.replace("""pretrained.act_postprocess4.4""", """neck.reassemble_stage.layers.3.resize""" ) if "pretrained" in name: A__ : Union[str, Any] = name.replace("""pretrained""", """dpt""" ) if "bn" in name: A__ : Union[str, Any] = name.replace("""bn""", """batch_norm""" ) if "head" in name: A__ : Dict = name.replace("""head""", """head.head""" ) if "encoder.norm" in name: A__ : Optional[int] = name.replace("""encoder.norm""", """layernorm""" ) if "auxlayer" in name: A__ : List[str] = name.replace("""auxlayer""", """auxiliary_head.head""" ) return name def _lowerCAmelCase ( UpperCAmelCase__ : int, UpperCAmelCase__ : Dict ) ->str: for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) A__ : Any = state_dict.pop(f'dpt.encoder.layer.{i}.attn.qkv.weight' ) A__ : Tuple = state_dict.pop(f'dpt.encoder.layer.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict A__ : List[str] = in_proj_weight[: config.hidden_size, :] A__ : int = in_proj_bias[: config.hidden_size] A__ : Tuple = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] A__ : Any = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] A__ : str = in_proj_weight[ -config.hidden_size :, : ] A__ : Optional[Any] = in_proj_bias[-config.hidden_size :] def _lowerCAmelCase ( ) ->List[str]: A__ : int = """http://images.cocodataset.org/val2017/000000039769.jpg""" A__ : int = Image.open(requests.get(UpperCAmelCase__, stream=UpperCAmelCase__ ).raw ) return im @torch.no_grad() def _lowerCAmelCase ( UpperCAmelCase__ : int, UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : str, UpperCAmelCase__ : int ) ->str: A__ , A__ : Dict = get_dpt_config(UpperCAmelCase__ ) # load original state_dict from URL A__ : Any = torch.hub.load_state_dict_from_url(UpperCAmelCase__, map_location="""cpu""" ) # remove certain keys remove_ignore_keys_(UpperCAmelCase__ ) # rename keys for key in state_dict.copy().keys(): A__ : int = state_dict.pop(UpperCAmelCase__ ) A__ : str = val # read in qkv matrices read_in_q_k_v(UpperCAmelCase__, UpperCAmelCase__ ) # load HuggingFace model A__ : Optional[Any] = DPTForSemanticSegmentation(UpperCAmelCase__ ) if """ade""" in checkpoint_url else DPTForDepthEstimation(UpperCAmelCase__ ) model.load_state_dict(UpperCAmelCase__ ) model.eval() # Check outputs on an image A__ : Optional[Any] = 4_8_0 if """ade""" in checkpoint_url else 3_8_4 A__ : Dict = DPTImageProcessor(size=UpperCAmelCase__ ) A__ : Optional[int] = prepare_img() A__ : Any = image_processor(UpperCAmelCase__, return_tensors="""pt""" ) # forward pass A__ : List[str] = model(**UpperCAmelCase__ ).logits if """ade""" in checkpoint_url else model(**UpperCAmelCase__ ).predicted_depth # Assert logits A__ : Optional[Any] = torch.tensor([[6.3199, 6.3629, 6.4148], [6.3850, 6.3615, 6.4166], [6.3519, 6.3176, 6.3575]] ) if "ade" in checkpoint_url: A__ : Optional[int] = torch.tensor([[4.0480, 4.2420, 4.4360], [4.3124, 4.5693, 4.8261], [4.5768, 4.8965, 5.2163]] ) assert outputs.shape == torch.Size(UpperCAmelCase__ ) assert ( torch.allclose(outputs[0, 0, :3, :3], UpperCAmelCase__, atol=1e-4 ) if "ade" in checkpoint_url else torch.allclose(outputs[0, :3, :3], UpperCAmelCase__ ) ) Path(UpperCAmelCase__ ).mkdir(exist_ok=UpperCAmelCase__ ) print(f'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(UpperCAmelCase__ ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(UpperCAmelCase__ ) if push_to_hub: print("""Pushing model to hub...""" ) model.push_to_hub( repo_path_or_name=Path(UpperCAmelCase__, UpperCAmelCase__ ), organization="""nielsr""", commit_message="""Add model""", use_temp_dir=UpperCAmelCase__, ) image_processor.push_to_hub( repo_path_or_name=Path(UpperCAmelCase__, UpperCAmelCase__ ), organization="""nielsr""", commit_message="""Add image processor""", use_temp_dir=UpperCAmelCase__, ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt''', type=str, help='''URL of the original DPT checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', action='''store_true''', ) parser.add_argument( '''--model_name''', default='''dpt-large''', type=str, help='''Name of the model, in case you\'re pushing to the hub.''', ) A_ = parser.parse_args() convert_dpt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
296
0
"""simple docstring""" from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { '''huggingface/informer-tourism-monthly''': ( '''https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json''' ), # See all Informer models at https://huggingface.co/models?filter=informer } class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = 'informer' snake_case_ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self : Optional[int] , snake_case : Any = None , snake_case : Optional[int] = None , snake_case : Union[str, Any] = "student_t" , snake_case : Optional[int] = "nll" , snake_case : Dict = 1 , snake_case : List[str] = None , snake_case : int = "mean" , snake_case : List[str] = 0 , snake_case : Tuple = 0 , snake_case : List[Any] = 0 , snake_case : Optional[Any] = 0 , snake_case : List[str] = None , snake_case : Union[str, Any] = None , snake_case : Tuple = 64 , snake_case : Optional[Any] = 32 , snake_case : List[Any] = 32 , snake_case : int = 2 , snake_case : Tuple = 2 , snake_case : Any = 2 , snake_case : Optional[Any] = 2 , snake_case : str = True , snake_case : int = "gelu" , snake_case : Dict = 0.05 , snake_case : List[Any] = 0.1 , snake_case : int = 0.1 , snake_case : Union[str, Any] = 0.1 , snake_case : Optional[int] = 0.1 , snake_case : str = 100 , snake_case : List[str] = 0.02 , snake_case : str=True , snake_case : Union[str, Any] = "prob" , snake_case : Any = 5 , snake_case : List[str] = True , **snake_case : Any , ): '''simple docstring''' A__ : Union[str, Any] = prediction_length A__ : List[Any] = context_length or prediction_length A__ : List[Any] = distribution_output A__ : str = loss A__ : List[str] = input_size A__ : List[str] = num_time_features A__ : str = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7] A__ : str = scaling A__ : Union[str, Any] = num_dynamic_real_features A__ : List[Any] = num_static_real_features A__ : str = num_static_categorical_features # set cardinality if cardinality and num_static_categorical_features > 0: if len(__a ) != num_static_categorical_features: raise ValueError( """The cardinality should be a list of the same length as `num_static_categorical_features`""" ) A__ : List[Any] = cardinality else: A__ : int = [0] # set embedding_dimension if embedding_dimension and num_static_categorical_features > 0: if len(__a ) != num_static_categorical_features: raise ValueError( """The embedding dimension should be a list of the same length as `num_static_categorical_features`""" ) A__ : Any = embedding_dimension else: A__ : int = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] A__ : Optional[Any] = num_parallel_samples # Transformer architecture configuration A__ : int = input_size * len(self.lags_sequence ) + self._number_of_features A__ : Any = d_model A__ : List[Any] = encoder_attention_heads A__ : List[str] = decoder_attention_heads A__ : int = encoder_ffn_dim A__ : str = decoder_ffn_dim A__ : Tuple = encoder_layers A__ : List[str] = decoder_layers A__ : Any = dropout A__ : Any = attention_dropout A__ : Dict = activation_dropout A__ : Union[str, Any] = encoder_layerdrop A__ : Optional[int] = decoder_layerdrop A__ : List[str] = activation_function A__ : Dict = init_std A__ : List[str] = use_cache # Informer A__ : Tuple = attention_type A__ : int = sampling_factor A__ : Dict = distil super().__init__(is_encoder_decoder=__a , **__a ) @property def _UpperCamelCase ( self : Any ): '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
362
"""simple docstring""" import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py A_ = '''src/diffusers''' A_ = '''.''' # This is to make sure the diffusers module imported is the one in the repo. A_ = importlib.util.spec_from_file_location( '''diffusers''', os.path.join(DIFFUSERS_PATH, '''__init__.py'''), submodule_search_locations=[DIFFUSERS_PATH], ) A_ = spec.loader.load_module() def _lowerCAmelCase ( UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : Optional[Any] ) ->Any: return line.startswith(UpperCAmelCase__ ) or len(UpperCAmelCase__ ) <= 1 or re.search(R"""^\s*\)(\s*->.*:|:)\s*$""", UpperCAmelCase__ ) is not None def _lowerCAmelCase ( UpperCAmelCase__ : List[str] ) ->Union[str, Any]: A__ : Any = object_name.split(""".""" ) A__ : int = 0 # First let's find the module where our object lives. A__ : str = parts[i] while i < len(UpperCAmelCase__ ) and not os.path.isfile(os.path.join(UpperCAmelCase__, f'{module}.py' ) ): i += 1 if i < len(UpperCAmelCase__ ): A__ : Union[str, Any] = os.path.join(UpperCAmelCase__, parts[i] ) if i >= len(UpperCAmelCase__ ): raise ValueError(f'`object_name` should begin with the name of a module of diffusers but got {object_name}.' ) with open(os.path.join(UpperCAmelCase__, f'{module}.py' ), """r""", encoding="""utf-8""", newline="""\n""" ) as f: A__ : List[Any] = f.readlines() # Now let's find the class / func in the code! A__ : Optional[Any] = """""" A__ : Any = 0 for name in parts[i + 1 :]: while ( line_index < len(UpperCAmelCase__ ) and re.search(Rf'^{indent}(class|def)\s+{name}(\(|\:)', lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(UpperCAmelCase__ ): raise ValueError(f' {object_name} does not match any function or class in {module}.' ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). A__ : List[Any] = line_index while line_index < len(UpperCAmelCase__ ) and _should_continue(lines[line_index], UpperCAmelCase__ ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 A__ : List[Any] = lines[start_index:line_index] return "".join(UpperCAmelCase__ ) A_ = re.compile(r'''^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)''') A_ = re.compile(r'''^\s*(\S+)->(\S+)(\s+.*|$)''') A_ = re.compile(r'''<FILL\s+[^>]*>''') def _lowerCAmelCase ( UpperCAmelCase__ : List[str] ) ->Optional[Any]: A__ : Dict = code.split("""\n""" ) A__ : List[Any] = 0 while idx < len(UpperCAmelCase__ ) and len(lines[idx] ) == 0: idx += 1 if idx < len(UpperCAmelCase__ ): return re.search(R"""^(\s*)\S""", lines[idx] ).groups()[0] return "" def _lowerCAmelCase ( UpperCAmelCase__ : Optional[Any] ) ->int: A__ : str = len(get_indent(UpperCAmelCase__ ) ) > 0 if has_indent: A__ : Union[str, Any] = f'class Bla:\n{code}' A__ : Optional[Any] = black.Mode(target_versions={black.TargetVersion.PYaa}, line_length=1_1_9, preview=UpperCAmelCase__ ) A__ : Tuple = black.format_str(UpperCAmelCase__, mode=UpperCAmelCase__ ) A__ , A__ : List[Any] = style_docstrings_in_code(UpperCAmelCase__ ) return result[len("""class Bla:\n""" ) :] if has_indent else result def _lowerCAmelCase ( UpperCAmelCase__ : Any, UpperCAmelCase__ : Dict=False ) ->List[Any]: with open(UpperCAmelCase__, """r""", encoding="""utf-8""", newline="""\n""" ) as f: A__ : int = f.readlines() A__ : Dict = [] A__ : List[str] = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(UpperCAmelCase__ ): A__ : Dict = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. A__ , A__ , A__ : Dict = search.groups() A__ : Tuple = find_code_in_diffusers(UpperCAmelCase__ ) A__ : int = get_indent(UpperCAmelCase__ ) A__ : List[str] = line_index + 1 if indent == theoretical_indent else line_index + 2 A__ : Tuple = theoretical_indent A__ : Optional[Any] = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. A__ : Tuple = True while line_index < len(UpperCAmelCase__ ) and should_continue: line_index += 1 if line_index >= len(UpperCAmelCase__ ): break A__ : Optional[int] = lines[line_index] A__ : Tuple = _should_continue(UpperCAmelCase__, UpperCAmelCase__ ) and re.search(f'^{indent}# End copy', UpperCAmelCase__ ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 A__ : Dict = lines[start_index:line_index] A__ : Tuple = """""".join(UpperCAmelCase__ ) # Remove any nested `Copied from` comments to avoid circular copies A__ : Optional[int] = [line for line in theoretical_code.split("""\n""" ) if _re_copy_warning.search(UpperCAmelCase__ ) is None] A__ : Optional[Any] = """\n""".join(UpperCAmelCase__ ) # Before comparing, use the `replace_pattern` on the original code. if len(UpperCAmelCase__ ) > 0: A__ : int = replace_pattern.replace("""with""", """""" ).split(""",""" ) A__ : List[Any] = [_re_replace_pattern.search(UpperCAmelCase__ ) for p in patterns] for pattern in patterns: if pattern is None: continue A__ , A__ , A__ : Union[str, Any] = pattern.groups() A__ : Union[str, Any] = re.sub(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) if option.strip() == "all-casing": A__ : List[Any] = re.sub(obja.lower(), obja.lower(), UpperCAmelCase__ ) A__ : Tuple = re.sub(obja.upper(), obja.upper(), UpperCAmelCase__ ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line A__ : Optional[int] = blackify(lines[start_index - 1] + theoretical_code ) A__ : List[Any] = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: A__ : List[Any] = lines[:start_index] + [theoretical_code] + lines[line_index:] A__ : Tuple = start_index + 1 if overwrite and len(UpperCAmelCase__ ) > 0: # Warn the user a file has been modified. print(f'Detected changes, rewriting {filename}.' ) with open(UpperCAmelCase__, """w""", encoding="""utf-8""", newline="""\n""" ) as f: f.writelines(UpperCAmelCase__ ) return diffs def _lowerCAmelCase ( UpperCAmelCase__ : bool = False ) ->Any: A__ : Dict = glob.glob(os.path.join(UpperCAmelCase__, """**/*.py""" ), recursive=UpperCAmelCase__ ) A__ : str = [] for filename in all_files: A__ : Any = is_copy_consistent(UpperCAmelCase__, UpperCAmelCase__ ) diffs += [f'- {filename}: copy does not match {d[0]} at line {d[1]}' for d in new_diffs] if not overwrite and len(UpperCAmelCase__ ) > 0: A__ : Any = """\n""".join(UpperCAmelCase__ ) raise Exception( """Found the following copy inconsistencies:\n""" + diff + """\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.""" ) if __name__ == "__main__": A_ = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') A_ = parser.parse_args() check_copies(args.fix_and_overwrite)
296
0
"""simple docstring""" import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) A_ = logging.getLogger() def _lowerCAmelCase ( ) ->Union[str, Any]: A__ : Tuple = argparse.ArgumentParser() parser.add_argument("""-f""" ) A__ : Union[str, Any] = parser.parse_args() return args.f def _lowerCAmelCase ( UpperCAmelCase__ : Optional[int] ) ->Optional[Any]: A__ : str = {} A__ : List[str] = os.path.join(UpperCAmelCase__, """all_results.json""" ) if os.path.exists(UpperCAmelCase__ ): with open(UpperCAmelCase__, """r""" ) as f: A__ : str = json.load(UpperCAmelCase__ ) else: raise ValueError(f'can\'t find {path}' ) return results def _lowerCAmelCase ( ) ->int: A__ : List[str] = torch.cuda.is_available() and torch_device == """cuda""" return is_using_cuda and is_apex_available() A_ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class __SCREAMING_SNAKE_CASE ( _snake_case ): @classmethod def _UpperCamelCase ( cls : Optional[int] ): '''simple docstring''' A__ : Optional[int] = tempfile.mkdtemp() A__ : Dict = os.path.join(cls.tmpdir , """default_config.yml""" ) write_basic_config(save_location=cls.configPath ) A__ : List[Any] = ["""accelerate""", """launch""", """--config_file""", cls.configPath] @classmethod def _UpperCamelCase ( cls : Optional[Any] ): '''simple docstring''' shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : List[Any] = self.get_auto_remove_tmp_dir() A__ : int = F'\n {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py\n --model_name_or_path distilbert-base-uncased\n --output_dir {tmp_dir}\n --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --learning_rate=1e-4\n --seed=42\n --checkpointing_steps epoch\n --with_tracking\n '.split() if is_cuda_and_apex_available(): testargs.append("""--fp16""" ) run_command(self._launch_args + testargs ) A__ : Any = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result["""eval_accuracy"""] , 0.75 ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase__ , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase__ , """glue_no_trainer""" ) ) ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def _UpperCamelCase ( self : Any ): '''simple docstring''' A__ : Tuple = self.get_auto_remove_tmp_dir() A__ : Dict = F'\n {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py\n --model_name_or_path distilgpt2\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --block_size 128\n --per_device_train_batch_size 5\n --per_device_eval_batch_size 5\n --num_train_epochs 2\n --output_dir {tmp_dir}\n --checkpointing_steps epoch\n --with_tracking\n '.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) A__ : Any = get_results(UpperCamelCase__ ) self.assertLess(result["""perplexity"""] , 100 ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase__ , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase__ , """clm_no_trainer""" ) ) ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Tuple = self.get_auto_remove_tmp_dir() A__ : Optional[Any] = F'\n {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py\n --model_name_or_path distilroberta-base\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --output_dir {tmp_dir}\n --num_train_epochs=1\n --checkpointing_steps epoch\n --with_tracking\n '.split() run_command(self._launch_args + testargs ) A__ : str = get_results(UpperCamelCase__ ) self.assertLess(result["""perplexity"""] , 42 ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase__ , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase__ , """mlm_no_trainer""" ) ) ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : List[Any] = 7 if get_gpu_count() > 1 else 2 A__ : str = self.get_auto_remove_tmp_dir() A__ : Optional[Any] = F'\n {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py\n --model_name_or_path bert-base-uncased\n --train_file tests/fixtures/tests_samples/conll/sample.json\n --validation_file tests/fixtures/tests_samples/conll/sample.json\n --output_dir {tmp_dir}\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=2\n --num_train_epochs={epochs}\n --seed 7\n --checkpointing_steps epoch\n --with_tracking\n '.split() run_command(self._launch_args + testargs ) A__ : str = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result["""eval_accuracy"""] , 0.75 ) self.assertLess(result["""train_loss"""] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase__ , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase__ , """ner_no_trainer""" ) ) ) @unittest.skip(reason="""Fix me @muellerzr""" ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : List[str] = self.get_auto_remove_tmp_dir() A__ : List[Any] = F'\n {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py\n --model_name_or_path bert-base-uncased\n --version_2_with_negative\n --train_file tests/fixtures/tests_samples/SQUAD/sample.json\n --validation_file tests/fixtures/tests_samples/SQUAD/sample.json\n --output_dir {tmp_dir}\n --seed=42\n --max_train_steps=10\n --num_warmup_steps=2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --checkpointing_steps epoch\n --with_tracking\n '.split() run_command(self._launch_args + testargs ) A__ : List[str] = get_results(UpperCamelCase__ ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result["""eval_f1"""] , 28 ) self.assertGreaterEqual(result["""eval_exact"""] , 28 ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase__ , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase__ , """qa_no_trainer""" ) ) ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def _UpperCamelCase ( self : Any ): '''simple docstring''' A__ : List[Any] = self.get_auto_remove_tmp_dir() A__ : Dict = F'\n {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py\n --model_name_or_path bert-base-uncased\n --train_file tests/fixtures/tests_samples/swag/sample.json\n --validation_file tests/fixtures/tests_samples/swag/sample.json\n --output_dir {tmp_dir}\n --max_train_steps=20\n --num_warmup_steps=2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --with_tracking\n '.split() run_command(self._launch_args + testargs ) A__ : List[Any] = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result["""eval_accuracy"""] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase__ , """swag_no_trainer""" ) ) ) @slow @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : int = self.get_auto_remove_tmp_dir() A__ : str = F'\n {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py\n --model_name_or_path t5-small\n --train_file tests/fixtures/tests_samples/xsum/sample.json\n --validation_file tests/fixtures/tests_samples/xsum/sample.json\n --output_dir {tmp_dir}\n --max_train_steps=50\n --num_warmup_steps=8\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --checkpointing_steps epoch\n --with_tracking\n '.split() run_command(self._launch_args + testargs ) A__ : str = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result["""eval_rouge1"""] , 10 ) self.assertGreaterEqual(result["""eval_rouge2"""] , 2 ) self.assertGreaterEqual(result["""eval_rougeL"""] , 7 ) self.assertGreaterEqual(result["""eval_rougeLsum"""] , 7 ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase__ , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase__ , """summarization_no_trainer""" ) ) ) @slow @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : str = self.get_auto_remove_tmp_dir() A__ : str = F'\n {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py\n --model_name_or_path sshleifer/student_marian_en_ro_6_1\n --source_lang en\n --target_lang ro\n --train_file tests/fixtures/tests_samples/wmt16/sample.json\n --validation_file tests/fixtures/tests_samples/wmt16/sample.json\n --output_dir {tmp_dir}\n --max_train_steps=50\n --num_warmup_steps=8\n --num_beams=6\n --learning_rate=3e-3\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --source_lang en_XX\n --target_lang ro_RO\n --checkpointing_steps epoch\n --with_tracking\n '.split() run_command(self._launch_args + testargs ) A__ : List[Any] = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result["""eval_bleu"""] , 30 ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase__ , """epoch_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase__ , """translation_no_trainer""" ) ) ) @slow def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Optional[int] = logging.StreamHandler(sys.stdout ) logger.addHandler(UpperCamelCase__ ) A__ : Optional[int] = self.get_auto_remove_tmp_dir() A__ : List[Any] = F'\n {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py\n --dataset_name huggingface/semantic-segmentation-test-sample\n --output_dir {tmp_dir}\n --max_train_steps=10\n --num_warmup_steps=2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --checkpointing_steps epoch\n '.split() run_command(self._launch_args + testargs ) A__ : Dict = get_results(UpperCamelCase__ ) self.assertGreaterEqual(result["""eval_overall_accuracy"""] , 0.10 ) @mock.patch.dict(os.environ , {"""WANDB_MODE""": """offline"""} ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : List[str] = self.get_auto_remove_tmp_dir() A__ : Union[str, Any] = F'\n {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py\n --model_name_or_path google/vit-base-patch16-224-in21k\n --dataset_name hf-internal-testing/cats_vs_dogs_sample\n --learning_rate 1e-4\n --per_device_train_batch_size 2\n --per_device_eval_batch_size 1\n --max_train_steps 2\n --train_val_split 0.1\n --seed 42\n --output_dir {tmp_dir}\n --with_tracking\n --checkpointing_steps 1\n '.split() if is_cuda_and_apex_available(): testargs.append("""--fp16""" ) run_command(self._launch_args + testargs ) A__ : Union[str, Any] = get_results(UpperCamelCase__ ) # The base model scores a 25% self.assertGreaterEqual(result["""eval_accuracy"""] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase__ , """step_1""" ) ) ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase__ , """image_classification_no_trainer""" ) ) )
363
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) A_ = { '''configuration_llama''': ['''LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LlamaConfig'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ['''LlamaTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ['''LlamaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''LlamaForCausalLM''', '''LlamaModel''', '''LlamaPreTrainedModel''', '''LlamaForSequenceClassification''', ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
296
0
"""simple docstring""" import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed A_ = '''true''' def _lowerCAmelCase ( UpperCAmelCase__ : Optional[Any], UpperCAmelCase__ : List[str]=8_2, UpperCAmelCase__ : str=1_6 ) ->Optional[int]: set_seed(4_2 ) A__ : str = RegressionModel() A__ : List[Any] = deepcopy(SCREAMING_SNAKE_CASE_ ) A__ : Optional[int] = RegressionDataset(length=SCREAMING_SNAKE_CASE_ ) A__ : str = DataLoader(SCREAMING_SNAKE_CASE_, batch_size=SCREAMING_SNAKE_CASE_ ) model.to(accelerator.device ) A__ , A__ : str = accelerator.prepare(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) return model, ddp_model, dataloader def _lowerCAmelCase ( UpperCAmelCase__ : Accelerator, UpperCAmelCase__ : Optional[int]=False ) ->Optional[int]: A__ : Any = AutoTokenizer.from_pretrained("""hf-internal-testing/mrpc-bert-base-cased""" ) A__ : Tuple = load_dataset("""glue""", """mrpc""", split="""validation""" ) def tokenize_function(UpperCAmelCase__ : List[Any] ): A__ : int = tokenizer(examples["""sentence1"""], examples["""sentence2"""], truncation=SCREAMING_SNAKE_CASE_, max_length=SCREAMING_SNAKE_CASE_ ) return outputs with accelerator.main_process_first(): A__ : Any = dataset.map( SCREAMING_SNAKE_CASE_, batched=SCREAMING_SNAKE_CASE_, remove_columns=["""idx""", """sentence1""", """sentence2"""], ) A__ : str = tokenized_datasets.rename_column("""label""", """labels""" ) def collate_fn(UpperCAmelCase__ : Union[str, Any] ): if use_longest: return tokenizer.pad(SCREAMING_SNAKE_CASE_, padding="""longest""", return_tensors="""pt""" ) return tokenizer.pad(SCREAMING_SNAKE_CASE_, padding="""max_length""", max_length=1_2_8, return_tensors="""pt""" ) return DataLoader(SCREAMING_SNAKE_CASE_, shuffle=SCREAMING_SNAKE_CASE_, collate_fn=SCREAMING_SNAKE_CASE_, batch_size=1_6 ) def _lowerCAmelCase ( UpperCAmelCase__ : List[str], UpperCAmelCase__ : int ) ->List[Any]: A__ : Tuple = Accelerator(dispatch_batches=SCREAMING_SNAKE_CASE_, split_batches=SCREAMING_SNAKE_CASE_ ) A__ : Optional[Any] = get_dataloader(SCREAMING_SNAKE_CASE_, not dispatch_batches ) A__ : int = AutoModelForSequenceClassification.from_pretrained( """hf-internal-testing/mrpc-bert-base-cased""", return_dict=SCREAMING_SNAKE_CASE_ ) A__ , A__ : Optional[int] = accelerator.prepare(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def _lowerCAmelCase ( UpperCAmelCase__ : str, UpperCAmelCase__ : List[str], UpperCAmelCase__ : Optional[int] ) ->Any: A__ : List[str] = [] for batch in dataloader: A__ , A__ : List[str] = batch.values() with torch.no_grad(): A__ : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ ) A__ , A__ : Optional[int] = accelerator.gather_for_metrics((logit, target) ) logits_and_targets.append((logit, target) ) A__ , A__ : List[str] = [], [] for logit, targ in logits_and_targets: logits.append(SCREAMING_SNAKE_CASE_ ) targs.append(SCREAMING_SNAKE_CASE_ ) A__ , A__ : Optional[int] = torch.cat(SCREAMING_SNAKE_CASE_ ), torch.cat(SCREAMING_SNAKE_CASE_ ) return logits, targs def _lowerCAmelCase ( UpperCAmelCase__ : Accelerator, UpperCAmelCase__ : Union[str, Any]=8_2, UpperCAmelCase__ : Union[str, Any]=False, UpperCAmelCase__ : Any=False, UpperCAmelCase__ : Optional[int]=1_6 ) ->List[Any]: A__ , A__ , A__ : Dict = get_basic_setup(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) A__ , A__ : List[str] = generate_predictions(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) assert ( len(SCREAMING_SNAKE_CASE_ ) == num_samples ), f'Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(SCREAMING_SNAKE_CASE_ )}' def _lowerCAmelCase ( UpperCAmelCase__ : bool = False, UpperCAmelCase__ : bool = False ) ->List[str]: A__ : List[Any] = evaluate.load("""glue""", """mrpc""" ) A__ , A__ : List[Any] = get_mrpc_setup(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) # First do baseline A__ , A__ , A__ : List[str] = setup["""no"""] model.to(SCREAMING_SNAKE_CASE_ ) model.eval() for batch in dataloader: batch.to(SCREAMING_SNAKE_CASE_ ) with torch.inference_mode(): A__ : Tuple = model(**SCREAMING_SNAKE_CASE_ ) A__ : Tuple = outputs.logits.argmax(dim=-1 ) metric.add_batch(predictions=SCREAMING_SNAKE_CASE_, references=batch["""labels"""] ) A__ : Any = metric.compute() # Then do distributed A__ , A__ , A__ : Optional[Any] = setup["""ddp"""] model.eval() for batch in dataloader: with torch.inference_mode(): A__ : int = model(**SCREAMING_SNAKE_CASE_ ) A__ : Any = outputs.logits.argmax(dim=-1 ) A__ : Union[str, Any] = batch["""labels"""] A__ , A__ : int = accelerator.gather_for_metrics((preds, references) ) metric.add_batch(predictions=SCREAMING_SNAKE_CASE_, references=SCREAMING_SNAKE_CASE_ ) A__ : List[Any] = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key], distributed[key] ), f'Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n' def _lowerCAmelCase ( ) ->str: A__ : List[Any] = Accelerator(split_batches=SCREAMING_SNAKE_CASE_, dispatch_batches=SCREAMING_SNAKE_CASE_ ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print("""**Testing gather_for_metrics**""" ) for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(f'With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`' ) test_mrpc(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) accelerator.state._reset_state() if accelerator.is_local_main_process: print("""**Test torch metrics**""" ) for split_batches in [True, False]: for dispatch_batches in [True, False]: A__ : Union[str, Any] = Accelerator(split_batches=SCREAMING_SNAKE_CASE_, dispatch_batches=SCREAMING_SNAKE_CASE_ ) if accelerator.is_local_main_process: print(f'With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99' ) test_torch_metrics(SCREAMING_SNAKE_CASE_, 9_9 ) accelerator.state._reset_state() if accelerator.is_local_main_process: print("""**Test last batch is not dropped when perfectly divisible**""" ) A__ : Any = Accelerator() test_torch_metrics(SCREAMING_SNAKE_CASE_, 5_1_2 ) accelerator.state._reset_state() def _lowerCAmelCase ( UpperCAmelCase__ : List[str] ) ->Tuple: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
364
"""simple docstring""" import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels A_ = object() # For specifying empty leaf dict `{}` A_ = object() def _lowerCAmelCase ( UpperCAmelCase__ : Tuple, UpperCAmelCase__ : List[Any] ) ->Dict: A__ : Union[str, Any] = tuple((re.compile(x + """$""" ) for x in qs) ) for i in range(len(UpperCAmelCase__ ) - len(UpperCAmelCase__ ) + 1 ): A__ : Optional[Any] = [x.match(UpperCAmelCase__ ) for x, y in zip(UpperCAmelCase__, ks[i:] )] if matches and all(UpperCAmelCase__ ): return True return False def _lowerCAmelCase ( UpperCAmelCase__ : List[Any] ) ->Dict: def replace(UpperCAmelCase__ : int, UpperCAmelCase__ : List[str] ): for rule, replacement in rules: if _match(UpperCAmelCase__, UpperCAmelCase__ ): return replacement return val return replace def _lowerCAmelCase ( ) ->Tuple: return [ # embeddings (("transformer", "wpe", "embedding"), P("""mp""", UpperCAmelCase__ )), (("transformer", "wte", "embedding"), P("""mp""", UpperCAmelCase__ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(UpperCAmelCase__, """mp""" )), (("attention", "out_proj", "kernel"), P("""mp""", UpperCAmelCase__ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(UpperCAmelCase__, """mp""" )), (("mlp", "c_fc", "bias"), P("""mp""" )), (("mlp", "c_proj", "kernel"), P("""mp""", UpperCAmelCase__ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def _lowerCAmelCase ( UpperCAmelCase__ : Tuple ) ->Any: A__ : Union[str, Any] = _get_partition_rules() A__ : int = _replacement_rules(UpperCAmelCase__ ) A__ : Tuple = {k: _unmatched for k in flatten_dict(UpperCAmelCase__ )} A__ : Optional[int] = {k: replace(UpperCAmelCase__, UpperCAmelCase__ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(UpperCAmelCase__ ) )
296
0
"""simple docstring""" import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEmbeddings, BertLayer, BertPooler, BertPreTrainedModel, ) def _lowerCAmelCase ( UpperCAmelCase__ : List[Any] ) ->Union[str, Any]: A__ : List[str] = torch.exp(snake_case__ ) A__ : List[str] = torch.sum(snake_case__, dim=1 ) # sum of exp(x_i) A__ : str = torch.sum(x * exp_x, dim=1 ) # sum of x_i * exp(x_i) return torch.log(snake_case__ ) - B / A class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : List[str] , snake_case : Union[str, Any] ): '''simple docstring''' super().__init__() A__ : Optional[int] = config.output_attentions A__ : Union[str, Any] = config.output_hidden_states A__ : Any = nn.ModuleList([BertLayer(SCREAMING_SNAKE_CASE_ ) for _ in range(config.num_hidden_layers )] ) A__ : int = nn.ModuleList([BertHighway(SCREAMING_SNAKE_CASE_ ) for _ in range(config.num_hidden_layers )] ) A__ : str = [-1 for _ in range(config.num_hidden_layers )] def _UpperCamelCase ( self : Tuple , snake_case : int ): '''simple docstring''' if (type(SCREAMING_SNAKE_CASE_ ) is float) or (type(SCREAMING_SNAKE_CASE_ ) is int): for i in range(len(self.early_exit_entropy ) ): A__ : str = x else: A__ : Optional[int] = x def _UpperCamelCase ( self : str , snake_case : int ): '''simple docstring''' A__ : int = pooler.state_dict() for highway in self.highway: for name, param in highway.pooler.state_dict().items(): param.copy_(loaded_model[name] ) def _UpperCamelCase ( self : Any , snake_case : Tuple , snake_case : int=None , snake_case : Dict=None , snake_case : Optional[Any]=None , snake_case : List[str]=None , ): '''simple docstring''' A__ : Optional[int] = () A__ : Tuple = () A__ : Optional[int] = () for i, layer_module in enumerate(self.layer ): if self.output_hidden_states: A__ : Dict = all_hidden_states + (hidden_states,) A__ : List[Any] = layer_module( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , head_mask[i] , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A__ : Union[str, Any] = layer_outputs[0] if self.output_attentions: A__ : Tuple = all_attentions + (layer_outputs[1],) A__ : Dict = (hidden_states,) if self.output_hidden_states: A__ : Dict = current_outputs + (all_hidden_states,) if self.output_attentions: A__ : Union[str, Any] = current_outputs + (all_attentions,) A__ : List[str] = self.highway[i](SCREAMING_SNAKE_CASE_ ) # logits, pooled_output if not self.training: A__ : str = highway_exit[0] A__ : Tuple = entropy(SCREAMING_SNAKE_CASE_ ) A__ : Dict = highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy A__ : int = all_highway_exits + (highway_exit,) if highway_entropy < self.early_exit_entropy[i]: A__ : int = (highway_logits,) + current_outputs[1:] + (all_highway_exits,) raise HighwayException(SCREAMING_SNAKE_CASE_ , i + 1 ) else: A__ : Union[str, Any] = all_highway_exits + (highway_exit,) # Add last layer if self.output_hidden_states: A__ : Optional[int] = all_hidden_states + (hidden_states,) A__ : int = (hidden_states,) if self.output_hidden_states: A__ : Optional[int] = outputs + (all_hidden_states,) if self.output_attentions: A__ : str = outputs + (all_attentions,) A__ : Optional[Any] = outputs + (all_highway_exits,) return outputs # last-layer hidden state, (all hidden states), (all attentions), all highway exits @add_start_docstrings( 'The Bert Model transformer with early exiting (DeeBERT). ' , a__ , ) class __SCREAMING_SNAKE_CASE ( a__ ): def __init__( self : Optional[Any] , snake_case : List[str] ): '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE_ ) A__ : Tuple = config A__ : Optional[int] = BertEmbeddings(SCREAMING_SNAKE_CASE_ ) A__ : Any = DeeBertEncoder(SCREAMING_SNAKE_CASE_ ) A__ : Any = BertPooler(SCREAMING_SNAKE_CASE_ ) self.init_weights() def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' self.encoder.init_highway_pooler(self.pooler ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return self.embeddings.word_embeddings def _UpperCamelCase ( self : Tuple , snake_case : Any ): '''simple docstring''' A__ : Tuple = value def _UpperCamelCase ( self : Dict , snake_case : int ): '''simple docstring''' for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(SCREAMING_SNAKE_CASE_ ) @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE_ ) def _UpperCamelCase ( self : Tuple , snake_case : List[Any]=None , snake_case : List[Any]=None , snake_case : int=None , snake_case : Optional[Any]=None , snake_case : Union[str, Any]=None , snake_case : int=None , snake_case : Any=None , snake_case : Optional[int]=None , ): '''simple docstring''' if input_ids is not None and inputs_embeds is not None: raise ValueError("""You cannot specify both input_ids and inputs_embeds at the same time""" ) elif input_ids is not None: A__ : List[Any] = input_ids.size() elif inputs_embeds is not None: A__ : Optional[Any] = inputs_embeds.size()[:-1] else: raise ValueError("""You have to specify either input_ids or inputs_embeds""" ) A__ : List[str] = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: A__ : Tuple = torch.ones(SCREAMING_SNAKE_CASE_ , device=SCREAMING_SNAKE_CASE_ ) if encoder_attention_mask is None: A__ : Tuple = torch.ones(SCREAMING_SNAKE_CASE_ , device=SCREAMING_SNAKE_CASE_ ) if token_type_ids is None: A__ : str = torch.zeros(SCREAMING_SNAKE_CASE_ , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. A__ : torch.Tensor = self.get_extended_attention_mask(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_attention_mask.dim() == 3: A__ : int = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.dim() == 2: A__ : str = encoder_attention_mask[:, None, None, :] A__ : Any = encoder_extended_attention_mask.to( dtype=next(self.parameters() ).dtype ) # fp16 compatibility A__ : List[str] = (1.0 - encoder_extended_attention_mask) * -1_0000.0 # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] A__ : Optional[int] = self.get_head_mask(SCREAMING_SNAKE_CASE_ , self.config.num_hidden_layers ) A__ : Optional[int] = self.embeddings( input_ids=SCREAMING_SNAKE_CASE_ , position_ids=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , inputs_embeds=SCREAMING_SNAKE_CASE_ ) A__ : Optional[Any] = self.encoder( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , head_mask=SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , encoder_attention_mask=SCREAMING_SNAKE_CASE_ , ) A__ : Dict = encoder_outputs[0] A__ : Union[str, Any] = self.pooler(SCREAMING_SNAKE_CASE_ ) A__ : List[str] = ( sequence_output, pooled_output, ) + encoder_outputs[ 1: ] # add hidden_states and attentions if they are here return outputs # sequence_output, pooled_output, (hidden_states), (attentions), highway exits class __SCREAMING_SNAKE_CASE ( a__ ): def __init__( self : Union[str, Any] , snake_case : Union[str, Any] , snake_case : int ): '''simple docstring''' A__ : Dict = message A__ : int = exit_layer # start from 1! class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : str , snake_case : Union[str, Any] ): '''simple docstring''' super().__init__() A__ : Union[str, Any] = BertPooler(SCREAMING_SNAKE_CASE_ ) A__ : Optional[int] = nn.Dropout(config.hidden_dropout_prob ) A__ : Union[str, Any] = nn.Linear(config.hidden_size , config.num_labels ) def _UpperCamelCase ( self : int , snake_case : str ): '''simple docstring''' A__ : Dict = encoder_outputs[0] A__ : List[Any] = self.pooler(SCREAMING_SNAKE_CASE_ ) # "return" pooler_output # BertModel A__ : Any = (pooler_input, pooler_output) + encoder_outputs[1:] # "return" bmodel_output # Dropout and classification A__ : List[str] = bmodel_output[1] A__ : Optional[Any] = self.dropout(SCREAMING_SNAKE_CASE_ ) A__ : Tuple = self.classifier(SCREAMING_SNAKE_CASE_ ) return logits, pooled_output @add_start_docstrings( 'Bert Model (with early exiting - DeeBERT) with a classifier on top,\n also takes care of multi-layer training. ' , a__ , ) class __SCREAMING_SNAKE_CASE ( a__ ): def __init__( self : Union[str, Any] , snake_case : Optional[Any] ): '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE_ ) A__ : str = config.num_labels A__ : Dict = config.num_hidden_layers A__ : Optional[Any] = DeeBertModel(SCREAMING_SNAKE_CASE_ ) A__ : Dict = nn.Dropout(config.hidden_dropout_prob ) A__ : Optional[int] = nn.Linear(config.hidden_size , self.config.num_labels ) self.init_weights() @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE_ ) def _UpperCamelCase ( self : List[str] , snake_case : Dict=None , snake_case : Tuple=None , snake_case : List[str]=None , snake_case : List[str]=None , snake_case : List[Any]=None , snake_case : Optional[int]=None , snake_case : Optional[Any]=None , snake_case : Tuple=-1 , snake_case : Tuple=False , ): '''simple docstring''' A__ : str = self.num_layers try: A__ : Tuple = self.bert( 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_ , ) # sequence_output, pooled_output, (hidden_states), (attentions), highway exits A__ : Optional[Any] = outputs[1] A__ : Union[str, Any] = self.dropout(SCREAMING_SNAKE_CASE_ ) A__ : int = self.classifier(SCREAMING_SNAKE_CASE_ ) A__ : Dict = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: A__ : Optional[int] = e.message A__ : List[Any] = e.exit_layer A__ : Optional[int] = outputs[0] if not self.training: A__ : List[Any] = entropy(SCREAMING_SNAKE_CASE_ ) A__ : Any = [] A__ : Any = [] if labels is not None: if self.num_labels == 1: # We are doing regression A__ : str = MSELoss() A__ : int = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: A__ : List[Any] = CrossEntropyLoss() A__ : Optional[Any] = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits A__ : List[Any] = [] for highway_exit in outputs[-1]: A__ : Tuple = 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 A__ : Optional[Any] = MSELoss() A__ : Optional[int] = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: A__ : Tuple = CrossEntropyLoss() A__ : Tuple = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(SCREAMING_SNAKE_CASE_ ) if train_highway: A__ : Tuple = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: A__ : Optional[int] = (loss,) + outputs if not self.training: A__ : Optional[int] = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: A__ : str = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), (highway_exits)
365
"""simple docstring""" import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class __SCREAMING_SNAKE_CASE : def __init__( self : List[str] , snake_case : Tuple , snake_case : List[str]=2 , snake_case : List[str]=8 , snake_case : List[Any]=True , snake_case : Optional[Any]=True , snake_case : List[Any]=True , snake_case : Dict=True , snake_case : Tuple=99 , snake_case : Dict=16 , snake_case : Dict=5 , snake_case : int=2 , snake_case : Any=36 , snake_case : str="gelu" , snake_case : Dict=0.0 , snake_case : List[Any]=0.0 , snake_case : int=512 , snake_case : List[Any]=16 , snake_case : Tuple=2 , snake_case : Any=0.02 , snake_case : Optional[Any]=3 , snake_case : List[Any]=4 , snake_case : str=None , ): '''simple docstring''' A__ : Union[str, Any] = parent A__ : Optional[Any] = batch_size A__ : Dict = seq_length A__ : str = is_training A__ : Tuple = use_input_mask A__ : Dict = use_token_type_ids A__ : Dict = use_labels A__ : int = vocab_size A__ : List[str] = hidden_size A__ : Union[str, Any] = num_hidden_layers A__ : int = num_attention_heads A__ : List[str] = intermediate_size A__ : int = hidden_act A__ : str = hidden_dropout_prob A__ : Tuple = attention_probs_dropout_prob A__ : Any = max_position_embeddings A__ : Optional[int] = type_vocab_size A__ : int = type_sequence_label_size A__ : Optional[Any] = initializer_range A__ : int = num_labels A__ : Optional[int] = num_choices A__ : Optional[int] = scope def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Any = None if self.use_input_mask: A__ : Any = random_attention_mask([self.batch_size, self.seq_length] ) A__ : Optional[int] = None if self.use_token_type_ids: A__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A__ : Dict = None A__ : List[str] = None A__ : Union[str, Any] = None if self.use_labels: A__ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : Any = ids_tensor([self.batch_size] , self.num_choices ) A__ : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case , initializer_range=self.initializer_range , ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Any = self.get_config() A__ : List[str] = 300 return config def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) : Tuple = self.prepare_config_and_inputs() A__ : List[str] = True A__ : List[str] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) A__ : int = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def _UpperCamelCase ( self : Any , snake_case : Any , snake_case : Tuple , snake_case : Any , snake_case : Optional[int] , snake_case : Optional[int] , snake_case : Optional[int] , snake_case : Dict ): '''simple docstring''' A__ : List[str] = MraModel(config=snake_case ) model.to(snake_case ) model.eval() A__ : Dict = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case ) A__ : List[str] = model(snake_case , token_type_ids=snake_case ) A__ : Union[str, Any] = model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : Optional[Any] , snake_case : List[Any] , snake_case : Any , snake_case : Optional[Any] , snake_case : Union[str, Any] , snake_case : Tuple , snake_case : Dict , snake_case : str , snake_case : Dict , snake_case : str , ): '''simple docstring''' A__ : Dict = True A__ : Optional[Any] = MraModel(snake_case ) model.to(snake_case ) model.eval() A__ : Union[str, Any] = model( snake_case , attention_mask=snake_case , token_type_ids=snake_case , encoder_hidden_states=snake_case , encoder_attention_mask=snake_case , ) A__ : str = model( snake_case , attention_mask=snake_case , token_type_ids=snake_case , encoder_hidden_states=snake_case , ) A__ : Optional[int] = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : int , snake_case : Optional[Any] , snake_case : Optional[int] , snake_case : int , snake_case : str , snake_case : Union[str, Any] , snake_case : Dict , snake_case : List[str] ): '''simple docstring''' A__ : Union[str, Any] = MraForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() A__ : List[Any] = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Dict , snake_case : Dict , snake_case : Dict , snake_case : List[str] , snake_case : List[str] , snake_case : Tuple , snake_case : Union[str, Any] ): '''simple docstring''' A__ : Dict = MraForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() A__ : str = model( 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 _UpperCamelCase ( self : Tuple , snake_case : List[Any] , snake_case : Optional[Any] , snake_case : Optional[Any] , snake_case : List[str] , snake_case : Optional[int] , snake_case : List[str] , snake_case : Union[str, Any] ): '''simple docstring''' A__ : str = self.num_labels A__ : Optional[Any] = MraForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : str = model(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 _UpperCamelCase ( self : Union[str, Any] , snake_case : Dict , snake_case : str , snake_case : List[Any] , snake_case : Any , snake_case : Dict , snake_case : Tuple , snake_case : Optional[Any] ): '''simple docstring''' A__ : str = self.num_labels A__ : Union[str, Any] = MraForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() A__ : str = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self : Tuple , snake_case : Optional[Any] , snake_case : Optional[int] , snake_case : int , snake_case : Optional[Any] , snake_case : List[str] , snake_case : Dict , snake_case : Optional[Any] ): '''simple docstring''' A__ : List[str] = self.num_choices A__ : str = MraForMultipleChoice(config=snake_case ) model.to(snake_case ) model.eval() A__ : int = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : str = model( 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_choices) ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : List[str] = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) : Dict = config_and_inputs A__ : Optional[int] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( UpperCamelCase , unittest.TestCase ): snake_case_ = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = () def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Optional[Any] = MraModelTester(self ) A__ : List[str] = ConfigTester(self , config_class=snake_case , hidden_size=37 ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A__ : List[str] = type self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case ) @slow def _UpperCamelCase ( self : Any ): '''simple docstring''' for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ : str = MraModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @unittest.skip(reason="""MRA does not output attentions""" ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' return @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : str = MraModel.from_pretrained("""uw-madison/mra-base-512-4""" ) A__ : Any = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): A__ : List[Any] = model(snake_case )[0] A__ : List[Any] = torch.Size((1, 256, 768) ) self.assertEqual(output.shape , snake_case ) A__ : int = torch.tensor( [[[-0.0140, 0.0830, -0.0381], [0.1546, 0.1402, 0.0220], [0.1162, 0.0851, 0.0165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) ) @slow def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : Union[str, Any] = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-512-4""" ) A__ : Tuple = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): A__ : List[Any] = model(snake_case )[0] A__ : Dict = 5_0265 A__ : List[str] = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape , snake_case ) A__ : List[Any] = torch.tensor( [[[9.2595, -3.6038, 11.8819], [9.3869, -3.2693, 11.0956], [11.8524, -3.4938, 13.1210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) ) @slow def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : Any = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-4096-8-d3""" ) A__ : List[Any] = torch.arange(4096 ).unsqueeze(0 ) with torch.no_grad(): A__ : List[Any] = model(snake_case )[0] A__ : Union[str, Any] = 5_0265 A__ : Optional[Any] = torch.Size((1, 4096, vocab_size) ) self.assertEqual(output.shape , snake_case ) A__ : Optional[int] = torch.tensor( [[[5.4789, -2.3564, 7.5064], [7.9067, -1.3369, 9.9668], [9.0712, -1.8106, 7.0380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) )
296
0
import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @property def _UpperCamelCase ( self : int ): '''simple docstring''' torch.manual_seed(0 ) A__ : List[Any] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") , up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") , ) return model def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : List[Any] = self.dummy_uncond_unet A__ : Optional[Any] = KarrasVeScheduler() A__ : List[str] = KarrasVePipeline(unet=snake_case , scheduler=snake_case ) pipe.to(snake_case ) pipe.set_progress_bar_config(disable=snake_case ) A__ : Union[str, Any] = torch.manual_seed(0 ) A__ : Any = pipe(num_inference_steps=2 , generator=snake_case , output_type="""numpy""" ).images A__ : Optional[Any] = torch.manual_seed(0 ) A__ : Dict = pipe(num_inference_steps=2 , generator=snake_case , output_type="""numpy""" , return_dict=snake_case )[0] A__ : List[str] = image[0, -3:, -3:, -1] A__ : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A__ : Union[str, Any] = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : int = """google/ncsnpp-celebahq-256""" A__ : List[Any] = UNetaDModel.from_pretrained(snake_case ) A__ : List[str] = KarrasVeScheduler() A__ : Optional[Any] = KarrasVePipeline(unet=snake_case , scheduler=snake_case ) pipe.to(snake_case ) pipe.set_progress_bar_config(disable=snake_case ) A__ : int = torch.manual_seed(0 ) A__ : Tuple = pipe(num_inference_steps=20 , generator=snake_case , output_type="""numpy""" ).images A__ : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) A__ : int = np.array([0.578, 0.5811, 0.5924, 0.5809, 0.587, 0.5886, 0.5861, 0.5802, 0.586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
366
"""simple docstring""" from sklearn.metrics import mean_squared_error import datasets A_ = '''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' A_ = '''\ Mean Squared Error(MSE) is the average of the square of difference between the predicted and actual values. ''' A_ = ''' Args: predictions: array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. references: array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. sample_weight: array-like of shape (n_samples,), default=None Sample weights. multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average" Defines aggregating of multiple output values. Array-like value defines weights used to average errors. "raw_values" : Returns a full set of errors in case of multioutput input. "uniform_average" : Errors of all outputs are averaged with uniform weight. squared : bool, default=True If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value. Returns: mse : mean squared error. Examples: >>> mse_metric = datasets.load_metric("mse") >>> predictions = [2.5, 0.0, 2, 8] >>> references = [3, -0.5, 2, 7] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {\'mse\': 0.375} >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False) >>> print(rmse_result) {\'mse\': 0.6123724356957945} If you\'re using multi-dimensional lists, then set the config as follows : >>> mse_metric = datasets.load_metric("mse", "multilist") >>> predictions = [[0.5, 1], [-1, 1], [7, -6]] >>> references = [[0, 2], [-1, 2], [8, -5]] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {\'mse\': 0.7083333333333334} >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\') >>> print(results) # doctest: +NORMALIZE_WHITESPACE {\'mse\': array([0.41666667, 1. ])} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE ( datasets.Metric ): def _UpperCamelCase ( self : Dict ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html""" ] , ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value("""float""" ) ), "references": datasets.Sequence(datasets.Value("""float""" ) ), } else: return { "predictions": datasets.Value("""float""" ), "references": datasets.Value("""float""" ), } def _UpperCamelCase ( self : List[str] , snake_case : Dict , snake_case : List[Any] , snake_case : List[str]=None , snake_case : List[Any]="uniform_average" , snake_case : int=True ): '''simple docstring''' A__ : Optional[int] = mean_squared_error( snake_case , snake_case , sample_weight=snake_case , multioutput=snake_case , squared=snake_case ) return {"mse": mse}
296
0
"""simple docstring""" import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: A_ = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : int , snake_case : List[Any] , snake_case : int=7 , snake_case : Any=3 , snake_case : Optional[int]=18 , snake_case : Optional[Any]=30 , snake_case : Optional[int]=400 , snake_case : List[str]=None , snake_case : Dict=True , snake_case : str=True , snake_case : Dict=None , ): '''simple docstring''' A__ : Optional[Any] = size if size is not None else {'''height''': 20, '''width''': 20} A__ : List[Any] = parent A__ : Dict = batch_size A__ : Any = num_channels A__ : Dict = image_size A__ : Union[str, Any] = min_resolution A__ : Tuple = max_resolution A__ : Any = size A__ : Optional[int] = do_normalize A__ : Tuple = do_convert_rgb A__ : List[str] = [512, 1024, 2048, 4096] A__ : str = patch_size if patch_size is not None else {'''height''': 16, '''width''': 16} def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : Union[str, Any] = '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg''' A__ : Optional[Any] = Image.open(requests.get(__lowercase , stream=__lowercase ).raw ).convert("""RGB""" ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( UpperCAmelCase_ , unittest.TestCase ): snake_case_ = PixaStructImageProcessor if is_vision_available() else None def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : Union[str, Any] = PixaStructImageProcessingTester(self ) @property def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : Tuple = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowercase , """do_normalize""" ) ) self.assertTrue(hasattr(__lowercase , """do_convert_rgb""" ) ) def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : Union[str, Any] = self.image_processor_tester.prepare_dummy_image() A__ : Any = self.image_processing_class(**self.image_processor_dict ) A__ : int = 2048 A__ : Tuple = image_processor(__lowercase , return_tensors="""pt""" , max_patches=__lowercase ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images A__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowercase ) for image in image_inputs: self.assertIsInstance(__lowercase , Image.Image ) # Test not batched input A__ : Optional[int] = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input A__ : Union[str, Any] = image_processor( image_inputs[0] , return_tensors="""pt""" , max_patches=__lowercase ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched A__ : Any = image_processor( __lowercase , return_tensors="""pt""" , max_patches=__lowercase ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PIL images A__ : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowercase ) for image in image_inputs: self.assertIsInstance(__lowercase , Image.Image ) # Test not batched input A__ : Any = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 A__ : str = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(__lowercase ): A__ : Tuple = image_processor( image_inputs[0] , return_tensors="""pt""" , max_patches=__lowercase ).flattened_patches A__ : int = '''Hello''' A__ : str = image_processor( image_inputs[0] , return_tensors="""pt""" , max_patches=__lowercase , header_text=__lowercase ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched A__ : List[Any] = image_processor( __lowercase , return_tensors="""pt""" , max_patches=__lowercase , header_text=__lowercase ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A__ : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowercase , numpify=__lowercase ) for image in image_inputs: self.assertIsInstance(__lowercase , np.ndarray ) A__ : Optional[Any] = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input A__ : Dict = image_processor( image_inputs[0] , return_tensors="""pt""" , max_patches=__lowercase ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched A__ : str = image_processor( __lowercase , return_tensors="""pt""" , max_patches=__lowercase ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A__ : Any = 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 A__ : Union[str, Any] = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input A__ : Tuple = image_processor( image_inputs[0] , return_tensors="""pt""" , max_patches=__lowercase ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched A__ : Optional[Any] = image_processor( __lowercase , return_tensors="""pt""" , max_patches=__lowercase ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( UpperCAmelCase_ , unittest.TestCase ): snake_case_ = PixaStructImageProcessor if is_vision_available() else None def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : List[Any] = PixaStructImageProcessingTester(self , num_channels=4 ) A__ : int = 3 @property def _UpperCamelCase ( self : Any ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowercase , """do_normalize""" ) ) self.assertTrue(hasattr(__lowercase , """do_convert_rgb""" ) ) def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images A__ : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowercase ) for image in image_inputs: self.assertIsInstance(__lowercase , Image.Image ) # Test not batched input A__ : Union[str, Any] = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input A__ : int = image_processor( image_inputs[0] , return_tensors="""pt""" , max_patches=__lowercase ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched A__ : Any = image_processor( __lowercase , return_tensors="""pt""" , max_patches=__lowercase ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
367
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging A_ = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): def __init__( self : Optional[int] , snake_case : List[str]=None , **snake_case : Any ): '''simple docstring''' warnings.warn( """`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` """ """instead.""" , snake_case , ) super().__init__(args=snake_case , **snake_case )
296
0
import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ ): @register_to_config def __init__( self : int , snake_case : int = 128 , snake_case : int = 256 , snake_case : float = 2000.0 , snake_case : int = 768 , snake_case : int = 12 , snake_case : int = 12 , snake_case : int = 64 , snake_case : int = 2048 , snake_case : float = 0.1 , ): '''simple docstring''' super().__init__() A__ : str = nn.Sequential( nn.Linear(__a , d_model * 4 , bias=__a ) , nn.SiLU() , nn.Linear(d_model * 4 , d_model * 4 , bias=__a ) , nn.SiLU() , ) A__ : Dict = nn.Embedding(__a , __a ) A__ : Union[str, Any] = False A__ : List[Any] = nn.Linear(__a , __a , bias=__a ) A__ : Optional[Any] = nn.Dropout(p=__a ) A__ : List[str] = nn.ModuleList() for lyr_num in range(__a ): # FiLM conditional T5 decoder A__ : int = DecoderLayer(d_model=__a , d_kv=__a , num_heads=__a , d_ff=__a , dropout_rate=__a ) self.decoders.append(__a ) A__ : int = TaLayerNorm(__a ) A__ : List[str] = nn.Dropout(p=__a ) A__ : Optional[int] = nn.Linear(__a , __a , bias=__a ) def _UpperCamelCase ( self : List[str] , snake_case : str , snake_case : List[str] ): '''simple docstring''' A__ : List[str] = torch.mul(query_input.unsqueeze(-1 ) , key_input.unsqueeze(-2 ) ) return mask.unsqueeze(-3 ) def _UpperCamelCase ( self : Dict , snake_case : Union[str, Any] , snake_case : Optional[int] , snake_case : Any ): '''simple docstring''' A__ , A__ , A__ : Any = decoder_input_tokens.shape assert decoder_noise_time.shape == (batch,) # decoder_noise_time is in [0, 1), so rescale to expected timing range. A__ : Union[str, Any] = get_timestep_embedding( decoder_noise_time * self.config.max_decoder_noise_time , embedding_dim=self.config.d_model , max_period=self.config.max_decoder_noise_time , ).to(dtype=self.dtype ) A__ : Dict = self.conditioning_emb(__a ).unsqueeze(1 ) assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4) A__ : List[Any] = decoder_input_tokens.shape[1] # If we want to use relative positions for audio context, we can just offset # this sequence by the length of encodings_and_masks. A__ : Optional[int] = torch.broadcast_to( torch.arange(__a , device=decoder_input_tokens.device ) , (batch, seq_length) , ) A__ : Dict = self.position_encoding(__a ) A__ : Union[str, Any] = self.continuous_inputs_projection(__a ) inputs += position_encodings A__ : Dict = self.dropout(__a ) # decoder: No padding present. A__ : Union[str, Any] = torch.ones( decoder_input_tokens.shape[:2] , device=decoder_input_tokens.device , dtype=inputs.dtype ) # Translate encoding masks to encoder-decoder masks. A__ : str = [(x, self.encoder_decoder_mask(__a , __a )) for x, y in encodings_and_masks] # cross attend style: concat encodings A__ : int = torch.cat([x[0] for x in encodings_and_encdec_masks] , dim=1 ) A__ : Optional[int] = torch.cat([x[1] for x in encodings_and_encdec_masks] , dim=-1 ) for lyr in self.decoders: A__ : Optional[Any] = lyr( __a , conditioning_emb=__a , encoder_hidden_states=__a , encoder_attention_mask=__a , )[0] A__ : Optional[Any] = self.decoder_norm(__a ) A__ : Any = self.post_dropout(__a ) A__ : str = self.spec_out(__a ) return spec_out class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Optional[Any] , snake_case : Union[str, Any] , snake_case : int , snake_case : Any , snake_case : List[Any] , snake_case : Optional[int] , snake_case : Dict=1e-6 ): '''simple docstring''' super().__init__() A__ : Tuple = nn.ModuleList() # cond self attention: layer 0 self.layer.append( TaLayerSelfAttentionCond(d_model=__a , d_kv=__a , num_heads=__a , dropout_rate=__a ) ) # cross attention: layer 1 self.layer.append( TaLayerCrossAttention( d_model=__a , d_kv=__a , num_heads=__a , dropout_rate=__a , layer_norm_epsilon=__a , ) ) # Film Cond MLP + dropout: last layer self.layer.append( TaLayerFFCond(d_model=__a , d_ff=__a , dropout_rate=__a , layer_norm_epsilon=__a ) ) def _UpperCamelCase ( self : int , snake_case : Dict , snake_case : Optional[int]=None , snake_case : Union[str, Any]=None , snake_case : List[str]=None , snake_case : Dict=None , snake_case : Optional[Any]=None , ): '''simple docstring''' A__ : Optional[Any] = self.layer[0]( __a , conditioning_emb=__a , attention_mask=__a , ) if encoder_hidden_states is not None: A__ : str = torch.where(encoder_attention_mask > 0 , 0 , -1e10 ).to( encoder_hidden_states.dtype ) A__ : Union[str, Any] = self.layer[1]( __a , key_value_states=__a , attention_mask=__a , ) # Apply Film Conditional Feed Forward layer A__ : Optional[Any] = self.layer[-1](__a , __a ) return (hidden_states,) class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : int , snake_case : List[str] , snake_case : Optional[int] , snake_case : int , snake_case : List[Any] ): '''simple docstring''' super().__init__() A__ : int = TaLayerNorm(__a ) A__ : str = TaFiLMLayer(in_features=d_model * 4 , out_features=__a ) A__ : List[Any] = Attention(query_dim=__a , heads=__a , dim_head=__a , out_bias=__a , scale_qk=__a ) A__ : Optional[Any] = nn.Dropout(__a ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Optional[Any] , snake_case : Dict=None , snake_case : Optional[Any]=None , ): '''simple docstring''' A__ : Dict = self.layer_norm(__a ) if conditioning_emb is not None: A__ : Tuple = self.FiLMLayer(__a , __a ) # Self-attention block A__ : Optional[int] = self.attention(__a ) A__ : List[str] = hidden_states + self.dropout(__a ) return hidden_states class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Dict , snake_case : int , snake_case : Union[str, Any] , snake_case : int , snake_case : int , snake_case : List[Any] ): '''simple docstring''' super().__init__() A__ : str = Attention(query_dim=__a , heads=__a , dim_head=__a , out_bias=__a , scale_qk=__a ) A__ : List[Any] = TaLayerNorm(__a , eps=__a ) A__ : str = nn.Dropout(__a ) def _UpperCamelCase ( self : Optional[int] , snake_case : str , snake_case : List[str]=None , snake_case : Tuple=None , ): '''simple docstring''' A__ : Tuple = self.layer_norm(__a ) A__ : Any = self.attention( __a , encoder_hidden_states=__a , attention_mask=attention_mask.squeeze(1 ) , ) A__ : Optional[int] = hidden_states + self.dropout(__a ) return layer_output class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : int , snake_case : Union[str, Any] , snake_case : Union[str, Any] , snake_case : int , snake_case : Optional[int] ): '''simple docstring''' super().__init__() A__ : str = TaDenseGatedActDense(d_model=__a , d_ff=__a , dropout_rate=__a ) A__ : Any = TaFiLMLayer(in_features=d_model * 4 , out_features=__a ) A__ : List[Any] = TaLayerNorm(__a , eps=__a ) A__ : Optional[int] = nn.Dropout(__a ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Any , snake_case : List[str]=None ): '''simple docstring''' A__ : int = self.layer_norm(__a ) if conditioning_emb is not None: A__ : Optional[Any] = self.film(__a , __a ) A__ : Tuple = self.DenseReluDense(__a ) A__ : Tuple = hidden_states + self.dropout(__a ) return hidden_states class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Dict , snake_case : Union[str, Any] , snake_case : List[Any] , snake_case : int ): '''simple docstring''' super().__init__() A__ : Dict = nn.Linear(__a , __a , bias=__a ) A__ : Optional[int] = nn.Linear(__a , __a , bias=__a ) A__ : Optional[int] = nn.Linear(__a , __a , bias=__a ) A__ : List[Any] = nn.Dropout(__a ) A__ : Tuple = NewGELUActivation() def _UpperCamelCase ( self : Optional[Any] , snake_case : int ): '''simple docstring''' A__ : List[Any] = self.act(self.wi_a(__a ) ) A__ : str = self.wi_a(__a ) A__ : Dict = hidden_gelu * hidden_linear A__ : Optional[int] = self.dropout(__a ) A__ : Optional[int] = self.wo(__a ) return hidden_states class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Optional[Any] , snake_case : str , snake_case : List[Any]=1e-6 ): '''simple docstring''' super().__init__() A__ : Dict = nn.Parameter(torch.ones(__a ) ) A__ : Union[str, Any] = eps def _UpperCamelCase ( self : Union[str, Any] , snake_case : Dict ): '''simple docstring''' A__ : Dict = hidden_states.to(torch.floataa ).pow(2 ).mean(-1 , keepdim=__a ) A__ : List[Any] = hidden_states * torch.rsqrt(variance + self.variance_epsilon ) # convert into half-precision if necessary if self.weight.dtype in [torch.floataa, torch.bfloataa]: A__ : int = hidden_states.to(self.weight.dtype ) return self.weight * hidden_states class __SCREAMING_SNAKE_CASE ( nn.Module ): def _UpperCamelCase ( self : Optional[int] , snake_case : torch.Tensor ): '''simple docstring''' return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi ) * (input + 0.044715 * torch.pow(__a , 3.0 )) )) class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : int , snake_case : Union[str, Any] , snake_case : List[Any] ): '''simple docstring''' super().__init__() A__ : Union[str, Any] = nn.Linear(__a , out_features * 2 , bias=__a ) def _UpperCamelCase ( self : Dict , snake_case : Union[str, Any] , snake_case : Any ): '''simple docstring''' A__ : Optional[Any] = self.scale_bias(__a ) A__ , A__ : Union[str, Any] = torch.chunk(__a , 2 , -1 ) A__ : Tuple = x * (1 + scale) + shift return x
368
"""simple docstring""" import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch A_ = random.Random() def _lowerCAmelCase ( UpperCAmelCase__ : Dict, UpperCAmelCase__ : Tuple=1.0, UpperCAmelCase__ : Optional[int]=None, UpperCAmelCase__ : str=None ) ->Union[str, Any]: if rng is None: A__ : Optional[int] = global_rng A__ : Optional[Any] = [] 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 __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : Union[str, Any] , snake_case : str , snake_case : List[str]=7 , snake_case : str=400 , snake_case : Optional[Any]=2000 , snake_case : Union[str, Any]=10 , snake_case : str=160 , snake_case : List[str]=8 , snake_case : List[Any]=0.0 , snake_case : Optional[Any]=4000 , snake_case : Any=False , snake_case : int=True , ): '''simple docstring''' A__ : Any = parent A__ : str = batch_size A__ : List[str] = min_seq_length A__ : Dict = max_seq_length A__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) A__ : Dict = padding_value A__ : Optional[Any] = sampling_rate A__ : Any = return_attention_mask A__ : Optional[int] = do_normalize A__ : Tuple = feature_size A__ : Optional[Any] = chunk_length A__ : Union[str, Any] = hop_length def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _UpperCamelCase ( self : Union[str, Any] , snake_case : Dict=False , snake_case : Optional[Any]=False ): '''simple docstring''' def _flatten(snake_case : Dict ): return list(itertools.chain(*snake_case ) ) if equal_length: A__ : Dict = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size A__ : Optional[int] = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: A__ : List[str] = [np.asarray(snake_case ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __SCREAMING_SNAKE_CASE ( UpperCamelCase , unittest.TestCase ): snake_case_ = WhisperFeatureExtractor if is_speech_available() else None def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : str = WhisperFeatureExtractionTester(self ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Any = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: A__ : List[Any] = feat_extract_first.save_pretrained(snake_case )[0] check_json_file_has_correct_format(snake_case ) A__ : Union[str, Any] = self.feature_extraction_class.from_pretrained(snake_case ) A__ : str = feat_extract_first.to_dict() A__ : Union[str, Any] = feat_extract_second.to_dict() A__ : List[Any] = feat_extract_first.mel_filters A__ : Optional[Any] = feat_extract_second.mel_filters self.assertTrue(np.allclose(snake_case , snake_case ) ) self.assertEqual(snake_case , snake_case ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Any = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: A__ : Any = os.path.join(snake_case , """feat_extract.json""" ) feat_extract_first.to_json_file(snake_case ) A__ : int = self.feature_extraction_class.from_json_file(snake_case ) A__ : Dict = feat_extract_first.to_dict() A__ : str = feat_extract_second.to_dict() A__ : str = feat_extract_first.mel_filters A__ : Dict = feat_extract_second.mel_filters self.assertTrue(np.allclose(snake_case , snake_case ) ) self.assertEqual(snake_case , snake_case ) def _UpperCamelCase ( self : Any ): '''simple docstring''' A__ : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 A__ : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] A__ : Union[str, Any] = [np.asarray(snake_case ) for speech_input in speech_inputs] # Test feature size A__ : Dict = feature_extractor(snake_case , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input A__ : str = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features A__ : Optional[int] = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(snake_case , snake_case , atol=1e-3 ) ) # Test batched A__ : List[str] = feature_extractor(snake_case , return_tensors="""np""" ).input_features A__ : List[str] = feature_extractor(snake_case , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(snake_case , snake_case ): self.assertTrue(np.allclose(snake_case , snake_case , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. A__ : Tuple = [floats_list((1, x) )[0] for x in (800, 800, 800)] A__ : str = np.asarray(snake_case ) A__ : List[str] = feature_extractor(snake_case , return_tensors="""np""" ).input_features A__ : Optional[int] = feature_extractor(snake_case , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(snake_case , snake_case ): self.assertTrue(np.allclose(snake_case , snake_case , atol=1e-3 ) ) # Test truncation required A__ : Optional[Any] = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] A__ : Union[str, Any] = [np.asarray(snake_case ) for speech_input in speech_inputs] A__ : Union[str, Any] = [x[: feature_extractor.n_samples] for x in speech_inputs] A__ : str = [np.asarray(snake_case ) for speech_input in speech_inputs_truncated] A__ : Optional[int] = feature_extractor(snake_case , return_tensors="""np""" ).input_features A__ : str = feature_extractor(snake_case , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(snake_case , snake_case ): self.assertTrue(np.allclose(snake_case , snake_case , atol=1e-3 ) ) def _UpperCamelCase ( self : str ): '''simple docstring''' import torch A__ : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A__ : List[str] = np.random.rand(100 , 32 ).astype(np.floataa ) A__ : Tuple = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: A__ : Optional[Any] = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) A__ : Optional[int] = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Optional[int] ): '''simple docstring''' A__ : int = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech A__ : Union[str, Any] = ds.sort("""id""" ).select(range(snake_case ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : str = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on A__ : Optional[Any] = self._load_datasamples(1 ) A__ : Union[str, Any] = WhisperFeatureExtractor() A__ : List[str] = feature_extractor(snake_case , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 80, 3000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , snake_case , atol=1e-4 ) ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A__ : Union[str, Any] = self._load_datasamples(1 )[0] A__ : Any = ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535 # Rescale to [0, 65535] to show issue A__ : str = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=snake_case )[0] self.assertTrue(np.all(np.mean(snake_case ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(snake_case ) - 1 ) < 1e-3 ) )
296
0
"""simple docstring""" import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : str = 'hf-internal-testing/tiny-random-t5' A__ : List[Any] = AutoTokenizer.from_pretrained(_UpperCAmelCase ) A__ : Dict = AutoModelForSeqaSeqLM.from_pretrained(_UpperCAmelCase ) A__ : Any = tokenizer("""This is me""" , return_tensors="""pt""" ) A__ : int = model.to_bettertransformer() self.assertTrue(any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) A__ : str = model.generate(**_UpperCAmelCase ) A__ : Optional[Any] = model.reverse_bettertransformer() self.assertFalse(any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_UpperCAmelCase ) A__ : Tuple = AutoModelForSeqaSeqLM.from_pretrained(_UpperCAmelCase ) self.assertFalse( any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) A__ : Optional[int] = model_reloaded.generate(**_UpperCAmelCase ) self.assertTrue(torch.allclose(_UpperCAmelCase , _UpperCAmelCase ) ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : str = 'hf-internal-testing/tiny-random-t5' A__ : int = AutoModelForSeqaSeqLM.from_pretrained(_UpperCAmelCase ) A__ : Dict = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(_UpperCAmelCase ): model.save_pretrained(_UpperCAmelCase ) A__ : str = model.reverse_bettertransformer() model.save_pretrained(_UpperCAmelCase )
369
"""simple docstring""" import numpy as np class __SCREAMING_SNAKE_CASE : def __init__( self : List[str] ): '''simple docstring''' A__ : Optional[int] = (0, 0) A__ : Dict = None A__ : int = 0 A__ : str = 0 A__ : Optional[Any] = 0 def __eq__( self : str , snake_case : Optional[int] ): '''simple docstring''' return self.position == cell.position def _UpperCamelCase ( self : List[str] ): '''simple docstring''' print(self.position ) class __SCREAMING_SNAKE_CASE : def __init__( self : int , snake_case : Any=(5, 5) ): '''simple docstring''' A__ : Optional[int] = np.zeros(snake_case ) A__ : List[Any] = world_size[0] A__ : Dict = world_size[1] def _UpperCamelCase ( self : Any ): '''simple docstring''' print(self.w ) def _UpperCamelCase ( self : Optional[int] , snake_case : List[Any] ): '''simple docstring''' A__ : int = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] A__ : int = cell.position[0] A__ : str = cell.position[1] A__ : Any = [] for n in neughbour_cord: A__ : List[Any] = current_x + n[0] A__ : Tuple = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: A__ : List[Any] = Cell() A__ : str = (x, y) A__ : Optional[Any] = cell neighbours.append(snake_case ) return neighbours def _lowerCAmelCase ( UpperCAmelCase__ : List[str], UpperCAmelCase__ : Optional[Any], UpperCAmelCase__ : Dict ) ->Dict: A__ : Union[str, Any] = [] A__ : Optional[int] = [] _open.append(UpperCAmelCase__ ) while _open: A__ : List[Any] = np.argmin([n.f for n in _open] ) A__ : Union[str, Any] = _open[min_f] _closed.append(_open.pop(UpperCAmelCase__ ) ) if current == goal: break for n in world.get_neigbours(UpperCAmelCase__ ): for c in _closed: if c == n: continue A__ : Dict = current.g + 1 A__ , A__ : int = n.position A__ , A__ : Optional[int] = goal.position A__ : Union[str, Any] = (ya - ya) ** 2 + (xa - xa) ** 2 A__ : Optional[int] = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(UpperCAmelCase__ ) A__ : List[str] = [] while current.parent is not None: path.append(current.position ) A__ : Union[str, Any] = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": A_ = Gridworld() # Start position and goal A_ = Cell() A_ = (0, 0) A_ = Cell() A_ = (4, 4) print(F'path from {start.position} to {goal.position}') A_ = astar(world, start, goal) # Just for visual reasons. for i in s: A_ = 1 print(world.w)
296
0
"""simple docstring""" 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 A_ = logging.getLogger(__name__) class __SCREAMING_SNAKE_CASE ( __snake_case ): snake_case_ = """token-classification""" def __init__( self : int , snake_case : Tuple ): '''simple docstring''' if type(UpperCamelCase__ ) == dict: A__ : Optional[Any] = Namespace(**UpperCamelCase__ ) A__ : Any = import_module("""tasks""" ) try: A__ : Optional[int] = getattr(UpperCamelCase__ , hparams.task_type ) A__ : 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__()}' ) A__ : List[str] = self.token_classification_task.get_labels(hparams.labels ) A__ : Any = CrossEntropyLoss().ignore_index super().__init__(UpperCamelCase__ , len(self.labels ) , self.mode ) def _UpperCamelCase ( self : Union[str, Any] , **snake_case : Optional[int] ): '''simple docstring''' return self.model(**UpperCamelCase__ ) def _UpperCamelCase ( self : Union[str, Any] , snake_case : Optional[int] , snake_case : List[str] ): '''simple docstring''' A__ : Optional[int] = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type != "distilbert": A__ : int = ( batch[2] if self.config.model_type in ["bert", "xlnet"] else None ) # XLM and RoBERTa don"t use token_type_ids A__ : Any = self(**UpperCamelCase__ ) A__ : Dict = outputs[0] # tensorboard_logs = {"loss": loss, "rate": self.lr_scheduler.get_last_lr()[-1]} return {"loss": loss} def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : Optional[int] = self.hparams for mode in ["train", "dev", "test"]: A__ : Dict = self._feature_file(UpperCamelCase__ ) if os.path.exists(UpperCamelCase__ ) and not args.overwrite_cache: logger.info("""Loading features from cached file %s""" , UpperCamelCase__ ) A__ : List[str] = torch.load(UpperCamelCase__ ) else: logger.info("""Creating features from dataset file at %s""" , args.data_dir ) A__ : Any = self.token_classification_task.read_examples_from_file(args.data_dir , UpperCamelCase__ ) A__ : Any = 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 _UpperCamelCase ( self : Optional[int] , snake_case : int , snake_case : int , snake_case : bool = False ): '''simple docstring''' A__ : Dict = self._feature_file(UpperCamelCase__ ) logger.info("""Loading features from cached file %s""" , UpperCamelCase__ ) A__ : Tuple = torch.load(UpperCamelCase__ ) A__ : Optional[Any] = torch.tensor([f.input_ids for f in features] , dtype=torch.long ) A__ : int = torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) if features[0].token_type_ids is not None: A__ : int = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) else: A__ : str = torch.tensor([0 for f in features] , dtype=torch.long ) # HACK(we will not use this anymore soon) A__ : List[str] = torch.tensor([f.label_ids for f in features] , dtype=torch.long ) return DataLoader( TensorDataset(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) , batch_size=UpperCamelCase__ ) def _UpperCamelCase ( self : List[Any] , snake_case : List[str] , snake_case : Optional[int] ): '''simple docstring''' """Compute validation""" "" A__ : str = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type != "distilbert": A__ : Dict = ( batch[2] if self.config.model_type in ["bert", "xlnet"] else None ) # XLM and RoBERTa don"t use token_type_ids A__ : List[str] = self(**UpperCamelCase__ ) A__ : Any = outputs[:2] A__ : Union[str, Any] = logits.detach().cpu().numpy() A__ : Optional[Any] = inputs["labels"].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def _UpperCamelCase ( self : Optional[Any] , snake_case : int ): '''simple docstring''' A__ : Dict = torch.stack([x["""val_loss"""] for x in outputs] ).mean() A__ : Dict = np.concatenate([x["""pred"""] for x in outputs] , axis=0 ) A__ : List[Any] = np.argmax(UpperCamelCase__ , axis=2 ) A__ : List[str] = np.concatenate([x["""target"""] for x in outputs] , axis=0 ) A__ : Tuple = dict(enumerate(self.labels ) ) A__ : Union[str, Any] = [[] for _ in range(out_label_ids.shape[0] )] A__ : 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]] ) A__ : 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__ ), } A__ : str = dict(results.items() ) A__ : List[str] = results return ret, preds_list, out_label_list def _UpperCamelCase ( self : Tuple , snake_case : Optional[Any] ): '''simple docstring''' A__ : str = self._eval_end(UpperCamelCase__ ) A__ : Tuple = ret["log"] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def _UpperCamelCase ( self : Union[str, Any] , snake_case : List[Any] ): '''simple docstring''' A__ : List[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 A__ : List[Any] = 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 _UpperCamelCase ( snake_case : List[Any] , snake_case : Optional[int] ): '''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=128 , 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__": A_ = argparse.ArgumentParser() add_generic_args(parser, os.getcwd()) A_ = NERTransformer.add_model_specific_args(parser, os.getcwd()) A_ = parser.parse_args() A_ = NERTransformer(args) A_ = 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 A_ = sorted(glob.glob(os.path.join(args.output_dir, '''checkpoint-epoch=*.ckpt'''), recursive=True)) A_ = model.load_from_checkpoint(checkpoints[-1]) trainer.test(model)
370
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) def _lowerCAmelCase ( UpperCAmelCase__ : Union[str, Any], UpperCAmelCase__ : Tuple=False ) ->str: A__ : Optional[int] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'blocks.{i}.norm1.weight', f'deit.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((f'blocks.{i}.norm1.bias', f'deit.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append((f'blocks.{i}.attn.proj.weight', f'deit.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append((f'blocks.{i}.attn.proj.bias', f'deit.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((f'blocks.{i}.norm2.weight', f'deit.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((f'blocks.{i}.norm2.bias', f'deit.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append((f'blocks.{i}.mlp.fc1.weight', f'deit.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((f'blocks.{i}.mlp.fc1.bias', f'deit.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((f'blocks.{i}.mlp.fc2.weight', f'deit.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((f'blocks.{i}.mlp.fc2.bias', f'deit.encoder.layer.{i}.output.dense.bias') ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """deit.embeddings.cls_token"""), ("""dist_token""", """deit.embeddings.distillation_token"""), ("""patch_embed.proj.weight""", """deit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """deit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """deit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" A__ : Optional[int] = [(pair[0], pair[1][4:]) if pair[1].startswith("""deit""" ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ("""norm.weight""", """deit.layernorm.weight"""), ("""norm.bias""", """deit.layernorm.bias"""), ("""head.weight""", """cls_classifier.weight"""), ("""head.bias""", """cls_classifier.bias"""), ("""head_dist.weight""", """distillation_classifier.weight"""), ("""head_dist.bias""", """distillation_classifier.bias"""), ] ) return rename_keys def _lowerCAmelCase ( UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : Tuple, UpperCAmelCase__ : List[Any]=False ) ->str: for i in range(config.num_hidden_layers ): if base_model: A__ : Any = """""" else: A__ : Tuple = """deit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) A__ : Any = state_dict.pop(f'blocks.{i}.attn.qkv.weight' ) A__ : Tuple = state_dict.pop(f'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict A__ : List[Any] = in_proj_weight[ : config.hidden_size, : ] A__ : str = in_proj_bias[: config.hidden_size] A__ : Any = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] A__ : Dict = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] A__ : Optional[Any] = in_proj_weight[ -config.hidden_size :, : ] A__ : Any = in_proj_bias[-config.hidden_size :] def _lowerCAmelCase ( UpperCAmelCase__ : List[Any], UpperCAmelCase__ : List[Any], UpperCAmelCase__ : Union[str, Any] ) ->Any: A__ : int = dct.pop(UpperCAmelCase__ ) A__ : Tuple = val def _lowerCAmelCase ( ) ->List[Any]: A__ : Optional[int] = """http://images.cocodataset.org/val2017/000000039769.jpg""" A__ : int = Image.open(requests.get(UpperCAmelCase__, stream=UpperCAmelCase__ ).raw ) return im @torch.no_grad() def _lowerCAmelCase ( UpperCAmelCase__ : Dict, UpperCAmelCase__ : Any ) ->Tuple: A__ : List[Any] = DeiTConfig() # all deit models have fine-tuned heads A__ : Tuple = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size A__ : str = 1_0_0_0 A__ : List[str] = """huggingface/label-files""" A__ : Dict = """imagenet-1k-id2label.json""" A__ : List[str] = json.load(open(hf_hub_download(UpperCAmelCase__, UpperCAmelCase__, repo_type="""dataset""" ), """r""" ) ) A__ : Dict = {int(UpperCAmelCase__ ): v for k, v in idalabel.items()} A__ : Optional[int] = idalabel A__ : Dict = {v: k for k, v in idalabel.items()} A__ : List[str] = int(deit_name[-6:-4] ) A__ : str = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith("""tiny""" ): A__ : List[str] = 1_9_2 A__ : int = 7_6_8 A__ : List[Any] = 1_2 A__ : Dict = 3 elif deit_name[9:].startswith("""small""" ): A__ : List[Any] = 3_8_4 A__ : List[str] = 1_5_3_6 A__ : Any = 1_2 A__ : Union[str, Any] = 6 if deit_name[9:].startswith("""base""" ): pass elif deit_name[4:].startswith("""large""" ): A__ : int = 1_0_2_4 A__ : str = 4_0_9_6 A__ : Any = 2_4 A__ : int = 1_6 # load original model from timm A__ : Dict = timm.create_model(UpperCAmelCase__, pretrained=UpperCAmelCase__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys A__ : Tuple = timm_model.state_dict() A__ : str = create_rename_keys(UpperCAmelCase__, UpperCAmelCase__ ) for src, dest in rename_keys: rename_key(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) read_in_q_k_v(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) # load HuggingFace model A__ : str = DeiTForImageClassificationWithTeacher(UpperCAmelCase__ ).eval() model.load_state_dict(UpperCAmelCase__ ) # Check outputs on an image, prepared by DeiTImageProcessor A__ : int = int( (2_5_6 / 2_2_4) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 A__ : Any = DeiTImageProcessor(size=UpperCAmelCase__, crop_size=config.image_size ) A__ : Union[str, Any] = image_processor(images=prepare_img(), return_tensors="""pt""" ) A__ : Optional[Any] = encoding["""pixel_values"""] A__ : Union[str, Any] = model(UpperCAmelCase__ ) A__ : Union[str, Any] = timm_model(UpperCAmelCase__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(UpperCAmelCase__, outputs.logits, atol=1e-3 ) Path(UpperCAmelCase__ ).mkdir(exist_ok=UpperCAmelCase__ ) print(f'Saving model {deit_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(UpperCAmelCase__ ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(UpperCAmelCase__ ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--deit_name''', default='''vit_deit_base_distilled_patch16_224''', type=str, help='''Name of the DeiT 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.''' ) A_ = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
296
0
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { '''asapp/sew-tiny-100k''': '''https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json''', # See all SEW models at https://huggingface.co/models?filter=sew } class __SCREAMING_SNAKE_CASE ( lowerCamelCase_ ): snake_case_ = '''sew''' def __init__( self : List[str] , snake_case : Dict=32 , snake_case : Optional[Any]=768 , snake_case : int=12 , snake_case : Any=12 , snake_case : str=3072 , snake_case : Any=2 , snake_case : Dict="gelu" , snake_case : Union[str, Any]=0.1 , snake_case : Dict=0.1 , snake_case : Tuple=0.1 , snake_case : int=0.0 , snake_case : str=0.1 , snake_case : Optional[Any]=0.1 , snake_case : Optional[Any]=0.02 , snake_case : Dict=1e-5 , snake_case : Tuple="group" , snake_case : Optional[int]="gelu" , snake_case : Dict=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , snake_case : Optional[Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , snake_case : Any=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , snake_case : Dict=False , snake_case : List[Any]=128 , snake_case : Optional[Any]=16 , snake_case : Union[str, Any]=True , snake_case : List[str]=0.05 , snake_case : Optional[int]=10 , snake_case : List[Any]=2 , snake_case : str=0.0 , snake_case : List[Any]=10 , snake_case : Optional[int]=0 , snake_case : Dict="mean" , snake_case : List[str]=False , snake_case : str=False , snake_case : Dict=256 , snake_case : Optional[int]=0 , snake_case : str=1 , snake_case : Any=2 , **snake_case : List[str] , ): '''simple docstring''' super().__init__(**__snake_case , pad_token_id=__snake_case , bos_token_id=__snake_case , eos_token_id=__snake_case ) A__ : Union[str, Any] = hidden_size A__ : int = feat_extract_norm A__ : List[Any] = feat_extract_activation A__ : List[str] = list(__snake_case ) A__ : Tuple = list(__snake_case ) A__ : Dict = list(__snake_case ) A__ : Optional[int] = conv_bias A__ : str = num_conv_pos_embeddings A__ : Any = num_conv_pos_embedding_groups A__ : int = len(self.conv_dim ) A__ : Union[str, Any] = num_hidden_layers A__ : Union[str, Any] = intermediate_size A__ : Optional[int] = squeeze_factor A__ : List[Any] = hidden_act A__ : Optional[int] = num_attention_heads A__ : Optional[Any] = hidden_dropout A__ : List[Any] = attention_dropout A__ : Any = activation_dropout A__ : int = feat_proj_dropout A__ : Union[str, Any] = final_dropout A__ : Dict = layerdrop A__ : List[Any] = layer_norm_eps A__ : Union[str, Any] = initializer_range A__ : str = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect.""" """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,""" F'but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)' F'= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 A__ : List[Any] = apply_spec_augment A__ : Any = mask_time_prob A__ : Dict = mask_time_length A__ : Any = mask_time_min_masks A__ : Dict = mask_feature_prob A__ : Any = mask_feature_length A__ : Union[str, Any] = mask_feature_min_masks # ctc loss A__ : int = ctc_loss_reduction A__ : Dict = ctc_zero_infinity # sequence classification A__ : List[Any] = use_weighted_layer_sum A__ : List[Any] = classifier_proj_size @property def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
371
"""simple docstring""" from __future__ import annotations import time from collections.abc import Sequence from random import randint from matplotlib import pyplot as plt def _lowerCAmelCase ( UpperCAmelCase__ : Sequence[float], UpperCAmelCase__ : int, UpperCAmelCase__ : int ) ->tuple[int | None, int | None, float]: if not arr: return None, None, 0 if low == high: return low, high, arr[low] A__ : Optional[int] = (low + high) // 2 A__ , A__ , A__ : List[Any] = max_subarray(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) A__ , A__ , A__ : Union[str, Any] = max_subarray(UpperCAmelCase__, mid + 1, UpperCAmelCase__ ) A__ , A__ , A__ : Union[str, Any] = max_cross_sum(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum return cross_left, cross_right, cross_sum def _lowerCAmelCase ( UpperCAmelCase__ : Sequence[float], UpperCAmelCase__ : int, UpperCAmelCase__ : int, UpperCAmelCase__ : int ) ->tuple[int, int, float]: A__ , A__ : Dict = float("""-inf""" ), -1 A__ , A__ : Optional[Any] = float("""-inf""" ), -1 A__ : int | float = 0 for i in range(UpperCAmelCase__, low - 1, -1 ): summ += arr[i] if summ > left_sum: A__ : Optional[int] = summ A__ : Union[str, Any] = i A__ : Optional[Any] = 0 for i in range(mid + 1, high + 1 ): summ += arr[i] if summ > right_sum: A__ : int = summ A__ : Union[str, Any] = i return max_left, max_right, (left_sum + right_sum) def _lowerCAmelCase ( UpperCAmelCase__ : int ) ->float: A__ : Union[str, Any] = [randint(1, UpperCAmelCase__ ) for _ in range(UpperCAmelCase__ )] A__ : Any = time.time() max_subarray(UpperCAmelCase__, 0, input_size - 1 ) A__ : List[Any] = time.time() return end - start def _lowerCAmelCase ( ) ->None: A__ : List[Any] = [1_0, 1_0_0, 1_0_0_0, 1_0_0_0_0, 5_0_0_0_0, 1_0_0_0_0_0, 2_0_0_0_0_0, 3_0_0_0_0_0, 4_0_0_0_0_0, 5_0_0_0_0_0] A__ : Any = [time_max_subarray(UpperCAmelCase__ ) for input_size in input_sizes] print("""No of Inputs\t\tTime Taken""" ) for input_size, runtime in zip(UpperCAmelCase__, UpperCAmelCase__ ): print(UpperCAmelCase__, """\t\t""", UpperCAmelCase__ ) plt.plot(UpperCAmelCase__, UpperCAmelCase__ ) plt.xlabel("""Number of Inputs""" ) plt.ylabel("""Time taken in seconds""" ) plt.show() if __name__ == "__main__": from doctest import testmod testmod()
296
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ = { '''configuration_bigbird_pegasus''': [ '''BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BigBirdPegasusConfig''', '''BigBirdPegasusOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''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 A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
350
"""simple docstring""" from __future__ import annotations class __SCREAMING_SNAKE_CASE : def __init__( self : Dict , snake_case : int ): '''simple docstring''' A__ : List[Any] = order # a_{0} ... a_{k} A__ : List[Any] = [1.0] + [0.0] * order # b_{0} ... b_{k} A__ : str = [1.0] + [0.0] * order # x[n-1] ... x[n-k] A__ : Union[str, Any] = [0.0] * self.order # y[n-1] ... y[n-k] A__ : List[str] = [0.0] * self.order def _UpperCamelCase ( self : Optional[int] , snake_case : list[float] , snake_case : list[float] ): '''simple docstring''' if len(snake_case ) < self.order: A__ : Any = [1.0, *a_coeffs] if len(snake_case ) != self.order + 1: A__ : str = ( F'Expected a_coeffs to have {self.order + 1} elements ' F'for {self.order}-order filter, got {len(snake_case )}' ) raise ValueError(snake_case ) if len(snake_case ) != self.order + 1: A__ : Union[str, Any] = ( F'Expected b_coeffs to have {self.order + 1} elements ' F'for {self.order}-order filter, got {len(snake_case )}' ) raise ValueError(snake_case ) A__ : Dict = a_coeffs A__ : Any = b_coeffs def _UpperCamelCase ( self : List[str] , snake_case : float ): '''simple docstring''' A__ : str = 0.0 # Start at index 1 and do index 0 at the end. for i in range(1 , self.order + 1 ): result += ( self.b_coeffs[i] * self.input_history[i - 1] - self.a_coeffs[i] * self.output_history[i - 1] ) A__ : Dict = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0] A__ : Tuple = self.input_history[:-1] A__ : int = self.output_history[:-1] A__ : Dict = sample A__ : Tuple = result return result
296
0
"""simple docstring""" import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def _lowerCAmelCase ( ) ->Dict: raise RuntimeError("""CUDA out of memory.""" ) class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : str ): '''simple docstring''' super().__init__() A__ : List[str] = nn.Linear(3 , 4 ) A__ : Optional[Any] = nn.BatchNormad(4 ) A__ : Any = nn.Linear(4 , 5 ) def _UpperCamelCase ( self : str , snake_case : List[Any] ): '''simple docstring''' return self.lineara(self.batchnorm(self.lineara(snake_case ) ) ) class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : List[Any] = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(snake_case : Union[str, Any] ): nonlocal batch_sizes batch_sizes.append(snake_case ) if batch_size != 8: raise_fake_out_of_memory() mock_training_loop_function() self.assertListEqual(snake_case , [128, 64, 32, 16, 8] ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : List[str] = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(snake_case : int , snake_case : Optional[Any] ): nonlocal batch_sizes batch_sizes.append(snake_case ) if batch_size != 8: raise_fake_out_of_memory() return batch_size, arga A__ : Optional[int] = mock_training_loop_function("""hello""" ) self.assertListEqual(snake_case , [128, 64, 32, 16, 8] ) self.assertListEqual([bs, arga] , [8, """hello"""] ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' @find_executable_batch_size(starting_batch_size=0 ) def mock_training_loop_function(snake_case : Union[str, Any] ): pass with self.assertRaises(snake_case ) as cm: mock_training_loop_function() self.assertIn("""No executable batch size found, reached zero.""" , cm.exception.args[0] ) def _UpperCamelCase ( self : str ): '''simple docstring''' @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(snake_case : Union[str, Any] ): if batch_size > 0: raise_fake_out_of_memory() pass with self.assertRaises(snake_case ) as cm: mock_training_loop_function() self.assertIn("""No executable batch size found, reached zero.""" , cm.exception.args[0] ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(snake_case : Any , snake_case : List[str] , snake_case : Optional[int] ): if batch_size != 8: raise raise_fake_out_of_memory() with self.assertRaises(snake_case ) as cm: mock_training_loop_function(128 , """hello""" , """world""" ) self.assertIn("""Batch size was passed into `f`""" , cm.exception.args[0] ) self.assertIn("""`f(arg1='hello', arg2='world')""" , cm.exception.args[0] ) def _UpperCamelCase ( self : Dict ): '''simple docstring''' @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(snake_case : Dict ): raise ValueError("""Oops, we had an error!""" ) with self.assertRaises(snake_case ) as cm: mock_training_loop_function() self.assertIn("""Oops, we had an error!""" , cm.exception.args[0] ) @require_cuda def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Any = torch.cuda.memory_allocated() A__ : int = ModelForTest() model.cuda() self.assertGreater(torch.cuda.memory_allocated() , snake_case ) A__ : int = release_memory(snake_case ) self.assertEqual(torch.cuda.memory_allocated() , snake_case )
351
"""simple docstring""" import unittest from parameterized import parameterized from transformers import AutoTokenizer, GPTNeoXConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXModel, ) class __SCREAMING_SNAKE_CASE : def __init__( self : Optional[int] , snake_case : Optional[Any] , snake_case : Tuple=13 , snake_case : Dict=7 , snake_case : Optional[int]=True , snake_case : Union[str, Any]=True , snake_case : Dict=True , snake_case : Any=True , snake_case : List[str]=99 , snake_case : str=64 , snake_case : Optional[int]=5 , snake_case : str=4 , snake_case : List[Any]=37 , snake_case : Optional[Any]="gelu" , snake_case : List[str]=0.1 , snake_case : str=0.1 , snake_case : Optional[int]=512 , snake_case : Dict=16 , snake_case : List[Any]=2 , snake_case : Optional[int]=0.02 , snake_case : Any=3 , snake_case : Union[str, Any]=4 , snake_case : Dict=None , ): '''simple docstring''' A__ : Tuple = parent A__ : Union[str, Any] = batch_size A__ : List[str] = seq_length A__ : Optional[int] = is_training A__ : Dict = use_input_mask A__ : Any = use_token_type_ids A__ : Optional[Any] = use_labels A__ : List[str] = vocab_size A__ : Optional[int] = hidden_size A__ : Optional[Any] = num_hidden_layers A__ : Any = num_attention_heads A__ : List[Any] = intermediate_size A__ : Optional[Any] = hidden_act A__ : Optional[int] = hidden_dropout_prob A__ : Tuple = attention_probs_dropout_prob A__ : str = max_position_embeddings A__ : List[str] = type_vocab_size A__ : Union[str, Any] = type_sequence_label_size A__ : List[Any] = initializer_range A__ : Optional[int] = num_labels A__ : Dict = num_choices A__ : Dict = scope A__ : List[Any] = vocab_size - 1 def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : List[Any] = None if self.use_input_mask: A__ : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) A__ : Union[str, Any] = None if self.use_labels: A__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : Tuple = self.get_config() return config, input_ids, input_mask, token_labels def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' return GPTNeoXConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case , initializer_range=self.initializer_range , pad_token_id=self.pad_token_id , ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ , A__ , A__ , A__ : str = self.prepare_config_and_inputs() A__ : Union[str, Any] = True return config, input_ids, input_mask, token_labels def _UpperCamelCase ( self : Union[str, Any] , snake_case : Optional[int] , snake_case : List[str] , snake_case : int ): '''simple docstring''' A__ : Any = GPTNeoXModel(config=snake_case ) model.to(snake_case ) model.eval() A__ : int = model(snake_case , attention_mask=snake_case ) A__ : Optional[int] = model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : Union[str, Any] , snake_case : str , snake_case : Any , snake_case : Union[str, Any] ): '''simple docstring''' A__ : int = True A__ : str = GPTNeoXModel(snake_case ) model.to(snake_case ) model.eval() A__ : Tuple = model(snake_case , attention_mask=snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : Dict , snake_case : List[Any] , snake_case : str , snake_case : Optional[Any] , snake_case : Any ): '''simple docstring''' A__ : Any = GPTNeoXForCausalLM(config=snake_case ) model.to(snake_case ) model.eval() A__ : Tuple = 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 _UpperCamelCase ( self : List[str] , snake_case : Optional[Any] , snake_case : Optional[Any] , snake_case : Union[str, Any] , snake_case : Tuple ): '''simple docstring''' A__ : int = self.num_labels A__ : int = GPTNeoXForQuestionAnswering(snake_case ) model.to(snake_case ) model.eval() A__ : Optional[Any] = model(snake_case , attention_mask=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 _UpperCamelCase ( self : str , snake_case : Tuple , snake_case : int , snake_case : int , snake_case : Dict ): '''simple docstring''' A__ : List[Any] = self.num_labels A__ : Tuple = GPTNeoXForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : List[str] = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _UpperCamelCase ( self : Any , snake_case : Union[str, Any] , snake_case : int , snake_case : Tuple , snake_case : Any ): '''simple docstring''' A__ : Tuple = self.num_labels A__ : Any = GPTNeoXForTokenClassification(snake_case ) model.to(snake_case ) model.eval() A__ : Dict = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self : List[str] , snake_case : List[str] , snake_case : Tuple , snake_case : Any ): '''simple docstring''' A__ : Optional[int] = True A__ : Any = GPTNeoXForCausalLM(config=snake_case ) model.to(snake_case ) model.eval() # first forward pass A__ : Tuple = model(snake_case , attention_mask=snake_case , use_cache=snake_case ) A__ : str = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A__ : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ : Tuple = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and A__ : Any = torch.cat([input_ids, next_tokens] , dim=-1 ) A__ : Any = torch.cat([input_mask, next_mask] , dim=-1 ) A__ : Tuple = model(snake_case , attention_mask=snake_case , output_hidden_states=snake_case ) A__ : List[Any] = output_from_no_past["""hidden_states"""][0] A__ : List[str] = model( snake_case , attention_mask=snake_case , past_key_values=snake_case , output_hidden_states=snake_case , )["""hidden_states"""][0] # select random slice A__ : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() A__ : List[Any] = output_from_no_past[:, -3:, random_slice_idx].detach() A__ : Any = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(snake_case , snake_case , atol=1e-3 ) ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : str = self.prepare_config_and_inputs() A__ , A__ , A__ , A__ : Dict = config_and_inputs A__ : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase ): snake_case_ = ( ( GPTNeoXModel, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, ) if is_torch_available() else () ) snake_case_ = (GPTNeoXForCausalLM,) if is_torch_available() else () snake_case_ = ( { 'feature-extraction': GPTNeoXModel, 'question-answering': GPTNeoXForQuestionAnswering, 'text-classification': GPTNeoXForSequenceClassification, 'text-generation': GPTNeoXForCausalLM, 'token-classification': GPTNeoXForTokenClassification, 'zero-shot': GPTNeoXForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Any = GPTNeoXModelTester(self ) A__ : Any = ConfigTester(self , config_class=snake_case , hidden_size=64 , num_attention_heads=8 ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self : Any ): '''simple docstring''' A__ , A__ , A__ , A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(snake_case , snake_case , snake_case ) def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ , A__ , A__ , A__ : Dict = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(snake_case , snake_case , snake_case ) def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ , A__ , A__ , A__ : List[str] = self.model_tester.prepare_config_and_inputs_for_decoder() A__ : Optional[Any] = None self.model_tester.create_and_check_model_as_decoder(snake_case , snake_case , snake_case ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ , A__ , A__ , A__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(snake_case , snake_case , snake_case ) def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*snake_case ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case ) @unittest.skip(reason="""Feed forward chunking is not implemented""" ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' pass @parameterized.expand([("""linear""",), ("""dynamic""",)] ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Optional[Any] ): '''simple docstring''' A__ , A__ : int = self.model_tester.prepare_config_and_inputs_for_common() A__ : List[Any] = ids_tensor([1, 10] , config.vocab_size ) A__ : str = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A__ : Union[str, Any] = GPTNeoXModel(snake_case ) original_model.to(snake_case ) original_model.eval() A__ : Optional[int] = original_model(snake_case ).last_hidden_state A__ : List[str] = original_model(snake_case ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A__ : Optional[int] = {"""type""": scaling_type, """factor""": 10.0} A__ : Optional[int] = GPTNeoXModel(snake_case ) scaled_model.to(snake_case ) scaled_model.eval() A__ : List[str] = scaled_model(snake_case ).last_hidden_state A__ : Tuple = scaled_model(snake_case ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(snake_case , snake_case , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(snake_case , snake_case , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(snake_case , snake_case , atol=1e-5 ) ) @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Any = AutoTokenizer.from_pretrained("""EleutherAI/pythia-410m-deduped""" ) for checkpointing in [True, False]: A__ : Optional[Any] = GPTNeoXForCausalLM.from_pretrained("""EleutherAI/pythia-410m-deduped""" ) if checkpointing: model.gradient_checkpointing_enable() else: model.gradient_checkpointing_disable() model.to(snake_case ) A__ : Optional[Any] = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(snake_case ) # The hub repo. is updated on 2023-04-04, resulting in poor outputs. # See: https://github.com/huggingface/transformers/pull/24193 A__ : Union[str, Any] = """My favorite food is a good old-fashioned, old-fashioned, old-fashioned.\n\nI'm not sure""" A__ : Tuple = model.generate(**snake_case , do_sample=snake_case , max_new_tokens=20 ) A__ : Tuple = tokenizer.batch_decode(snake_case )[0] self.assertEqual(snake_case , snake_case )
296
0
"""simple docstring""" import math A_ = 10 A_ = 7 A_ = BALLS_PER_COLOUR * NUM_COLOURS def _lowerCAmelCase ( UpperCAmelCase__ : int = 2_0 ) ->str: A__ : List[Any] = math.comb(UpperCAmelCase__, UpperCAmelCase__ ) A__ : Optional[int] = math.comb(NUM_BALLS - BALLS_PER_COLOUR, UpperCAmelCase__ ) A__ : int = NUM_COLOURS * (1 - missing_colour / total) return f'{result:.9f}' if __name__ == "__main__": print(solution(20))
352
"""simple docstring""" from collections import defaultdict from math import gcd def _lowerCAmelCase ( UpperCAmelCase__ : int = 1_5_0_0_0_0_0 ) ->int: A__ : defaultdict = defaultdict(UpperCAmelCase__ ) A__ : Any = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1, UpperCAmelCase__, 2 ): if gcd(UpperCAmelCase__, UpperCAmelCase__ ) > 1: continue A__ : str = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(UpperCAmelCase__, limit + 1, UpperCAmelCase__ ): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1 ) if __name__ == "__main__": print(F'{solution() = }')
296
0
"""simple docstring""" def _lowerCAmelCase ( UpperCAmelCase__ : int = 1_0_0_0_0_0_0 ) ->int: A__ : int = set(range(3, UpperCAmelCase__, 2 ) ) primes.add(2 ) for p in range(3, UpperCAmelCase__, 2 ): if p not in primes: continue primes.difference_update(set(range(p * p, UpperCAmelCase__, UpperCAmelCase__ ) ) ) A__ : str = [float(UpperCAmelCase__ ) for n in range(limit + 1 )] for p in primes: for n in range(UpperCAmelCase__, limit + 1, UpperCAmelCase__ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(F'{solution() = }')
353
"""simple docstring""" import os from distutils.util import strtobool def _lowerCAmelCase ( UpperCAmelCase__ : List[Any], UpperCAmelCase__ : Optional[Any] ) ->List[str]: for e in env_keys: A__ : List[Any] = int(os.environ.get(UpperCAmelCase__, -1 ) ) if val >= 0: return val return default def _lowerCAmelCase ( UpperCAmelCase__ : Tuple, UpperCAmelCase__ : str=False ) ->List[str]: A__ : List[Any] = os.environ.get(UpperCAmelCase__, str(UpperCAmelCase__ ) ) return strtobool(UpperCAmelCase__ ) == 1 # As its name indicates `strtobool` actually returns an int... def _lowerCAmelCase ( UpperCAmelCase__ : Tuple, UpperCAmelCase__ : List[Any]="no" ) ->int: A__ : str = os.environ.get(UpperCAmelCase__, str(UpperCAmelCase__ ) ) return value
296
0
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { '''microsoft/git-base''': '''https://huggingface.co/microsoft/git-base/resolve/main/config.json''', } class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = 'git_vision_model' def __init__( self : Union[str, Any] , snake_case : Any=768 , snake_case : Optional[int]=3072 , snake_case : Tuple=12 , snake_case : Any=12 , snake_case : Dict=3 , snake_case : Dict=224 , snake_case : List[str]=16 , snake_case : Optional[int]="quick_gelu" , snake_case : Optional[int]=1e-5 , snake_case : Tuple=0.0 , snake_case : Optional[int]=0.02 , **snake_case : Optional[Any] , ): '''simple docstring''' super().__init__(**snake_case ) A__ : Dict = hidden_size A__ : Optional[Any] = intermediate_size A__ : List[str] = num_hidden_layers A__ : Optional[Any] = num_attention_heads A__ : Any = num_channels A__ : Tuple = patch_size A__ : Any = image_size A__ : str = initializer_range A__ : Any = attention_dropout A__ : List[str] = layer_norm_eps A__ : Tuple = hidden_act @classmethod def _UpperCamelCase ( cls : str , snake_case : Union[str, os.PathLike] , **snake_case : Any ): '''simple docstring''' cls._set_token_in_kwargs(snake_case ) A__ : Any = cls.get_config_dict(snake_case , **snake_case ) # get the vision config dict if we are loading from GITConfig if config_dict.get("""model_type""" ) == "git": A__ : Tuple = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(snake_case , **snake_case ) class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = 'git' def __init__( self : Any , snake_case : Tuple=None , snake_case : int=3_0522 , snake_case : Optional[int]=768 , snake_case : int=6 , snake_case : int=12 , snake_case : Optional[Any]=3072 , snake_case : Dict="gelu" , snake_case : str=0.1 , snake_case : int=0.1 , snake_case : Dict=1024 , snake_case : Optional[Any]=0.02 , snake_case : Optional[int]=1e-12 , snake_case : int=0 , snake_case : int="absolute" , snake_case : List[str]=True , snake_case : List[str]=False , snake_case : List[str]=101 , snake_case : int=102 , snake_case : Tuple=None , **snake_case : Optional[Any] , ): '''simple docstring''' super().__init__(bos_token_id=snake_case , eos_token_id=snake_case , pad_token_id=snake_case , **snake_case ) if vision_config is None: A__ : Any = {} logger.info("""vision_config is None. initializing the GitVisionConfig with default values.""" ) A__ : Union[str, Any] = GitVisionConfig(**snake_case ) A__ : Any = vocab_size A__ : Optional[int] = hidden_size A__ : List[str] = num_hidden_layers A__ : Dict = num_attention_heads A__ : List[Any] = hidden_act A__ : Tuple = intermediate_size A__ : str = hidden_dropout_prob A__ : List[Any] = attention_probs_dropout_prob A__ : Any = max_position_embeddings A__ : Union[str, Any] = initializer_range A__ : Union[str, Any] = layer_norm_eps A__ : Dict = position_embedding_type A__ : List[str] = use_cache A__ : List[Any] = tie_word_embeddings A__ : List[str] = num_image_with_embedding A__ : str = bos_token_id A__ : int = eos_token_id def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Union[str, Any] = copy.deepcopy(self.__dict__ ) A__ : Union[str, Any] = self.vision_config.to_dict() A__ : str = self.__class__.model_type return output
354
"""simple docstring""" import cva import numpy as np class __SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , snake_case : float , snake_case : int ): '''simple docstring''' if k in (0.04, 0.06): A__ : Optional[int] = k A__ : int = window_size else: raise ValueError("""invalid k value""" ) def __str__( self : List[Any] ): '''simple docstring''' return str(self.k ) def _UpperCamelCase ( self : int , snake_case : str ): '''simple docstring''' A__ : List[str] = cva.imread(snake_case , 0 ) A__ , A__ : Union[str, Any] = img.shape A__ : list[list[int]] = [] A__ : Optional[Any] = img.copy() A__ : List[str] = cva.cvtColor(snake_case , cva.COLOR_GRAY2RGB ) A__ , A__ : List[Any] = np.gradient(snake_case ) A__ : List[Any] = dx**2 A__ : Any = dy**2 A__ : Dict = dx * dy A__ : Any = 0.04 A__ : Optional[Any] = self.window_size // 2 for y in range(snake_case , h - offset ): for x in range(snake_case , w - offset ): A__ : List[str] = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() A__ : Tuple = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() A__ : Optional[int] = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() A__ : int = (wxx * wyy) - (wxy**2) A__ : Any = wxx + wyy A__ : List[str] = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 255 ) return color_img, corner_list if __name__ == "__main__": A_ = HarrisCorner(0.04, 3) A_ , A_ = edge_detect.detect('''path_to_image''') cva.imwrite('''detect.png''', color_img)
296
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { '''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/config.json''', '''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/config.json''', '''xlm-roberta-large-finetuned-conll02-dutch''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll02-spanish''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-english''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-german''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json''' ), } class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = 'xlm-roberta' def __init__( self : Tuple , snake_case : Optional[Any]=3_0522 , snake_case : Optional[Any]=768 , snake_case : Any=12 , snake_case : Optional[int]=12 , snake_case : Any=3072 , snake_case : Optional[Any]="gelu" , snake_case : List[str]=0.1 , snake_case : Dict=0.1 , snake_case : Tuple=512 , snake_case : Union[str, Any]=2 , snake_case : Any=0.02 , snake_case : Union[str, Any]=1e-12 , snake_case : Any=1 , snake_case : Optional[int]=0 , snake_case : Optional[int]=2 , snake_case : int="absolute" , snake_case : Dict=True , snake_case : str=None , **snake_case : Dict , ): '''simple docstring''' super().__init__(pad_token_id=snake_case , bos_token_id=snake_case , eos_token_id=snake_case , **snake_case ) A__ : Optional[int] = vocab_size A__ : Optional[Any] = hidden_size A__ : Optional[Any] = num_hidden_layers A__ : List[str] = num_attention_heads A__ : Union[str, Any] = hidden_act A__ : Any = intermediate_size A__ : Dict = hidden_dropout_prob A__ : Any = attention_probs_dropout_prob A__ : Tuple = max_position_embeddings A__ : List[str] = type_vocab_size A__ : Optional[int] = initializer_range A__ : Any = layer_norm_eps A__ : List[str] = position_embedding_type A__ : str = use_cache A__ : int = classifier_dropout class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): @property def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' if self.task == "multiple-choice": A__ : int = {0: """batch""", 1: """choice""", 2: """sequence"""} else: A__ : List[str] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
355
"""simple docstring""" from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING A_ = logging.get_logger(__name__) A_ = Dict[str, Any] A_ = List[Prediction] @add_end_docstrings(UpperCamelCase ) class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): def __init__( self : str , *snake_case : Tuple , **snake_case : Tuple ): '''simple docstring''' super().__init__(*snake_case , **snake_case ) if self.framework == "tf": raise ValueError(F'The {self.__class__} is only available in PyTorch.' ) requires_backends(self , """vision""" ) self.check_model_type( dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items() ) ) def _UpperCamelCase ( self : List[Any] , **snake_case : Optional[int] ): '''simple docstring''' A__ : Dict = {} if "threshold" in kwargs: A__ : int = kwargs["""threshold"""] return {}, {}, postprocess_kwargs def __call__( self : Tuple , *snake_case : Union[str, Any] , **snake_case : Union[str, Any] ): '''simple docstring''' return super().__call__(*snake_case , **snake_case ) def _UpperCamelCase ( self : str , snake_case : int ): '''simple docstring''' A__ : List[str] = load_image(snake_case ) A__ : int = torch.IntTensor([[image.height, image.width]] ) A__ : Union[str, Any] = self.image_processor(images=[image] , return_tensors="""pt""" ) if self.tokenizer is not None: A__ : str = self.tokenizer(text=inputs["""words"""] , boxes=inputs["""boxes"""] , return_tensors="""pt""" ) A__ : List[str] = target_size return inputs def _UpperCamelCase ( self : Optional[int] , snake_case : List[Any] ): '''simple docstring''' A__ : str = model_inputs.pop("""target_size""" ) A__ : Dict = self.model(**snake_case ) A__ : Optional[Any] = outputs.__class__({"""target_size""": target_size, **outputs} ) if self.tokenizer is not None: A__ : str = model_inputs["""bbox"""] return model_outputs def _UpperCamelCase ( self : Tuple , snake_case : Optional[int] , snake_case : int=0.9 ): '''simple docstring''' A__ : Any = model_outputs["""target_size"""] if self.tokenizer is not None: # This is a LayoutLMForTokenClassification variant. # The OCR got the boxes and the model classified the words. A__ , A__ : Tuple = target_size[0].tolist() def unnormalize(snake_case : Optional[int] ): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ] ) ) A__ , A__ : Optional[int] = model_outputs["""logits"""].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 ) A__ : Optional[Any] = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] A__ : List[str] = [unnormalize(snake_case ) for bbox in model_outputs["""bbox"""].squeeze(0 )] A__ : Tuple = ["""score""", """label""", """box"""] A__ : Any = [dict(zip(snake_case , snake_case ) ) for vals in zip(scores.tolist() , snake_case , snake_case ) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel A__ : Union[str, Any] = self.image_processor.post_process_object_detection(snake_case , snake_case , snake_case ) A__ : str = raw_annotations[0] A__ : str = raw_annotation["""scores"""] A__ : List[Any] = raw_annotation["""labels"""] A__ : int = raw_annotation["""boxes"""] A__ : str = scores.tolist() A__ : Any = [self.model.config.idalabel[label.item()] for label in labels] A__ : int = [self._get_bounding_box(snake_case ) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] A__ : str = ["""score""", """label""", """box"""] A__ : Dict = [ dict(zip(snake_case , snake_case ) ) for vals in zip(raw_annotation["""scores"""] , raw_annotation["""labels"""] , raw_annotation["""boxes"""] ) ] return annotation def _UpperCamelCase ( self : Union[str, Any] , snake_case : "torch.Tensor" ): '''simple docstring''' if self.framework != "pt": raise ValueError("""The ObjectDetectionPipeline is only available in PyTorch.""" ) A__ , A__ , A__ , A__ : Any = box.int().tolist() A__ : Any = { """xmin""": xmin, """ymin""": ymin, """xmax""": xmax, """ymax""": ymax, } return bbox
296
0
"""simple docstring""" def _lowerCAmelCase ( UpperCAmelCase__ : int | float | str ) ->tuple[int, int]: try: A__ : Dict = float(UpperCAmelCase__ ) except ValueError: raise ValueError("""Please enter a valid number""" ) A__ : int = decimal - int(UpperCAmelCase__ ) if fractional_part == 0: return int(UpperCAmelCase__ ), 1 else: A__ : int = len(str(UpperCAmelCase__ ).split(""".""" )[1] ) A__ : Optional[Any] = int(decimal * (1_0**number_of_frac_digits) ) A__ : Any = 1_0**number_of_frac_digits A__ : Union[str, Any] = denominator, numerator while True: A__ : List[str] = dividend % divisor if remainder == 0: break A__ : Tuple = divisor, remainder A__ : Optional[int] = numerator / divisor, denominator / divisor return int(UpperCAmelCase__ ), int(UpperCAmelCase__ ) if __name__ == "__main__": print(F'{decimal_to_fraction(2) = }') print(F'{decimal_to_fraction(89.0) = }') print(F'{decimal_to_fraction("67") = }') print(F'{decimal_to_fraction("45.0") = }') print(F'{decimal_to_fraction(1.5) = }') print(F'{decimal_to_fraction("6.25") = }') print(F'{decimal_to_fraction("78td") = }')
356
"""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 A_ = logging.get_logger(__name__) A_ = { '''microsoft/table-transformer-detection''': ( '''https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json''' ), } class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = 'table-transformer' snake_case_ = ['past_key_values'] snake_case_ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Dict , snake_case : int=True , snake_case : Dict=None , snake_case : Union[str, Any]=3 , snake_case : Dict=100 , snake_case : Tuple=6 , snake_case : Optional[int]=2048 , snake_case : int=8 , snake_case : Dict=6 , snake_case : Any=2048 , snake_case : str=8 , snake_case : Union[str, Any]=0.0 , snake_case : List[str]=0.0 , snake_case : List[str]=True , snake_case : Any="relu" , snake_case : str=256 , snake_case : int=0.1 , snake_case : Dict=0.0 , snake_case : str=0.0 , snake_case : Union[str, Any]=0.02 , snake_case : Union[str, Any]=1.0 , snake_case : Optional[Any]=False , snake_case : int="sine" , snake_case : Optional[Any]="resnet50" , snake_case : Optional[int]=True , snake_case : Any=False , snake_case : int=1 , snake_case : Tuple=5 , snake_case : Optional[int]=2 , snake_case : Tuple=1 , snake_case : Optional[Any]=1 , snake_case : Optional[Any]=5 , snake_case : Dict=2 , snake_case : Any=0.1 , **snake_case : Any , ): '''simple docstring''' 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.""" ) A__ : Optional[Any] = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(snake_case , snake_case ): A__ : Optional[int] = backbone_config.get("""model_type""" ) A__ : Optional[int] = CONFIG_MAPPING[backbone_model_type] A__ : List[str] = config_class.from_dict(snake_case ) # set timm attributes to None A__ , A__ , A__ : str = None, None, None A__ : Tuple = use_timm_backbone A__ : str = backbone_config A__ : str = num_channels A__ : List[Any] = num_queries A__ : Optional[Any] = d_model A__ : Tuple = encoder_ffn_dim A__ : Union[str, Any] = encoder_layers A__ : List[Any] = encoder_attention_heads A__ : Optional[int] = decoder_ffn_dim A__ : Any = decoder_layers A__ : int = decoder_attention_heads A__ : Any = dropout A__ : Dict = attention_dropout A__ : Dict = activation_dropout A__ : Tuple = activation_function A__ : List[str] = init_std A__ : List[str] = init_xavier_std A__ : Any = encoder_layerdrop A__ : Optional[Any] = decoder_layerdrop A__ : Union[str, Any] = encoder_layers A__ : Dict = auxiliary_loss A__ : List[Any] = position_embedding_type A__ : Optional[Any] = backbone A__ : str = use_pretrained_backbone A__ : Union[str, Any] = dilation # Hungarian matcher A__ : Tuple = class_cost A__ : Optional[Any] = bbox_cost A__ : Dict = giou_cost # Loss coefficients A__ : Any = mask_loss_coefficient A__ : str = dice_loss_coefficient A__ : str = bbox_loss_coefficient A__ : Union[str, Any] = giou_loss_coefficient A__ : List[str] = eos_coefficient super().__init__(is_encoder_decoder=snake_case , **snake_case ) @property def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return self.encoder_attention_heads @property def _UpperCamelCase ( self : Dict ): '''simple docstring''' return self.d_model class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = version.parse('1.11' ) @property def _UpperCamelCase ( self : Any ): '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' return 1e-5 @property def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return 12
296
0
"""simple docstring""" import qiskit def _lowerCAmelCase ( UpperCAmelCase__ : int, UpperCAmelCase__ : int ) ->qiskit.result.counts.Counts: A__ : Optional[Any] = qiskit.Aer.get_backend("""aer_simulator""" ) # Create a Quantum Circuit acting on the q register A__ : List[Any] = qiskit.QuantumCircuit(UpperCAmelCase__, UpperCAmelCase__ ) # Map the quantum measurement to the classical bits circuit.measure([0], [0] ) # Execute the circuit on the simulator A__ : int = qiskit.execute(UpperCAmelCase__, UpperCAmelCase__, shots=1_0_0_0 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(UpperCAmelCase__ ) if __name__ == "__main__": print(F'Total count for various states are: {single_qubit_measure(1, 1)}')
357
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = 'Salesforce/blip-image-captioning-base' snake_case_ = ( 'This is a tool that generates a description of an image. It takes an input named `image` which should be the ' 'image to caption, and returns a text that contains the description in English.' ) snake_case_ = 'image_captioner' snake_case_ = AutoModelForVisionaSeq snake_case_ = ['image'] snake_case_ = ['text'] def __init__( self : int , *snake_case : Optional[int] , **snake_case : Optional[int] ): '''simple docstring''' requires_backends(self , ["""vision"""] ) super().__init__(*snake_case , **snake_case ) def _UpperCamelCase ( self : int , snake_case : "Image" ): '''simple docstring''' return self.pre_processor(images=snake_case , return_tensors="""pt""" ) def _UpperCamelCase ( self : int , snake_case : List[Any] ): '''simple docstring''' return self.model.generate(**snake_case ) def _UpperCamelCase ( self : Optional[int] , snake_case : Any ): '''simple docstring''' return self.pre_processor.batch_decode(snake_case , skip_special_tokens=snake_case )[0].strip()
296
0
"""simple docstring""" import argparse import os from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_task_guides.py A_ = '''src/transformers''' A_ = '''docs/source/en/tasks''' def _lowerCAmelCase ( UpperCAmelCase__ : Dict, UpperCAmelCase__ : Any, UpperCAmelCase__ : str ) ->Optional[int]: with open(UpperCAmelCase__, """r""", encoding="""utf-8""", newline="""\n""" ) as f: A__ : int = f.readlines() # Find the start prompt. A__ : List[Any] = 0 while not lines[start_index].startswith(UpperCAmelCase__ ): start_index += 1 start_index += 1 A__ : str = start_index while not lines[end_index].startswith(UpperCAmelCase__ ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # This is to make sure the transformers module imported is the one in the repo. A_ = direct_transformers_import(TRANSFORMERS_PATH) A_ = { '''asr.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES, '''audio_classification.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, '''language_modeling.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, '''image_classification.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, '''masked_language_modeling.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES, '''multiple_choice.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES, '''object_detection.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, '''question_answering.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, '''semantic_segmentation.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, '''sequence_classification.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, '''summarization.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, '''token_classification.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, '''translation.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, '''video_classification.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES, '''document_question_answering.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, '''monocular_depth_estimation.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, } # This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any # `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`). A_ = { '''summarization.md''': ('''nllb''',), '''translation.md''': ('''nllb''',), } def _lowerCAmelCase ( UpperCAmelCase__ : str ) ->str: A__ : Optional[int] = TASK_GUIDE_TO_MODELS[task_guide] A__ : Tuple = SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(UpperCAmelCase__, set() ) A__ : Any = { code: name for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if (code in model_maping_names or code in special_model_types) } return ", ".join([f'[{name}](../model_doc/{code})' for code, name in model_names.items()] ) + "\n" def _lowerCAmelCase ( UpperCAmelCase__ : List[Any], UpperCAmelCase__ : int=False ) ->int: A__ : str = _find_text_in_file( filename=os.path.join(UpperCAmelCase__, UpperCAmelCase__ ), start_prompt="""<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->""", end_prompt="""<!--End of the generated tip-->""", ) A__ : List[Any] = get_model_list_for_task(UpperCAmelCase__ ) if current_list != new_list: if overwrite: with open(os.path.join(UpperCAmelCase__, UpperCAmelCase__ ), """w""", encoding="""utf-8""", newline="""\n""" ) as f: f.writelines(lines[:start_index] + [new_list] + lines[end_index:] ) else: raise ValueError( f'The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`' """ to fix this.""" ) if __name__ == "__main__": A_ = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') A_ = parser.parse_args() for task_guide in TASK_GUIDE_TO_MODELS.keys(): check_model_list_for_task(task_guide, args.fix_and_overwrite)
358
"""simple docstring""" import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : List[Any] ): '''simple docstring''' super().__init__() A__ : int = nn.Linear(3 , 4 ) A__ : Union[str, Any] = nn.BatchNormad(4 ) A__ : Union[str, Any] = nn.Linear(4 , 5 ) def _UpperCamelCase ( self : str , snake_case : List[str] ): '''simple docstring''' return self.lineara(self.batchnorm(self.lineara(snake_case ) ) ) class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : int = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(snake_case , model.state_dict() ) A__ : List[str] = os.path.join(snake_case , """index.json""" ) self.assertTrue(os.path.isfile(snake_case ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: A__ : List[str] = os.path.join(snake_case , F'{key}.dat' ) self.assertTrue(os.path.isfile(snake_case ) ) # TODO: add tests on the fact weights are properly loaded def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Union[str, Any] = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: A__ : str = torch.randn(2 , 3 , dtype=snake_case ) with TemporaryDirectory() as tmp_dir: A__ : List[str] = offload_weight(snake_case , """weight""" , snake_case , {} ) A__ : Union[str, Any] = os.path.join(snake_case , """weight.dat""" ) self.assertTrue(os.path.isfile(snake_case ) ) self.assertDictEqual(snake_case , {"""weight""": {"""shape""": [2, 3], """dtype""": str(snake_case ).split(""".""" )[1]}} ) A__ : str = load_offloaded_weight(snake_case , index["""weight"""] ) self.assertTrue(torch.equal(snake_case , snake_case ) ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : str = ModelForTest() A__ : Union[str, Any] = model.state_dict() A__ : Optional[int] = {k: v for k, v in state_dict.items() if """linear2""" not in k} A__ : List[Any] = {k: v for k, v in state_dict.items() if """linear2""" in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(snake_case , snake_case ) A__ : Dict = OffloadedWeightsLoader(state_dict=snake_case , save_folder=snake_case ) # Every key is there with the right value self.assertEqual(sorted(snake_case ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(snake_case , weight_map[key] ) ) A__ : int = {k: v for k, v in state_dict.items() if """weight""" in k} A__ : Tuple = {k: v for k, v in state_dict.items() if """weight""" not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(snake_case , snake_case ) A__ : Optional[Any] = OffloadedWeightsLoader(state_dict=snake_case , save_folder=snake_case ) # Every key is there with the right value self.assertEqual(sorted(snake_case ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(snake_case , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(snake_case , snake_case ) # Duplicates are removed A__ : int = OffloadedWeightsLoader(state_dict=snake_case , save_folder=snake_case ) # Every key is there with the right value self.assertEqual(sorted(snake_case ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(snake_case , weight_map[key] ) ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : List[str] = {"""a.1""": 0, """a.10""": 1, """a.2""": 2} A__ : str = extract_submodules_state_dict(snake_case , ["""a.1""", """a.2"""] ) self.assertDictEqual(snake_case , {"""a.1""": 0, """a.2""": 2} ) A__ : Dict = {"""a.1.a""": 0, """a.10.a""": 1, """a.2.a""": 2} A__ : int = extract_submodules_state_dict(snake_case , ["""a.1""", """a.2"""] ) self.assertDictEqual(snake_case , {"""a.1.a""": 0, """a.2.a""": 2} )
296
0
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) def _lowerCAmelCase ( UpperCAmelCase__ : Union[str, Any], UpperCAmelCase__ : Tuple=False ) ->str: A__ : Optional[int] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'blocks.{i}.norm1.weight', f'deit.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((f'blocks.{i}.norm1.bias', f'deit.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append((f'blocks.{i}.attn.proj.weight', f'deit.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append((f'blocks.{i}.attn.proj.bias', f'deit.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((f'blocks.{i}.norm2.weight', f'deit.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((f'blocks.{i}.norm2.bias', f'deit.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append((f'blocks.{i}.mlp.fc1.weight', f'deit.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((f'blocks.{i}.mlp.fc1.bias', f'deit.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((f'blocks.{i}.mlp.fc2.weight', f'deit.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((f'blocks.{i}.mlp.fc2.bias', f'deit.encoder.layer.{i}.output.dense.bias') ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """deit.embeddings.cls_token"""), ("""dist_token""", """deit.embeddings.distillation_token"""), ("""patch_embed.proj.weight""", """deit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """deit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """deit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" A__ : Optional[int] = [(pair[0], pair[1][4:]) if pair[1].startswith("""deit""" ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ("""norm.weight""", """deit.layernorm.weight"""), ("""norm.bias""", """deit.layernorm.bias"""), ("""head.weight""", """cls_classifier.weight"""), ("""head.bias""", """cls_classifier.bias"""), ("""head_dist.weight""", """distillation_classifier.weight"""), ("""head_dist.bias""", """distillation_classifier.bias"""), ] ) return rename_keys def _lowerCAmelCase ( UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : Tuple, UpperCAmelCase__ : List[Any]=False ) ->str: for i in range(config.num_hidden_layers ): if base_model: A__ : Any = """""" else: A__ : Tuple = """deit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) A__ : Any = state_dict.pop(f'blocks.{i}.attn.qkv.weight' ) A__ : Tuple = state_dict.pop(f'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict A__ : List[Any] = in_proj_weight[ : config.hidden_size, : ] A__ : str = in_proj_bias[: config.hidden_size] A__ : Any = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] A__ : Dict = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] A__ : Optional[Any] = in_proj_weight[ -config.hidden_size :, : ] A__ : Any = in_proj_bias[-config.hidden_size :] def _lowerCAmelCase ( UpperCAmelCase__ : List[Any], UpperCAmelCase__ : List[Any], UpperCAmelCase__ : Union[str, Any] ) ->Any: A__ : int = dct.pop(UpperCAmelCase__ ) A__ : Tuple = val def _lowerCAmelCase ( ) ->List[Any]: A__ : Optional[int] = """http://images.cocodataset.org/val2017/000000039769.jpg""" A__ : int = Image.open(requests.get(UpperCAmelCase__, stream=UpperCAmelCase__ ).raw ) return im @torch.no_grad() def _lowerCAmelCase ( UpperCAmelCase__ : Dict, UpperCAmelCase__ : Any ) ->Tuple: A__ : List[Any] = DeiTConfig() # all deit models have fine-tuned heads A__ : Tuple = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size A__ : str = 1_0_0_0 A__ : List[str] = """huggingface/label-files""" A__ : Dict = """imagenet-1k-id2label.json""" A__ : List[str] = json.load(open(hf_hub_download(UpperCAmelCase__, UpperCAmelCase__, repo_type="""dataset""" ), """r""" ) ) A__ : Dict = {int(UpperCAmelCase__ ): v for k, v in idalabel.items()} A__ : Optional[int] = idalabel A__ : Dict = {v: k for k, v in idalabel.items()} A__ : List[str] = int(deit_name[-6:-4] ) A__ : str = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith("""tiny""" ): A__ : List[str] = 1_9_2 A__ : int = 7_6_8 A__ : List[Any] = 1_2 A__ : Dict = 3 elif deit_name[9:].startswith("""small""" ): A__ : List[Any] = 3_8_4 A__ : List[str] = 1_5_3_6 A__ : Any = 1_2 A__ : Union[str, Any] = 6 if deit_name[9:].startswith("""base""" ): pass elif deit_name[4:].startswith("""large""" ): A__ : int = 1_0_2_4 A__ : str = 4_0_9_6 A__ : Any = 2_4 A__ : int = 1_6 # load original model from timm A__ : Dict = timm.create_model(UpperCAmelCase__, pretrained=UpperCAmelCase__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys A__ : Tuple = timm_model.state_dict() A__ : str = create_rename_keys(UpperCAmelCase__, UpperCAmelCase__ ) for src, dest in rename_keys: rename_key(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) read_in_q_k_v(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) # load HuggingFace model A__ : str = DeiTForImageClassificationWithTeacher(UpperCAmelCase__ ).eval() model.load_state_dict(UpperCAmelCase__ ) # Check outputs on an image, prepared by DeiTImageProcessor A__ : int = int( (2_5_6 / 2_2_4) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 A__ : Any = DeiTImageProcessor(size=UpperCAmelCase__, crop_size=config.image_size ) A__ : Union[str, Any] = image_processor(images=prepare_img(), return_tensors="""pt""" ) A__ : Optional[Any] = encoding["""pixel_values"""] A__ : Union[str, Any] = model(UpperCAmelCase__ ) A__ : Union[str, Any] = timm_model(UpperCAmelCase__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(UpperCAmelCase__, outputs.logits, atol=1e-3 ) Path(UpperCAmelCase__ ).mkdir(exist_ok=UpperCAmelCase__ ) print(f'Saving model {deit_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(UpperCAmelCase__ ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(UpperCAmelCase__ ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--deit_name''', default='''vit_deit_base_distilled_patch16_224''', type=str, help='''Name of the DeiT 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.''' ) A_ = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
359
"""simple docstring""" import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class __SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , snake_case : str , snake_case : List[Any]=13 , snake_case : Union[str, Any]=7 , snake_case : Optional[Any]=True , snake_case : str=True , snake_case : Dict=False , snake_case : Union[str, Any]=True , snake_case : Optional[Any]=99 , snake_case : str=32 , snake_case : Tuple=5 , snake_case : List[str]=4 , snake_case : Optional[int]=37 , snake_case : str="gelu" , snake_case : Tuple=0.1 , snake_case : Optional[int]=0.1 , snake_case : int=512 , snake_case : List[str]=16 , snake_case : str=2 , snake_case : Optional[int]=0.02 , snake_case : str=3 , snake_case : Dict=4 , snake_case : Optional[Any]=None , ): '''simple docstring''' A__ : int = parent A__ : Union[str, Any] = batch_size A__ : Optional[int] = seq_length A__ : List[Any] = is_training A__ : List[str] = use_input_mask A__ : Optional[Any] = use_token_type_ids A__ : List[Any] = use_labels A__ : Union[str, Any] = vocab_size A__ : List[Any] = hidden_size A__ : Any = num_hidden_layers A__ : Any = num_attention_heads A__ : Optional[int] = intermediate_size A__ : Any = hidden_act A__ : Tuple = hidden_dropout_prob A__ : Dict = attention_probs_dropout_prob A__ : Optional[int] = max_position_embeddings A__ : Tuple = type_vocab_size A__ : Union[str, Any] = type_sequence_label_size A__ : List[str] = initializer_range A__ : Any = num_labels A__ : Any = num_choices A__ : int = scope def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Tuple = None if self.use_input_mask: A__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) A__ : Union[str, Any] = None if self.use_token_type_ids: A__ : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A__ : int = None A__ : int = None A__ : List[str] = None if self.use_labels: A__ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : Dict = ids_tensor([self.batch_size] , self.num_choices ) A__ : Union[str, Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCamelCase ( self : Tuple ): '''simple docstring''' return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case , initializer_range=self.initializer_range , ) def _UpperCamelCase ( self : Optional[int] , snake_case : Dict , snake_case : Any , snake_case : Dict , snake_case : Any , snake_case : Union[str, Any] , snake_case : Tuple , snake_case : Optional[Any] ): '''simple docstring''' A__ : Optional[Any] = BioGptModel(config=snake_case ) model.to(snake_case ) model.eval() A__ : List[Any] = model(snake_case , attention_mask=snake_case ) A__ : Dict = model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : Optional[int] , snake_case : Dict , snake_case : Optional[int] , snake_case : List[str] , snake_case : str , snake_case : Optional[Any] , snake_case : List[str] , snake_case : List[Any] , snake_case : Tuple , snake_case : Optional[Any] , ): '''simple docstring''' A__ : List[str] = BioGptForCausalLM(config=snake_case ) model.to(snake_case ) model.eval() A__ : Union[str, Any] = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCamelCase ( self : Any , snake_case : str , snake_case : Tuple , snake_case : int , snake_case : Optional[Any] , snake_case : Any , *snake_case : Dict ): '''simple docstring''' A__ : Union[str, Any] = BioGptModel(config=snake_case ) model.to(snake_case ) model.eval() # create attention mask A__ : List[Any] = torch.ones(input_ids.shape , dtype=torch.long , device=snake_case ) A__ : Any = self.seq_length // 2 A__ : str = 0 # first forward pass A__ , A__ : List[Any] = model(snake_case , attention_mask=snake_case ).to_tuple() # create hypothetical next token and extent to next_input_ids A__ : int = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids A__ : List[str] = ids_tensor((1,) , snake_case ).item() + 1 A__ : Optional[int] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) A__ : int = random_other_next_tokens # append to next input_ids and attn_mask A__ : str = torch.cat([input_ids, next_tokens] , dim=-1 ) A__ : List[Any] = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=snake_case )] , dim=1 , ) # get two different outputs A__ : Union[str, Any] = model(snake_case , attention_mask=snake_case )["""last_hidden_state"""] A__ : Optional[int] = model(snake_case , past_key_values=snake_case , attention_mask=snake_case )["""last_hidden_state"""] # select random slice A__ : List[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() A__ : List[str] = output_from_no_past[:, -1, random_slice_idx].detach() A__ : Any = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(snake_case , snake_case , atol=1e-3 ) ) def _UpperCamelCase ( self : int , snake_case : Optional[Any] , snake_case : Optional[Any] , snake_case : str , snake_case : int , snake_case : Optional[Any] , *snake_case : str ): '''simple docstring''' A__ : Dict = BioGptModel(config=snake_case ).to(snake_case ).eval() A__ : Tuple = torch.ones(input_ids.shape , dtype=torch.long , device=snake_case ) # first forward pass A__ : Dict = model(snake_case , attention_mask=snake_case , use_cache=snake_case ) A__ , A__ : List[Any] = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids A__ : Union[str, Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ : int = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and A__ : str = torch.cat([input_ids, next_tokens] , dim=-1 ) A__ : Optional[int] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) A__ : Any = model(snake_case , attention_mask=snake_case )["""last_hidden_state"""] A__ : Union[str, Any] = model(snake_case , attention_mask=snake_case , past_key_values=snake_case )[ """last_hidden_state""" ] # select random slice A__ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() A__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() A__ : List[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(snake_case , snake_case , atol=1e-3 ) ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Tuple , snake_case : Union[str, Any] , snake_case : Optional[Any] , snake_case : Any , snake_case : Tuple , *snake_case : Union[str, Any] , snake_case : Union[str, Any]=False ): '''simple docstring''' A__ : Tuple = BioGptForCausalLM(snake_case ) model.to(snake_case ) if gradient_checkpointing: model.gradient_checkpointing_enable() A__ : Optional[Any] = model(snake_case , labels=snake_case ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def _UpperCamelCase ( self : int , snake_case : Optional[Any] , *snake_case : Optional[int] ): '''simple docstring''' A__ : int = BioGptModel(snake_case ) A__ : Union[str, Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def _UpperCamelCase ( self : Any , snake_case : Dict , snake_case : Tuple , snake_case : int , snake_case : Union[str, Any] , snake_case : Dict , *snake_case : Any ): '''simple docstring''' A__ : Union[str, Any] = self.num_labels A__ : int = BioGptForTokenClassification(snake_case ) model.to(snake_case ) model.eval() A__ : str = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : List[str] = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) : str = config_and_inputs A__ : Union[str, Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase ): snake_case_ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) snake_case_ = (BioGptForCausalLM,) if is_torch_available() else () snake_case_ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = False def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : List[str] = BioGptModelTester(self ) A__ : List[Any] = ConfigTester(self , config_class=snake_case , hidden_size=37 ) def _UpperCamelCase ( self : int ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Any ): '''simple docstring''' A__ : int = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A__ : str = type self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*snake_case ) def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*snake_case , gradient_checkpointing=snake_case ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*snake_case ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*snake_case ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*snake_case ) @slow def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : Tuple = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(snake_case ) A__ : Optional[int] = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) A__ : Any = """left""" # Define PAD Token = EOS Token = 50256 A__ : Optional[int] = tokenizer.eos_token A__ : Dict = model.config.eos_token_id # use different length sentences to test batching A__ : Union[str, Any] = [ """Hello, my dog is a little""", """Today, I""", ] A__ : List[str] = tokenizer(snake_case , return_tensors="""pt""" , padding=snake_case ) A__ : str = inputs["""input_ids"""].to(snake_case ) A__ : Dict = model.generate( input_ids=snake_case , attention_mask=inputs["""attention_mask"""].to(snake_case ) , ) A__ : Optional[int] = tokenizer(sentences[0] , return_tensors="""pt""" ).input_ids.to(snake_case ) A__ : Any = model.generate(input_ids=snake_case ) A__ : List[str] = inputs_non_padded.shape[-1] - inputs["""attention_mask"""][-1].long().sum().cpu().item() A__ : str = tokenizer(sentences[1] , return_tensors="""pt""" ).input_ids.to(snake_case ) A__ : Dict = model.generate(input_ids=snake_case , max_length=model.config.max_length - num_paddings ) A__ : Optional[Any] = tokenizer.batch_decode(snake_case , skip_special_tokens=snake_case ) A__ : List[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=snake_case ) A__ : str = tokenizer.decode(output_padded[0] , skip_special_tokens=snake_case ) A__ : Optional[int] = [ """Hello, my dog is a little bit bigger than a little bit.""", """Today, I have a good idea of how to use the information""", ] self.assertListEqual(snake_case , snake_case ) self.assertListEqual(snake_case , [non_padded_sentence, padded_sentence] ) @slow def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ : Optional[Any] = BioGptModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ , A__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() A__ : Optional[int] = 3 A__ : List[Any] = input_dict["""input_ids"""] A__ : Dict = input_ids.ne(1 ).to(snake_case ) A__ : Optional[Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) A__ : Union[str, Any] = BioGptForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : int = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ , A__ : str = self.model_tester.prepare_config_and_inputs_for_common() A__ : Any = 3 A__ : List[Any] = """multi_label_classification""" A__ : Dict = input_dict["""input_ids"""] A__ : Tuple = input_ids.ne(1 ).to(snake_case ) A__ : Any = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) A__ : Tuple = BioGptForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : List[str] = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : Optional[Any] = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) A__ : str = torch.tensor([[2, 4805, 9, 656, 21]] ) A__ : Dict = model(snake_case )[0] A__ : Tuple = 4_2384 A__ : str = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , snake_case ) A__ : str = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) ) @slow def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : Tuple = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) A__ : Any = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(snake_case ) torch.manual_seed(0 ) A__ : Tuple = tokenizer("""COVID-19 is""" , return_tensors="""pt""" ).to(snake_case ) A__ : Optional[int] = model.generate( **snake_case , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=snake_case , ) A__ : Optional[int] = tokenizer.decode(output_ids[0] , skip_special_tokens=snake_case ) A__ : List[str] = ( """COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the""" """ causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and""" """ territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),""" """ and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and""" """ more than 800,000 deaths.""" ) self.assertEqual(snake_case , snake_case )
296
0
"""simple docstring""" def _lowerCAmelCase ( UpperCAmelCase__ : int, UpperCAmelCase__ : float, UpperCAmelCase__ : float ) ->float: return round(float(moles / volume ) * nfactor ) def _lowerCAmelCase ( UpperCAmelCase__ : float, UpperCAmelCase__ : float, UpperCAmelCase__ : float ) ->float: return round(float((moles * 0.0821 * temperature) / (volume) ) ) def _lowerCAmelCase ( UpperCAmelCase__ : float, UpperCAmelCase__ : float, UpperCAmelCase__ : float ) ->float: return round(float((moles * 0.0821 * temperature) / (pressure) ) ) def _lowerCAmelCase ( UpperCAmelCase__ : float, UpperCAmelCase__ : float, UpperCAmelCase__ : float ) ->float: return round(float((pressure * volume) / (0.0821 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
360
"""simple docstring""" 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 SPIECE_UNDERLINE, logging A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''spiece.model'''} A_ = { '''vocab_file''': { '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model''', '''xlnet-large-cased''': '''https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model''', } } A_ = { '''xlnet-base-cased''': None, '''xlnet-large-cased''': None, } # Segments (not really needed) A_ = 0 A_ = 1 A_ = 2 A_ = 3 A_ = 4 class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = 'left' def __init__( self : Dict , snake_case : int , snake_case : List[Any]=False , snake_case : List[str]=True , snake_case : Dict=False , snake_case : Optional[Any]="<s>" , snake_case : List[str]="</s>" , snake_case : Tuple="<unk>" , snake_case : Tuple="<sep>" , snake_case : Union[str, Any]="<pad>" , snake_case : Dict="<cls>" , snake_case : Optional[Any]="<mask>" , snake_case : Optional[int]=["<eop>", "<eod>"] , snake_case : Optional[Dict[str, Any]] = None , **snake_case : Dict , ): '''simple docstring''' A__ : Optional[int] = AddedToken(snake_case , lstrip=snake_case , rstrip=snake_case ) if isinstance(snake_case , snake_case ) else mask_token A__ : Union[str, Any] = {} 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 , additional_special_tokens=snake_case , sp_model_kwargs=self.sp_model_kwargs , **snake_case , ) A__ : str = 3 A__ : str = do_lower_case A__ : Optional[Any] = remove_space A__ : List[Any] = keep_accents A__ : Union[str, Any] = vocab_file A__ : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(snake_case ) @property def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' return len(self.sp_model ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : 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 : str ): '''simple docstring''' A__ : int = self.__dict__.copy() A__ : int = None return state def __setstate__( self : Tuple , snake_case : Union[str, Any] ): '''simple docstring''' A__ : int = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): A__ : Optional[int] = {} A__ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _UpperCamelCase ( self : List[str] , snake_case : Optional[Any] ): '''simple docstring''' if self.remove_space: A__ : Optional[Any] = """ """.join(inputs.strip().split() ) else: A__ : Dict = inputs A__ : str = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: A__ : Any = unicodedata.normalize("""NFKD""" , snake_case ) A__ : Optional[int] = """""".join([c for c in outputs if not unicodedata.combining(snake_case )] ) if self.do_lower_case: A__ : Any = outputs.lower() return outputs def _UpperCamelCase ( self : Union[str, Any] , snake_case : str ): '''simple docstring''' A__ : Dict = self.preprocess_text(snake_case ) A__ : Dict = self.sp_model.encode(snake_case , out_type=snake_case ) A__ : Optional[int] = [] for piece in pieces: if len(snake_case ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): A__ : Optional[Any] = 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__ : Any = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(snake_case ) else: new_pieces.append(snake_case ) return new_pieces def _UpperCamelCase ( self : List[str] , snake_case : Tuple ): '''simple docstring''' return self.sp_model.PieceToId(snake_case ) def _UpperCamelCase ( self : List[str] , snake_case : Any ): '''simple docstring''' return self.sp_model.IdToPiece(snake_case ) def _UpperCamelCase ( self : Optional[int] , snake_case : Any ): '''simple docstring''' A__ : Union[str, Any] = """""".join(snake_case ).replace(snake_case , """ """ ).strip() return out_string def _UpperCamelCase ( self : int , snake_case : List[int] , snake_case : bool = False , snake_case : bool = None , snake_case : bool = True , **snake_case : Union[str, Any] , ): '''simple docstring''' A__ : List[str] = kwargs.pop("""use_source_tokenizer""" , snake_case ) A__ : Any = self.convert_ids_to_tokens(snake_case , skip_special_tokens=snake_case ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 A__ : Any = [] A__ : Any = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(snake_case ) ) A__ : str = [] sub_texts.append(snake_case ) else: current_sub_text.append(snake_case ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(snake_case ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens A__ : Dict = """""".join(snake_case ) A__ : int = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: A__ : Tuple = self.clean_up_tokenization(snake_case ) return clean_text else: return text def _UpperCamelCase ( self : str , snake_case : List[int] , snake_case : Optional[List[int]] = None ): '''simple docstring''' A__ : Tuple = [self.sep_token_id] A__ : Dict = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _UpperCamelCase ( self : Dict , snake_case : List[int] , snake_case : Optional[List[int]] = None , snake_case : bool = False ): '''simple docstring''' 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 ([0] * len(snake_case )) + [1] + ([0] * len(snake_case )) + [1, 1] return ([0] * len(snake_case )) + [1, 1] def _UpperCamelCase ( self : str , snake_case : List[int] , snake_case : Optional[List[int]] = None ): '''simple docstring''' A__ : Any = [self.sep_token_id] A__ : int = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _UpperCamelCase ( self : Optional[Any] , snake_case : str , snake_case : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(snake_case ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A__ : List[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__ : Optional[Any] = self.sp_model.serialized_model_proto() fi.write(snake_case ) return (out_vocab_file,)
296
0
"""simple docstring""" import os A_ ={'''I''': 1, '''V''': 5, '''X''': 10, '''L''': 50, '''C''': 100, '''D''': 500, '''M''': 1000} def _lowerCAmelCase ( UpperCAmelCase__ : str ) ->int: A__ : Optional[int] = 0 A__ : Optional[Any] = 0 while index < len(UpperCAmelCase__ ) - 1: A__ : Any = SYMBOLS[numerals[index]] A__ : List[str] = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def _lowerCAmelCase ( UpperCAmelCase__ : int ) ->str: A__ : Union[str, Any] = """""" A__ : Dict = num // 1_0_0_0 numerals += m_count * "M" num %= 1_0_0_0 A__ : Optional[Any] = num // 1_0_0 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 1_0_0 A__ : Dict = num // 1_0 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 1_0 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def _lowerCAmelCase ( UpperCAmelCase__ : str = "/p089_roman.txt" ) ->int: A__ : str = 0 with open(os.path.dirname(UpperCAmelCase__ ) + roman_numerals_filename ) as filea: A__ : List[Any] = filea.readlines() for line in lines: A__ : Optional[Any] = line.strip() A__ : Tuple = parse_roman_numerals(UpperCAmelCase__ ) A__ : Tuple = generate_roman_numerals(UpperCAmelCase__ ) savings += len(UpperCAmelCase__ ) - len(UpperCAmelCase__ ) return savings if __name__ == "__main__": print(F'{solution() = }')
361
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) def _lowerCAmelCase ( UpperCAmelCase__ : List[Any] ) ->List[str]: A__ : Union[str, Any] = DPTConfig() if "large" in checkpoint_url: A__ : int = 1_0_2_4 A__ : Union[str, Any] = 4_0_9_6 A__ : Optional[int] = 2_4 A__ : int = 1_6 A__ : Union[str, Any] = [5, 1_1, 1_7, 2_3] A__ : Tuple = [2_5_6, 5_1_2, 1_0_2_4, 1_0_2_4] A__ : Tuple = (1, 3_8_4, 3_8_4) if "ade" in checkpoint_url: A__ : Optional[int] = True A__ : int = 1_5_0 A__ : Union[str, Any] = """huggingface/label-files""" A__ : List[Any] = """ade20k-id2label.json""" A__ : Union[str, Any] = json.load(open(cached_download(hf_hub_url(UpperCAmelCase__, UpperCAmelCase__, repo_type="""dataset""" ) ), """r""" ) ) A__ : List[Any] = {int(UpperCAmelCase__ ): v for k, v in idalabel.items()} A__ : Dict = idalabel A__ : List[Any] = {v: k for k, v in idalabel.items()} A__ : Optional[Any] = [1, 1_5_0, 4_8_0, 4_8_0] return config, expected_shape def _lowerCAmelCase ( UpperCAmelCase__ : int ) ->Any: A__ : List[Any] = ["""pretrained.model.head.weight""", """pretrained.model.head.bias"""] for k in ignore_keys: state_dict.pop(UpperCAmelCase__, UpperCAmelCase__ ) def _lowerCAmelCase ( UpperCAmelCase__ : Union[str, Any] ) ->List[str]: if ( "pretrained.model" in name and "cls_token" not in name and "pos_embed" not in name and "patch_embed" not in name ): A__ : str = name.replace("""pretrained.model""", """dpt.encoder""" ) if "pretrained.model" in name: A__ : Dict = name.replace("""pretrained.model""", """dpt.embeddings""" ) if "patch_embed" in name: A__ : List[Any] = name.replace("""patch_embed""", """patch_embeddings""" ) if "pos_embed" in name: A__ : int = name.replace("""pos_embed""", """position_embeddings""" ) if "attn.proj" in name: A__ : Tuple = name.replace("""attn.proj""", """attention.output.dense""" ) if "proj" in name and "project" not in name: A__ : List[Any] = name.replace("""proj""", """projection""" ) if "blocks" in name: A__ : Optional[Any] = name.replace("""blocks""", """layer""" ) if "mlp.fc1" in name: A__ : int = name.replace("""mlp.fc1""", """intermediate.dense""" ) if "mlp.fc2" in name: A__ : List[str] = name.replace("""mlp.fc2""", """output.dense""" ) if "norm1" in name: A__ : Any = name.replace("""norm1""", """layernorm_before""" ) if "norm2" in name: A__ : List[str] = name.replace("""norm2""", """layernorm_after""" ) if "scratch.output_conv" in name: A__ : Optional[int] = name.replace("""scratch.output_conv""", """head""" ) if "scratch" in name: A__ : List[str] = name.replace("""scratch""", """neck""" ) if "layer1_rn" in name: A__ : List[str] = name.replace("""layer1_rn""", """convs.0""" ) if "layer2_rn" in name: A__ : Optional[int] = name.replace("""layer2_rn""", """convs.1""" ) if "layer3_rn" in name: A__ : Any = name.replace("""layer3_rn""", """convs.2""" ) if "layer4_rn" in name: A__ : Any = name.replace("""layer4_rn""", """convs.3""" ) if "refinenet" in name: A__ : Union[str, Any] = int(name[len("""neck.refinenet""" ) : len("""neck.refinenet""" ) + 1] ) # tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3 A__ : str = name.replace(f'refinenet{layer_idx}', f'fusion_stage.layers.{abs(layer_idx-4 )}' ) if "out_conv" in name: A__ : Optional[Any] = name.replace("""out_conv""", """projection""" ) if "resConfUnit1" in name: A__ : List[Any] = name.replace("""resConfUnit1""", """residual_layer1""" ) if "resConfUnit2" in name: A__ : Tuple = name.replace("""resConfUnit2""", """residual_layer2""" ) if "conv1" in name: A__ : Tuple = name.replace("""conv1""", """convolution1""" ) if "conv2" in name: A__ : List[Any] = name.replace("""conv2""", """convolution2""" ) # readout blocks if "pretrained.act_postprocess1.0.project.0" in name: A__ : Union[str, Any] = name.replace("""pretrained.act_postprocess1.0.project.0""", """neck.reassemble_stage.readout_projects.0.0""" ) if "pretrained.act_postprocess2.0.project.0" in name: A__ : Tuple = name.replace("""pretrained.act_postprocess2.0.project.0""", """neck.reassemble_stage.readout_projects.1.0""" ) if "pretrained.act_postprocess3.0.project.0" in name: A__ : Optional[Any] = name.replace("""pretrained.act_postprocess3.0.project.0""", """neck.reassemble_stage.readout_projects.2.0""" ) if "pretrained.act_postprocess4.0.project.0" in name: A__ : Optional[Any] = name.replace("""pretrained.act_postprocess4.0.project.0""", """neck.reassemble_stage.readout_projects.3.0""" ) # resize blocks if "pretrained.act_postprocess1.3" in name: A__ : Any = name.replace("""pretrained.act_postprocess1.3""", """neck.reassemble_stage.layers.0.projection""" ) if "pretrained.act_postprocess1.4" in name: A__ : List[Any] = name.replace("""pretrained.act_postprocess1.4""", """neck.reassemble_stage.layers.0.resize""" ) if "pretrained.act_postprocess2.3" in name: A__ : Dict = name.replace("""pretrained.act_postprocess2.3""", """neck.reassemble_stage.layers.1.projection""" ) if "pretrained.act_postprocess2.4" in name: A__ : Optional[Any] = name.replace("""pretrained.act_postprocess2.4""", """neck.reassemble_stage.layers.1.resize""" ) if "pretrained.act_postprocess3.3" in name: A__ : Union[str, Any] = name.replace("""pretrained.act_postprocess3.3""", """neck.reassemble_stage.layers.2.projection""" ) if "pretrained.act_postprocess4.3" in name: A__ : Optional[int] = name.replace("""pretrained.act_postprocess4.3""", """neck.reassemble_stage.layers.3.projection""" ) if "pretrained.act_postprocess4.4" in name: A__ : Dict = name.replace("""pretrained.act_postprocess4.4""", """neck.reassemble_stage.layers.3.resize""" ) if "pretrained" in name: A__ : Union[str, Any] = name.replace("""pretrained""", """dpt""" ) if "bn" in name: A__ : Union[str, Any] = name.replace("""bn""", """batch_norm""" ) if "head" in name: A__ : Dict = name.replace("""head""", """head.head""" ) if "encoder.norm" in name: A__ : Optional[int] = name.replace("""encoder.norm""", """layernorm""" ) if "auxlayer" in name: A__ : List[str] = name.replace("""auxlayer""", """auxiliary_head.head""" ) return name def _lowerCAmelCase ( UpperCAmelCase__ : int, UpperCAmelCase__ : Dict ) ->str: for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) A__ : Any = state_dict.pop(f'dpt.encoder.layer.{i}.attn.qkv.weight' ) A__ : Tuple = state_dict.pop(f'dpt.encoder.layer.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict A__ : List[str] = in_proj_weight[: config.hidden_size, :] A__ : int = in_proj_bias[: config.hidden_size] A__ : Tuple = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] A__ : Any = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] A__ : str = in_proj_weight[ -config.hidden_size :, : ] A__ : Optional[Any] = in_proj_bias[-config.hidden_size :] def _lowerCAmelCase ( ) ->List[str]: A__ : int = """http://images.cocodataset.org/val2017/000000039769.jpg""" A__ : int = Image.open(requests.get(UpperCAmelCase__, stream=UpperCAmelCase__ ).raw ) return im @torch.no_grad() def _lowerCAmelCase ( UpperCAmelCase__ : int, UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : str, UpperCAmelCase__ : int ) ->str: A__ , A__ : Dict = get_dpt_config(UpperCAmelCase__ ) # load original state_dict from URL A__ : Any = torch.hub.load_state_dict_from_url(UpperCAmelCase__, map_location="""cpu""" ) # remove certain keys remove_ignore_keys_(UpperCAmelCase__ ) # rename keys for key in state_dict.copy().keys(): A__ : int = state_dict.pop(UpperCAmelCase__ ) A__ : str = val # read in qkv matrices read_in_q_k_v(UpperCAmelCase__, UpperCAmelCase__ ) # load HuggingFace model A__ : Optional[Any] = DPTForSemanticSegmentation(UpperCAmelCase__ ) if """ade""" in checkpoint_url else DPTForDepthEstimation(UpperCAmelCase__ ) model.load_state_dict(UpperCAmelCase__ ) model.eval() # Check outputs on an image A__ : Optional[Any] = 4_8_0 if """ade""" in checkpoint_url else 3_8_4 A__ : Dict = DPTImageProcessor(size=UpperCAmelCase__ ) A__ : Optional[int] = prepare_img() A__ : Any = image_processor(UpperCAmelCase__, return_tensors="""pt""" ) # forward pass A__ : List[str] = model(**UpperCAmelCase__ ).logits if """ade""" in checkpoint_url else model(**UpperCAmelCase__ ).predicted_depth # Assert logits A__ : Optional[Any] = torch.tensor([[6.3199, 6.3629, 6.4148], [6.3850, 6.3615, 6.4166], [6.3519, 6.3176, 6.3575]] ) if "ade" in checkpoint_url: A__ : Optional[int] = torch.tensor([[4.0480, 4.2420, 4.4360], [4.3124, 4.5693, 4.8261], [4.5768, 4.8965, 5.2163]] ) assert outputs.shape == torch.Size(UpperCAmelCase__ ) assert ( torch.allclose(outputs[0, 0, :3, :3], UpperCAmelCase__, atol=1e-4 ) if "ade" in checkpoint_url else torch.allclose(outputs[0, :3, :3], UpperCAmelCase__ ) ) Path(UpperCAmelCase__ ).mkdir(exist_ok=UpperCAmelCase__ ) print(f'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(UpperCAmelCase__ ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(UpperCAmelCase__ ) if push_to_hub: print("""Pushing model to hub...""" ) model.push_to_hub( repo_path_or_name=Path(UpperCAmelCase__, UpperCAmelCase__ ), organization="""nielsr""", commit_message="""Add model""", use_temp_dir=UpperCAmelCase__, ) image_processor.push_to_hub( repo_path_or_name=Path(UpperCAmelCase__, UpperCAmelCase__ ), organization="""nielsr""", commit_message="""Add image processor""", use_temp_dir=UpperCAmelCase__, ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt''', type=str, help='''URL of the original DPT checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', action='''store_true''', ) parser.add_argument( '''--model_name''', default='''dpt-large''', type=str, help='''Name of the model, in case you\'re pushing to the hub.''', ) A_ = parser.parse_args() convert_dpt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
296
0
"""simple docstring""" from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging A_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): def __init__( self : List[str] , snake_case : CLIPSegForImageSegmentation , snake_case : CLIPSegProcessor , snake_case : AutoencoderKL , snake_case : CLIPTextModel , snake_case : CLIPTokenizer , snake_case : UNetaDConditionModel , snake_case : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , snake_case : StableDiffusionSafetyChecker , snake_case : CLIPImageProcessor , ): '''simple docstring''' super().__init__() if hasattr(scheduler.config , """steps_offset""" ) and scheduler.config.steps_offset != 1: A__ : Dict = ( F'The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`' F' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure ' """to update the config accordingly as leaving `steps_offset` might led to incorrect results""" """ in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,""" """ it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`""" """ file""" ) deprecate("""steps_offset!=1""" , """1.0.0""" , snake_case , standard_warn=snake_case ) A__ : Optional[int] = dict(scheduler.config ) A__ : str = 1 A__ : List[Any] = FrozenDict(snake_case ) if hasattr(scheduler.config , """skip_prk_steps""" ) and scheduler.config.skip_prk_steps is False: A__ : Tuple = ( F'The configuration file of this scheduler: {scheduler} has not set the configuration' """ `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make""" """ sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to""" """ incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face""" """ Hub, it would be very nice if you could open a Pull request for the""" """ `scheduler/scheduler_config.json` file""" ) deprecate("""skip_prk_steps not set""" , """1.0.0""" , snake_case , standard_warn=snake_case ) A__ : List[Any] = dict(scheduler.config ) A__ : Tuple = True A__ : Any = FrozenDict(snake_case ) if safety_checker is None: logger.warning( F'You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure' """ that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered""" """ results in services or applications open to the public. Both the diffusers team and Hugging Face""" """ strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling""" """ it only for use-cases that involve analyzing network behavior or auditing its results. For more""" """ information, please have a look at https://github.com/huggingface/diffusers/pull/254 .""" ) self.register_modules( segmentation_model=snake_case , segmentation_processor=snake_case , vae=snake_case , text_encoder=snake_case , tokenizer=snake_case , unet=snake_case , scheduler=snake_case , safety_checker=snake_case , feature_extractor=snake_case , ) def _UpperCamelCase ( self : Optional[int] , snake_case : Optional[Union[str, int]] = "auto" ): '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory A__ : Dict = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(snake_case ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' self.enable_attention_slicing(snake_case ) def _UpperCamelCase ( self : Dict ): '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) A__ : Optional[Any] = torch.device("""cuda""" ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(snake_case , snake_case ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' if self.device != torch.device("""meta""" ) or not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(snake_case , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__( self : str , snake_case : Union[str, List[str]] , snake_case : Union[torch.FloatTensor, PIL.Image.Image] , snake_case : str , snake_case : int = 512 , snake_case : int = 512 , snake_case : int = 50 , snake_case : float = 7.5 , snake_case : Optional[Union[str, List[str]]] = None , snake_case : Optional[int] = 1 , snake_case : float = 0.0 , snake_case : Optional[torch.Generator] = None , snake_case : Optional[torch.FloatTensor] = None , snake_case : Optional[str] = "pil" , snake_case : bool = True , snake_case : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , snake_case : int = 1 , **snake_case : Optional[Any] , ): '''simple docstring''' A__ : Optional[int] = self.segmentation_processor( text=[text] , images=[image] , padding="""max_length""" , return_tensors="""pt""" ).to(self.device ) A__ : List[str] = self.segmentation_model(**snake_case ) A__ : Union[str, Any] = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() A__ : Tuple = self.numpy_to_pil(snake_case )[0].resize(image.size ) # Run inpainting pipeline with the generated mask A__ : Dict = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=snake_case , image=snake_case , mask_image=snake_case , height=snake_case , width=snake_case , num_inference_steps=snake_case , guidance_scale=snake_case , negative_prompt=snake_case , num_images_per_prompt=snake_case , eta=snake_case , generator=snake_case , latents=snake_case , output_type=snake_case , return_dict=snake_case , callback=snake_case , callback_steps=snake_case , )
362
"""simple docstring""" import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py A_ = '''src/diffusers''' A_ = '''.''' # This is to make sure the diffusers module imported is the one in the repo. A_ = importlib.util.spec_from_file_location( '''diffusers''', os.path.join(DIFFUSERS_PATH, '''__init__.py'''), submodule_search_locations=[DIFFUSERS_PATH], ) A_ = spec.loader.load_module() def _lowerCAmelCase ( UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : Optional[Any] ) ->Any: return line.startswith(UpperCAmelCase__ ) or len(UpperCAmelCase__ ) <= 1 or re.search(R"""^\s*\)(\s*->.*:|:)\s*$""", UpperCAmelCase__ ) is not None def _lowerCAmelCase ( UpperCAmelCase__ : List[str] ) ->Union[str, Any]: A__ : Any = object_name.split(""".""" ) A__ : int = 0 # First let's find the module where our object lives. A__ : str = parts[i] while i < len(UpperCAmelCase__ ) and not os.path.isfile(os.path.join(UpperCAmelCase__, f'{module}.py' ) ): i += 1 if i < len(UpperCAmelCase__ ): A__ : Union[str, Any] = os.path.join(UpperCAmelCase__, parts[i] ) if i >= len(UpperCAmelCase__ ): raise ValueError(f'`object_name` should begin with the name of a module of diffusers but got {object_name}.' ) with open(os.path.join(UpperCAmelCase__, f'{module}.py' ), """r""", encoding="""utf-8""", newline="""\n""" ) as f: A__ : List[Any] = f.readlines() # Now let's find the class / func in the code! A__ : Optional[Any] = """""" A__ : Any = 0 for name in parts[i + 1 :]: while ( line_index < len(UpperCAmelCase__ ) and re.search(Rf'^{indent}(class|def)\s+{name}(\(|\:)', lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(UpperCAmelCase__ ): raise ValueError(f' {object_name} does not match any function or class in {module}.' ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). A__ : List[Any] = line_index while line_index < len(UpperCAmelCase__ ) and _should_continue(lines[line_index], UpperCAmelCase__ ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 A__ : List[Any] = lines[start_index:line_index] return "".join(UpperCAmelCase__ ) A_ = re.compile(r'''^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)''') A_ = re.compile(r'''^\s*(\S+)->(\S+)(\s+.*|$)''') A_ = re.compile(r'''<FILL\s+[^>]*>''') def _lowerCAmelCase ( UpperCAmelCase__ : List[str] ) ->Optional[Any]: A__ : Dict = code.split("""\n""" ) A__ : List[Any] = 0 while idx < len(UpperCAmelCase__ ) and len(lines[idx] ) == 0: idx += 1 if idx < len(UpperCAmelCase__ ): return re.search(R"""^(\s*)\S""", lines[idx] ).groups()[0] return "" def _lowerCAmelCase ( UpperCAmelCase__ : Optional[Any] ) ->int: A__ : str = len(get_indent(UpperCAmelCase__ ) ) > 0 if has_indent: A__ : Union[str, Any] = f'class Bla:\n{code}' A__ : Optional[Any] = black.Mode(target_versions={black.TargetVersion.PYaa}, line_length=1_1_9, preview=UpperCAmelCase__ ) A__ : Tuple = black.format_str(UpperCAmelCase__, mode=UpperCAmelCase__ ) A__ , A__ : List[Any] = style_docstrings_in_code(UpperCAmelCase__ ) return result[len("""class Bla:\n""" ) :] if has_indent else result def _lowerCAmelCase ( UpperCAmelCase__ : Any, UpperCAmelCase__ : Dict=False ) ->List[Any]: with open(UpperCAmelCase__, """r""", encoding="""utf-8""", newline="""\n""" ) as f: A__ : int = f.readlines() A__ : Dict = [] A__ : List[str] = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(UpperCAmelCase__ ): A__ : Dict = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. A__ , A__ , A__ : Dict = search.groups() A__ : Tuple = find_code_in_diffusers(UpperCAmelCase__ ) A__ : int = get_indent(UpperCAmelCase__ ) A__ : List[str] = line_index + 1 if indent == theoretical_indent else line_index + 2 A__ : Tuple = theoretical_indent A__ : Optional[Any] = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. A__ : Tuple = True while line_index < len(UpperCAmelCase__ ) and should_continue: line_index += 1 if line_index >= len(UpperCAmelCase__ ): break A__ : Optional[int] = lines[line_index] A__ : Tuple = _should_continue(UpperCAmelCase__, UpperCAmelCase__ ) and re.search(f'^{indent}# End copy', UpperCAmelCase__ ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 A__ : Dict = lines[start_index:line_index] A__ : Tuple = """""".join(UpperCAmelCase__ ) # Remove any nested `Copied from` comments to avoid circular copies A__ : Optional[int] = [line for line in theoretical_code.split("""\n""" ) if _re_copy_warning.search(UpperCAmelCase__ ) is None] A__ : Optional[Any] = """\n""".join(UpperCAmelCase__ ) # Before comparing, use the `replace_pattern` on the original code. if len(UpperCAmelCase__ ) > 0: A__ : int = replace_pattern.replace("""with""", """""" ).split(""",""" ) A__ : List[Any] = [_re_replace_pattern.search(UpperCAmelCase__ ) for p in patterns] for pattern in patterns: if pattern is None: continue A__ , A__ , A__ : Union[str, Any] = pattern.groups() A__ : Union[str, Any] = re.sub(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) if option.strip() == "all-casing": A__ : List[Any] = re.sub(obja.lower(), obja.lower(), UpperCAmelCase__ ) A__ : Tuple = re.sub(obja.upper(), obja.upper(), UpperCAmelCase__ ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line A__ : Optional[int] = blackify(lines[start_index - 1] + theoretical_code ) A__ : List[Any] = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: A__ : List[Any] = lines[:start_index] + [theoretical_code] + lines[line_index:] A__ : Tuple = start_index + 1 if overwrite and len(UpperCAmelCase__ ) > 0: # Warn the user a file has been modified. print(f'Detected changes, rewriting {filename}.' ) with open(UpperCAmelCase__, """w""", encoding="""utf-8""", newline="""\n""" ) as f: f.writelines(UpperCAmelCase__ ) return diffs def _lowerCAmelCase ( UpperCAmelCase__ : bool = False ) ->Any: A__ : Dict = glob.glob(os.path.join(UpperCAmelCase__, """**/*.py""" ), recursive=UpperCAmelCase__ ) A__ : str = [] for filename in all_files: A__ : Any = is_copy_consistent(UpperCAmelCase__, UpperCAmelCase__ ) diffs += [f'- {filename}: copy does not match {d[0]} at line {d[1]}' for d in new_diffs] if not overwrite and len(UpperCAmelCase__ ) > 0: A__ : Any = """\n""".join(UpperCAmelCase__ ) raise Exception( """Found the following copy inconsistencies:\n""" + diff + """\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.""" ) if __name__ == "__main__": A_ = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') A_ = parser.parse_args() check_copies(args.fix_and_overwrite)
296
0
"""simple docstring""" from math import isclose, sqrt def _lowerCAmelCase ( UpperCAmelCase__ : float, UpperCAmelCase__ : float, UpperCAmelCase__ : float ) ->tuple[float, float, float]: A__ : List[Any] = point_y / 4 / point_x A__ : Any = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) A__ : str = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) A__ : Dict = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 A__ : Optional[int] = outgoing_gradient**2 + 4 A__ : List[Any] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) A__ : Any = (point_y - outgoing_gradient * point_x) ** 2 - 1_0_0 A__ : Dict = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) A__ : List[str] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point A__ : int = x_minus if isclose(UpperCAmelCase__, UpperCAmelCase__ ) else x_plus A__ : Any = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def _lowerCAmelCase ( UpperCAmelCase__ : float = 1.4, UpperCAmelCase__ : float = -9.6 ) ->int: A__ : int = 0 A__ : float = first_x_coord A__ : float = first_y_coord A__ : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): A__ : Optional[Any] = next_point(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F'{solution() = }')
363
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) A_ = { '''configuration_llama''': ['''LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LlamaConfig'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ['''LlamaTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ['''LlamaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''LlamaForCausalLM''', '''LlamaModel''', '''LlamaPreTrainedModel''', '''LlamaForSequenceClassification''', ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
296
0
"""simple docstring""" import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint A_ = { '''169M''': 12, '''430M''': 24, '''1B5''': 24, '''3B''': 32, '''7B''': 32, '''14B''': 40, } A_ = { '''169M''': 768, '''430M''': 1024, '''1B5''': 2048, '''3B''': 2560, '''7B''': 4096, '''14B''': 5120, } def _lowerCAmelCase ( UpperCAmelCase__ : int ) ->List[Any]: A__ : Tuple = list(state_dict.keys() ) for name in state_dict_keys: A__ : Optional[Any] = state_dict.pop(UpperCAmelCase__ ) # emb -> embedding if name.startswith("""emb.""" ): A__ : Optional[Any] = name.replace("""emb.""", """embeddings.""" ) # ln_0 -> pre_ln (only present at block 0) if name.startswith("""blocks.0.ln0""" ): A__ : List[Any] = name.replace("""blocks.0.ln0""", """blocks.0.pre_ln""" ) # att -> attention A__ : Union[str, Any] = re.sub(R"""blocks\.(\d+)\.att""", R"""blocks.\1.attention""", UpperCAmelCase__ ) # ffn -> feed_forward A__ : int = re.sub(R"""blocks\.(\d+)\.ffn""", R"""blocks.\1.feed_forward""", UpperCAmelCase__ ) # time_mix_k -> time_mix_key and reshape if name.endswith(""".time_mix_k""" ): A__ : List[str] = name.replace(""".time_mix_k""", """.time_mix_key""" ) # time_mix_v -> time_mix_value and reshape if name.endswith(""".time_mix_v""" ): A__ : int = name.replace(""".time_mix_v""", """.time_mix_value""" ) # time_mix_r -> time_mix_key and reshape if name.endswith(""".time_mix_r""" ): A__ : int = name.replace(""".time_mix_r""", """.time_mix_receptance""" ) if name != "head.weight": A__ : Union[str, Any] = """rwkv.""" + name A__ : Optional[int] = weight return state_dict def _lowerCAmelCase ( UpperCAmelCase__ : Dict, UpperCAmelCase__ : int, UpperCAmelCase__ : List[Any], UpperCAmelCase__ : Any=None, UpperCAmelCase__ : int=None, UpperCAmelCase__ : Dict=False, UpperCAmelCase__ : Union[str, Any]=None ) ->Any: # 1. If possible, build the tokenizer. if tokenizer_file is None: print("""No `--tokenizer_file` provided, we will use the default tokenizer.""" ) A__ : str = 5_0_2_7_7 A__ : Optional[Any] = AutoTokenizer.from_pretrained("""EleutherAI/gpt-neox-20b""" ) else: A__ : Optional[int] = PreTrainedTokenizerFast(tokenizer_file=UpperCAmelCase__ ) A__ : List[Any] = len(UpperCAmelCase__ ) tokenizer.save_pretrained(UpperCAmelCase__ ) # 2. Build the config A__ : Optional[int] = list(NUM_HIDDEN_LAYERS_MAPPING.keys() ) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: A__ : int = candidate break if size is None: raise ValueError("""Could not infer the size, please provide it with the `--size` argument.""" ) if size not in possible_sizes: raise ValueError(f'`size` should be one of {possible_sizes}, got {size}.' ) A__ : int = RwkvConfig( vocab_size=UpperCAmelCase__, num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size], hidden_size=HIDEN_SIZE_MAPPING[size], ) config.save_pretrained(UpperCAmelCase__ ) # 3. Download model file then convert state_dict A__ : Optional[Any] = hf_hub_download(UpperCAmelCase__, UpperCAmelCase__ ) A__ : Dict = torch.load(UpperCAmelCase__, map_location="""cpu""" ) A__ : List[str] = convert_state_dict(UpperCAmelCase__ ) # 4. Split in shards and save A__ : str = shard_checkpoint(UpperCAmelCase__ ) for shard_file, shard in shards.items(): torch.save(UpperCAmelCase__, os.path.join(UpperCAmelCase__, UpperCAmelCase__ ) ) if index is not None: A__ : List[Any] = os.path.join(UpperCAmelCase__, UpperCAmelCase__ ) # Save the index as well with open(UpperCAmelCase__, """w""", encoding="""utf-8""" ) as f: A__ : Dict = json.dumps(UpperCAmelCase__, indent=2, sort_keys=UpperCAmelCase__ ) + """\n""" f.write(UpperCAmelCase__ ) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( """Cleaning up shards. This may error with an OOM error, it this is the case don't worry you still have converted the model.""" ) A__ : Optional[Any] = list(shards.keys() ) del state_dict del shards gc.collect() for shard_file in shard_files: A__ : Union[str, Any] = torch.load(os.path.join(UpperCAmelCase__, UpperCAmelCase__ ) ) torch.save({k: v.cpu().clone() for k, v in state_dict.items()}, os.path.join(UpperCAmelCase__, UpperCAmelCase__ ) ) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError("""Please provide a `model_name` to push the model to the Hub.""" ) A__ : Union[str, Any] = AutoModelForCausalLM.from_pretrained(UpperCAmelCase__ ) model.push_to_hub(UpperCAmelCase__, max_shard_size="""2GB""" ) tokenizer.push_to_hub(UpperCAmelCase__ ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--repo_id''', default=None, type=str, required=True, help='''Repo ID from which to pull the checkpoint.''' ) parser.add_argument( '''--checkpoint_file''', default=None, type=str, required=True, help='''Name of the checkpoint file in the repo.''' ) parser.add_argument( '''--output_dir''', default=None, type=str, required=True, help='''Where to save the converted model.''' ) parser.add_argument( '''--tokenizer_file''', default=None, type=str, help='''Path to the tokenizer file to use (if not provided, only the model is converted).''', ) parser.add_argument( '''--size''', default=None, type=str, help='''Size of the model. Will be inferred from the `checkpoint_file` if not passed.''', ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Push to the Hub the converted model.''', ) parser.add_argument( '''--model_name''', default=None, type=str, help='''Name of the pushed model on the Hub, including the username / organization.''', ) A_ = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
364
"""simple docstring""" import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels A_ = object() # For specifying empty leaf dict `{}` A_ = object() def _lowerCAmelCase ( UpperCAmelCase__ : Tuple, UpperCAmelCase__ : List[Any] ) ->Dict: A__ : Union[str, Any] = tuple((re.compile(x + """$""" ) for x in qs) ) for i in range(len(UpperCAmelCase__ ) - len(UpperCAmelCase__ ) + 1 ): A__ : Optional[Any] = [x.match(UpperCAmelCase__ ) for x, y in zip(UpperCAmelCase__, ks[i:] )] if matches and all(UpperCAmelCase__ ): return True return False def _lowerCAmelCase ( UpperCAmelCase__ : List[Any] ) ->Dict: def replace(UpperCAmelCase__ : int, UpperCAmelCase__ : List[str] ): for rule, replacement in rules: if _match(UpperCAmelCase__, UpperCAmelCase__ ): return replacement return val return replace def _lowerCAmelCase ( ) ->Tuple: return [ # embeddings (("transformer", "wpe", "embedding"), P("""mp""", UpperCAmelCase__ )), (("transformer", "wte", "embedding"), P("""mp""", UpperCAmelCase__ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(UpperCAmelCase__, """mp""" )), (("attention", "out_proj", "kernel"), P("""mp""", UpperCAmelCase__ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(UpperCAmelCase__, """mp""" )), (("mlp", "c_fc", "bias"), P("""mp""" )), (("mlp", "c_proj", "kernel"), P("""mp""", UpperCAmelCase__ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def _lowerCAmelCase ( UpperCAmelCase__ : Tuple ) ->Any: A__ : Union[str, Any] = _get_partition_rules() A__ : int = _replacement_rules(UpperCAmelCase__ ) A__ : Tuple = {k: _unmatched for k in flatten_dict(UpperCAmelCase__ )} A__ : Optional[int] = {k: replace(UpperCAmelCase__, UpperCAmelCase__ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(UpperCAmelCase__ ) )
296
0
"""simple docstring""" import math def _lowerCAmelCase ( UpperCAmelCase__ : list, UpperCAmelCase__ : int ) ->int: A__ : Any = len(UpperCAmelCase__ ) A__ : Optional[int] = int(math.floor(math.sqrt(UpperCAmelCase__ ) ) ) A__ : int = 0 while arr[min(UpperCAmelCase__, UpperCAmelCase__ ) - 1] < x: A__ : int = step step += int(math.floor(math.sqrt(UpperCAmelCase__ ) ) ) if prev >= n: return -1 while arr[prev] < x: A__ : Union[str, Any] = prev + 1 if prev == min(UpperCAmelCase__, UpperCAmelCase__ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": A_ = input('''Enter numbers separated by a comma:\n''').strip() A_ = [int(item) for item in user_input.split(''',''')] A_ = int(input('''Enter the number to be searched:\n''')) A_ = jump_search(arr, x) if res == -1: print('''Number not found!''') else: print(F'Number {x} is at index {res}')
365
"""simple docstring""" import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class __SCREAMING_SNAKE_CASE : def __init__( self : List[str] , snake_case : Tuple , snake_case : List[str]=2 , snake_case : List[str]=8 , snake_case : List[Any]=True , snake_case : Optional[Any]=True , snake_case : List[Any]=True , snake_case : Dict=True , snake_case : Tuple=99 , snake_case : Dict=16 , snake_case : Dict=5 , snake_case : int=2 , snake_case : Any=36 , snake_case : str="gelu" , snake_case : Dict=0.0 , snake_case : List[Any]=0.0 , snake_case : int=512 , snake_case : List[Any]=16 , snake_case : Tuple=2 , snake_case : Any=0.02 , snake_case : Optional[Any]=3 , snake_case : List[Any]=4 , snake_case : str=None , ): '''simple docstring''' A__ : Union[str, Any] = parent A__ : Optional[Any] = batch_size A__ : Dict = seq_length A__ : str = is_training A__ : Tuple = use_input_mask A__ : Dict = use_token_type_ids A__ : Dict = use_labels A__ : int = vocab_size A__ : List[str] = hidden_size A__ : Union[str, Any] = num_hidden_layers A__ : int = num_attention_heads A__ : List[str] = intermediate_size A__ : int = hidden_act A__ : str = hidden_dropout_prob A__ : Tuple = attention_probs_dropout_prob A__ : Any = max_position_embeddings A__ : Optional[int] = type_vocab_size A__ : int = type_sequence_label_size A__ : Optional[Any] = initializer_range A__ : int = num_labels A__ : Optional[int] = num_choices A__ : Optional[int] = scope def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Any = None if self.use_input_mask: A__ : Any = random_attention_mask([self.batch_size, self.seq_length] ) A__ : Optional[int] = None if self.use_token_type_ids: A__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A__ : Dict = None A__ : List[str] = None A__ : Union[str, Any] = None if self.use_labels: A__ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : Any = ids_tensor([self.batch_size] , self.num_choices ) A__ : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case , initializer_range=self.initializer_range , ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Any = self.get_config() A__ : List[str] = 300 return config def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) : Tuple = self.prepare_config_and_inputs() A__ : List[str] = True A__ : List[str] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) A__ : int = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def _UpperCamelCase ( self : Any , snake_case : Any , snake_case : Tuple , snake_case : Any , snake_case : Optional[int] , snake_case : Optional[int] , snake_case : Optional[int] , snake_case : Dict ): '''simple docstring''' A__ : List[str] = MraModel(config=snake_case ) model.to(snake_case ) model.eval() A__ : Dict = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case ) A__ : List[str] = model(snake_case , token_type_ids=snake_case ) A__ : Union[str, Any] = model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : Optional[Any] , snake_case : List[Any] , snake_case : Any , snake_case : Optional[Any] , snake_case : Union[str, Any] , snake_case : Tuple , snake_case : Dict , snake_case : str , snake_case : Dict , snake_case : str , ): '''simple docstring''' A__ : Dict = True A__ : Optional[Any] = MraModel(snake_case ) model.to(snake_case ) model.eval() A__ : Union[str, Any] = model( snake_case , attention_mask=snake_case , token_type_ids=snake_case , encoder_hidden_states=snake_case , encoder_attention_mask=snake_case , ) A__ : str = model( snake_case , attention_mask=snake_case , token_type_ids=snake_case , encoder_hidden_states=snake_case , ) A__ : Optional[int] = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : int , snake_case : Optional[Any] , snake_case : Optional[int] , snake_case : int , snake_case : str , snake_case : Union[str, Any] , snake_case : Dict , snake_case : List[str] ): '''simple docstring''' A__ : Union[str, Any] = MraForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() A__ : List[Any] = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Dict , snake_case : Dict , snake_case : Dict , snake_case : List[str] , snake_case : List[str] , snake_case : Tuple , snake_case : Union[str, Any] ): '''simple docstring''' A__ : Dict = MraForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() A__ : str = model( 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 _UpperCamelCase ( self : Tuple , snake_case : List[Any] , snake_case : Optional[Any] , snake_case : Optional[Any] , snake_case : List[str] , snake_case : Optional[int] , snake_case : List[str] , snake_case : Union[str, Any] ): '''simple docstring''' A__ : str = self.num_labels A__ : Optional[Any] = MraForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : str = model(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 _UpperCamelCase ( self : Union[str, Any] , snake_case : Dict , snake_case : str , snake_case : List[Any] , snake_case : Any , snake_case : Dict , snake_case : Tuple , snake_case : Optional[Any] ): '''simple docstring''' A__ : str = self.num_labels A__ : Union[str, Any] = MraForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() A__ : str = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self : Tuple , snake_case : Optional[Any] , snake_case : Optional[int] , snake_case : int , snake_case : Optional[Any] , snake_case : List[str] , snake_case : Dict , snake_case : Optional[Any] ): '''simple docstring''' A__ : List[str] = self.num_choices A__ : str = MraForMultipleChoice(config=snake_case ) model.to(snake_case ) model.eval() A__ : int = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : str = model( 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_choices) ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : List[str] = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) : Dict = config_and_inputs A__ : Optional[int] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( UpperCamelCase , unittest.TestCase ): snake_case_ = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = () def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Optional[Any] = MraModelTester(self ) A__ : List[str] = ConfigTester(self , config_class=snake_case , hidden_size=37 ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A__ : List[str] = type self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case ) @slow def _UpperCamelCase ( self : Any ): '''simple docstring''' for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ : str = MraModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @unittest.skip(reason="""MRA does not output attentions""" ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' return @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : str = MraModel.from_pretrained("""uw-madison/mra-base-512-4""" ) A__ : Any = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): A__ : List[Any] = model(snake_case )[0] A__ : List[Any] = torch.Size((1, 256, 768) ) self.assertEqual(output.shape , snake_case ) A__ : int = torch.tensor( [[[-0.0140, 0.0830, -0.0381], [0.1546, 0.1402, 0.0220], [0.1162, 0.0851, 0.0165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) ) @slow def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : Union[str, Any] = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-512-4""" ) A__ : Tuple = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): A__ : List[Any] = model(snake_case )[0] A__ : Dict = 5_0265 A__ : List[str] = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape , snake_case ) A__ : List[Any] = torch.tensor( [[[9.2595, -3.6038, 11.8819], [9.3869, -3.2693, 11.0956], [11.8524, -3.4938, 13.1210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) ) @slow def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : Any = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-4096-8-d3""" ) A__ : List[Any] = torch.arange(4096 ).unsqueeze(0 ) with torch.no_grad(): A__ : List[Any] = model(snake_case )[0] A__ : Union[str, Any] = 5_0265 A__ : Optional[Any] = torch.Size((1, 4096, vocab_size) ) self.assertEqual(output.shape , snake_case ) A__ : Optional[int] = torch.tensor( [[[5.4789, -2.3564, 7.5064], [7.9067, -1.3369, 9.9668], [9.0712, -1.8106, 7.0380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) )
296
0
def _lowerCAmelCase ( UpperCAmelCase__ : int ) ->str: if isinstance(UpperCAmelCase__, UpperCAmelCase__ ): raise TypeError("""'float' object cannot be interpreted as an integer""" ) if isinstance(UpperCAmelCase__, UpperCAmelCase__ ): raise TypeError("""'str' object cannot be interpreted as an integer""" ) if num == 0: return "0b0" A__ : Optional[int] = False if num < 0: A__ : int = True A__ : int = -num A__ : list[int] = [] while num > 0: binary.insert(0, num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(UpperCAmelCase__ ) for e in binary ) return "0b" + "".join(str(UpperCAmelCase__ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
366
"""simple docstring""" from sklearn.metrics import mean_squared_error import datasets A_ = '''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' A_ = '''\ Mean Squared Error(MSE) is the average of the square of difference between the predicted and actual values. ''' A_ = ''' Args: predictions: array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. references: array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. sample_weight: array-like of shape (n_samples,), default=None Sample weights. multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average" Defines aggregating of multiple output values. Array-like value defines weights used to average errors. "raw_values" : Returns a full set of errors in case of multioutput input. "uniform_average" : Errors of all outputs are averaged with uniform weight. squared : bool, default=True If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value. Returns: mse : mean squared error. Examples: >>> mse_metric = datasets.load_metric("mse") >>> predictions = [2.5, 0.0, 2, 8] >>> references = [3, -0.5, 2, 7] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {\'mse\': 0.375} >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False) >>> print(rmse_result) {\'mse\': 0.6123724356957945} If you\'re using multi-dimensional lists, then set the config as follows : >>> mse_metric = datasets.load_metric("mse", "multilist") >>> predictions = [[0.5, 1], [-1, 1], [7, -6]] >>> references = [[0, 2], [-1, 2], [8, -5]] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {\'mse\': 0.7083333333333334} >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\') >>> print(results) # doctest: +NORMALIZE_WHITESPACE {\'mse\': array([0.41666667, 1. ])} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE ( datasets.Metric ): def _UpperCamelCase ( self : Dict ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html""" ] , ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value("""float""" ) ), "references": datasets.Sequence(datasets.Value("""float""" ) ), } else: return { "predictions": datasets.Value("""float""" ), "references": datasets.Value("""float""" ), } def _UpperCamelCase ( self : List[str] , snake_case : Dict , snake_case : List[Any] , snake_case : List[str]=None , snake_case : List[Any]="uniform_average" , snake_case : int=True ): '''simple docstring''' A__ : Optional[int] = mean_squared_error( snake_case , snake_case , sample_weight=snake_case , multioutput=snake_case , squared=snake_case ) return {"mse": mse}
296
0
"""simple docstring""" from PIL import Image def _lowerCAmelCase ( UpperCAmelCase__ : Image, UpperCAmelCase__ : float ) ->Image: def brightness(UpperCAmelCase__ : int ) -> float: return 1_2_8 + level + (c - 1_2_8) if not -255.0 <= level <= 255.0: raise ValueError("""level must be between -255.0 (black) and 255.0 (white)""" ) return img.point(UpperCAmelCase__ ) if __name__ == "__main__": # Load image with Image.open('''image_data/lena.jpg''') as img: # Change brightness to 100 A_ = change_brightness(img, 100) brigt_img.save('''image_data/lena_brightness.png''', format='''png''')
367
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging A_ = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): def __init__( self : Optional[int] , snake_case : List[str]=None , **snake_case : Any ): '''simple docstring''' warnings.warn( """`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` """ """instead.""" , snake_case , ) super().__init__(args=snake_case , **snake_case )
296
0
import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): def __init__( self : Any , snake_case : Any , snake_case : Any , snake_case : Any=1024 , snake_case : Optional[int]=1024 , snake_case : Optional[Any]=3.6 ): '''simple docstring''' A__ : Optional[int] = tokenizer A__ : Optional[int] = tokenizer.bos_token_id A__ : Dict = dataset A__ : Optional[int] = seq_length A__ : Union[str, Any] = seq_length * chars_per_token * num_of_sequences def __iter__( self : Any ): '''simple docstring''' A__ : int = iter(self.dataset ) A__ : str = True while more_examples: A__ : Any = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(snake_case )["""content"""] ) buffer_len += len(buffer[-1] ) except StopIteration: A__ : str = False break A__ : Optional[Any] = tokenizer(snake_case , truncation=snake_case )["""input_ids"""] A__ : Optional[Any] = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(snake_case ) , self.seq_length ): A__ : int = all_token_ids[i : i + self.seq_length] if len(snake_case ) == self.seq_length: yield torch.tensor(snake_case ) def _lowerCAmelCase ( UpperCAmelCase__ : Optional[Any] ) ->Dict: A__ : List[Any] = {"""streaming""": True} A__ : Optional[int] = load_dataset(args.dataset_name, split="""train""", **UpperCAmelCase__ ) A__ : str = ConstantLengthDataset(UpperCAmelCase__, UpperCAmelCase__, seq_length=args.seq_length ) A__ : Union[str, Any] = DataLoader(UpperCAmelCase__, batch_size=args.batch_size ) return eval_dataloader def _lowerCAmelCase ( UpperCAmelCase__ : Union[str, Any] ) ->int: model.eval() A__ : Tuple = [] for step, batch in enumerate(UpperCAmelCase__ ): with torch.no_grad(): A__ : List[str] = model(UpperCAmelCase__, labels=UpperCAmelCase__ ) A__ : Dict = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(UpperCAmelCase__ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break A__ : Union[str, Any] = torch.mean(torch.cat(UpperCAmelCase__ ) ) try: A__ : Union[str, Any] = torch.exp(UpperCAmelCase__ ) except OverflowError: A__ : Union[str, Any] = float("""inf""" ) return loss.item(), perplexity.item() # Setup Accelerator A_ = Accelerator() # Parse configuration A_ = HfArgumentParser(EvaluationArguments) A_ = parser.parse_args() set_seed(args.seed) # Logging A_ = logging.getLogger(__name__) logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) # Load model and tokenizer A_ = AutoModelForCausalLM.from_pretrained(args.model_ckpt) A_ = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader A_ = create_dataloader(args) # Prepare everything with our `accelerator`. A_ , A_ = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('''Evaluating and saving model after training''') A_ , A_ = evaluate(args) logger.info(F'loss/eval: {eval_loss}, perplexity: {perplexity}')
368
"""simple docstring""" import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch A_ = random.Random() def _lowerCAmelCase ( UpperCAmelCase__ : Dict, UpperCAmelCase__ : Tuple=1.0, UpperCAmelCase__ : Optional[int]=None, UpperCAmelCase__ : str=None ) ->Union[str, Any]: if rng is None: A__ : Optional[int] = global_rng A__ : Optional[Any] = [] 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 __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : Union[str, Any] , snake_case : str , snake_case : List[str]=7 , snake_case : str=400 , snake_case : Optional[Any]=2000 , snake_case : Union[str, Any]=10 , snake_case : str=160 , snake_case : List[str]=8 , snake_case : List[Any]=0.0 , snake_case : Optional[Any]=4000 , snake_case : Any=False , snake_case : int=True , ): '''simple docstring''' A__ : Any = parent A__ : str = batch_size A__ : List[str] = min_seq_length A__ : Dict = max_seq_length A__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) A__ : Dict = padding_value A__ : Optional[Any] = sampling_rate A__ : Any = return_attention_mask A__ : Optional[int] = do_normalize A__ : Tuple = feature_size A__ : Optional[Any] = chunk_length A__ : Union[str, Any] = hop_length def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _UpperCamelCase ( self : Union[str, Any] , snake_case : Dict=False , snake_case : Optional[Any]=False ): '''simple docstring''' def _flatten(snake_case : Dict ): return list(itertools.chain(*snake_case ) ) if equal_length: A__ : Dict = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size A__ : Optional[int] = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: A__ : List[str] = [np.asarray(snake_case ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __SCREAMING_SNAKE_CASE ( UpperCamelCase , unittest.TestCase ): snake_case_ = WhisperFeatureExtractor if is_speech_available() else None def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : str = WhisperFeatureExtractionTester(self ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Any = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: A__ : List[Any] = feat_extract_first.save_pretrained(snake_case )[0] check_json_file_has_correct_format(snake_case ) A__ : Union[str, Any] = self.feature_extraction_class.from_pretrained(snake_case ) A__ : str = feat_extract_first.to_dict() A__ : Union[str, Any] = feat_extract_second.to_dict() A__ : List[Any] = feat_extract_first.mel_filters A__ : Optional[Any] = feat_extract_second.mel_filters self.assertTrue(np.allclose(snake_case , snake_case ) ) self.assertEqual(snake_case , snake_case ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Any = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: A__ : Any = os.path.join(snake_case , """feat_extract.json""" ) feat_extract_first.to_json_file(snake_case ) A__ : int = self.feature_extraction_class.from_json_file(snake_case ) A__ : Dict = feat_extract_first.to_dict() A__ : str = feat_extract_second.to_dict() A__ : str = feat_extract_first.mel_filters A__ : Dict = feat_extract_second.mel_filters self.assertTrue(np.allclose(snake_case , snake_case ) ) self.assertEqual(snake_case , snake_case ) def _UpperCamelCase ( self : Any ): '''simple docstring''' A__ : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 A__ : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] A__ : Union[str, Any] = [np.asarray(snake_case ) for speech_input in speech_inputs] # Test feature size A__ : Dict = feature_extractor(snake_case , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input A__ : str = feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features A__ : Optional[int] = feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(snake_case , snake_case , atol=1e-3 ) ) # Test batched A__ : List[str] = feature_extractor(snake_case , return_tensors="""np""" ).input_features A__ : List[str] = feature_extractor(snake_case , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(snake_case , snake_case ): self.assertTrue(np.allclose(snake_case , snake_case , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. A__ : Tuple = [floats_list((1, x) )[0] for x in (800, 800, 800)] A__ : str = np.asarray(snake_case ) A__ : List[str] = feature_extractor(snake_case , return_tensors="""np""" ).input_features A__ : Optional[int] = feature_extractor(snake_case , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(snake_case , snake_case ): self.assertTrue(np.allclose(snake_case , snake_case , atol=1e-3 ) ) # Test truncation required A__ : Optional[Any] = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] A__ : Union[str, Any] = [np.asarray(snake_case ) for speech_input in speech_inputs] A__ : Union[str, Any] = [x[: feature_extractor.n_samples] for x in speech_inputs] A__ : str = [np.asarray(snake_case ) for speech_input in speech_inputs_truncated] A__ : Optional[int] = feature_extractor(snake_case , return_tensors="""np""" ).input_features A__ : str = feature_extractor(snake_case , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(snake_case , snake_case ): self.assertTrue(np.allclose(snake_case , snake_case , atol=1e-3 ) ) def _UpperCamelCase ( self : str ): '''simple docstring''' import torch A__ : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A__ : List[str] = np.random.rand(100 , 32 ).astype(np.floataa ) A__ : Tuple = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: A__ : Optional[Any] = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) A__ : Optional[int] = feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Optional[int] ): '''simple docstring''' A__ : int = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech A__ : Union[str, Any] = ds.sort("""id""" ).select(range(snake_case ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : str = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on A__ : Optional[Any] = self._load_datasamples(1 ) A__ : Union[str, Any] = WhisperFeatureExtractor() A__ : List[str] = feature_extractor(snake_case , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 80, 3000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , snake_case , atol=1e-4 ) ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) A__ : Union[str, Any] = self._load_datasamples(1 )[0] A__ : Any = ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535 # Rescale to [0, 65535] to show issue A__ : str = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=snake_case )[0] self.assertTrue(np.all(np.mean(snake_case ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(snake_case ) - 1 ) < 1e-3 ) )
296
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices A_ = logging.get_logger(__name__) A_ = { '''shi-labs/nat-mini-in1k-224''': '''https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json''', # See all Nat models at https://huggingface.co/models?filter=nat } class __SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase ): snake_case_ = 'nat' snake_case_ = { 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self : Union[str, Any] , snake_case : Any=4 , snake_case : Any=3 , snake_case : Optional[Any]=64 , snake_case : Any=[3, 4, 6, 5] , snake_case : List[str]=[2, 4, 8, 16] , snake_case : str=7 , snake_case : List[Any]=3.0 , snake_case : Optional[Any]=True , snake_case : Any=0.0 , snake_case : int=0.0 , snake_case : int=0.1 , snake_case : int="gelu" , snake_case : Optional[Any]=0.02 , snake_case : List[str]=1e-5 , snake_case : Tuple=0.0 , snake_case : Dict=None , snake_case : Tuple=None , **snake_case : Union[str, Any] , ): '''simple docstring''' super().__init__(**snake_case ) A__ : Optional[int] = patch_size A__ : Optional[int] = num_channels A__ : Dict = embed_dim A__ : str = depths A__ : Any = len(snake_case ) A__ : Tuple = num_heads A__ : Tuple = kernel_size A__ : int = mlp_ratio A__ : int = qkv_bias A__ : Any = hidden_dropout_prob A__ : List[str] = attention_probs_dropout_prob A__ : Any = drop_path_rate A__ : str = hidden_act A__ : Optional[int] = layer_norm_eps A__ : Dict = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model A__ : Optional[Any] = int(embed_dim * 2 ** (len(snake_case ) - 1) ) A__ : Tuple = layer_scale_init_value A__ : Optional[int] = ["""stem"""] + [F'stage{idx}' for idx in range(1 , len(snake_case ) + 1 )] A__ : Dict = get_aligned_output_features_output_indices( out_features=snake_case , out_indices=snake_case , stage_names=self.stage_names )
369
"""simple docstring""" import numpy as np class __SCREAMING_SNAKE_CASE : def __init__( self : List[str] ): '''simple docstring''' A__ : Optional[int] = (0, 0) A__ : Dict = None A__ : int = 0 A__ : str = 0 A__ : Optional[Any] = 0 def __eq__( self : str , snake_case : Optional[int] ): '''simple docstring''' return self.position == cell.position def _UpperCamelCase ( self : List[str] ): '''simple docstring''' print(self.position ) class __SCREAMING_SNAKE_CASE : def __init__( self : int , snake_case : Any=(5, 5) ): '''simple docstring''' A__ : Optional[int] = np.zeros(snake_case ) A__ : List[Any] = world_size[0] A__ : Dict = world_size[1] def _UpperCamelCase ( self : Any ): '''simple docstring''' print(self.w ) def _UpperCamelCase ( self : Optional[int] , snake_case : List[Any] ): '''simple docstring''' A__ : int = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] A__ : int = cell.position[0] A__ : str = cell.position[1] A__ : Any = [] for n in neughbour_cord: A__ : List[Any] = current_x + n[0] A__ : Tuple = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: A__ : List[Any] = Cell() A__ : str = (x, y) A__ : Optional[Any] = cell neighbours.append(snake_case ) return neighbours def _lowerCAmelCase ( UpperCAmelCase__ : List[str], UpperCAmelCase__ : Optional[Any], UpperCAmelCase__ : Dict ) ->Dict: A__ : Union[str, Any] = [] A__ : Optional[int] = [] _open.append(UpperCAmelCase__ ) while _open: A__ : List[Any] = np.argmin([n.f for n in _open] ) A__ : Union[str, Any] = _open[min_f] _closed.append(_open.pop(UpperCAmelCase__ ) ) if current == goal: break for n in world.get_neigbours(UpperCAmelCase__ ): for c in _closed: if c == n: continue A__ : Dict = current.g + 1 A__ , A__ : int = n.position A__ , A__ : Optional[int] = goal.position A__ : Union[str, Any] = (ya - ya) ** 2 + (xa - xa) ** 2 A__ : Optional[int] = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(UpperCAmelCase__ ) A__ : List[str] = [] while current.parent is not None: path.append(current.position ) A__ : Union[str, Any] = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": A_ = Gridworld() # Start position and goal A_ = Cell() A_ = (0, 0) A_ = Cell() A_ = (4, 4) print(F'path from {start.position} to {goal.position}') A_ = astar(world, start, goal) # Just for visual reasons. for i in s: A_ = 1 print(world.w)
296
0
"""simple docstring""" import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging A_ = logging.get_logger(__name__) def _lowerCAmelCase ( UpperCAmelCase__ : List[str]=None, UpperCAmelCase__ : Dict=None ) ->str: return field(default_factory=lambda: default, metadata=UpperCAmelCase__ ) @dataclass class __SCREAMING_SNAKE_CASE : snake_case_ = list_field( default=[] , metadata={ 'help': ( 'Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version' ' of all available models' ) } , ) snake_case_ = list_field( default=[8] , metadata={'help': 'List of batch sizes for which memory and time performance will be evaluated'} ) snake_case_ = list_field( default=[8, 32, 128, 512] , metadata={'help': 'List of sequence lengths for which memory and time performance will be evaluated'} , ) snake_case_ = field( default=UpperCamelCase , metadata={'help': 'Whether to benchmark inference of model. Inference can be disabled via --no-inference.'} , ) snake_case_ = field( default=UpperCamelCase , metadata={'help': 'Whether to run on available cuda devices. Cuda can be disabled via --no-cuda.'} , ) snake_case_ = field( default=UpperCamelCase , metadata={'help': 'Whether to run on available tpu devices. TPU can be disabled via --no-tpu.'} ) snake_case_ = field(default=UpperCamelCase , metadata={'help': 'Use FP16 to accelerate inference.'} ) snake_case_ = field(default=UpperCamelCase , metadata={'help': 'Benchmark training of model'} ) snake_case_ = field(default=UpperCamelCase , metadata={'help': 'Verbose memory tracing'} ) snake_case_ = field( default=UpperCamelCase , metadata={'help': 'Whether to perform speed measurements. Speed measurements can be disabled via --no-speed.'} , ) snake_case_ = field( default=UpperCamelCase , metadata={ 'help': 'Whether to perform memory measurements. Memory measurements can be disabled via --no-memory' } , ) snake_case_ = field(default=UpperCamelCase , metadata={'help': 'Trace memory line by line'} ) snake_case_ = field(default=UpperCamelCase , metadata={'help': 'Save result to a CSV file'} ) snake_case_ = field(default=UpperCamelCase , metadata={'help': 'Save all print statements in a log file'} ) snake_case_ = field(default=UpperCamelCase , metadata={'help': 'Whether to print environment information'} ) snake_case_ = field( default=UpperCamelCase , metadata={ 'help': ( 'Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use' ' multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled' ' for debugging / testing and on TPU.' ) } , ) snake_case_ = field( default=F"inference_time_{round(time() )}.csv" , metadata={'help': 'CSV filename used if saving time results to csv.'} , ) snake_case_ = field( default=F"inference_memory_{round(time() )}.csv" , metadata={'help': 'CSV filename used if saving memory results to csv.'} , ) snake_case_ = field( default=F"train_time_{round(time() )}.csv" , metadata={'help': 'CSV filename used if saving time results to csv for training.'} , ) snake_case_ = field( default=F"train_memory_{round(time() )}.csv" , metadata={'help': 'CSV filename used if saving memory results to csv for training.'} , ) snake_case_ = field( default=F"env_info_{round(time() )}.csv" , metadata={'help': 'CSV filename used if saving environment information.'} , ) snake_case_ = field( default=F"log_{round(time() )}.csv" , metadata={'help': 'Log filename used if print statements are saved in log.'} , ) snake_case_ = field(default=3 , metadata={'help': 'Times an experiment will be run.'} ) snake_case_ = field( default=UpperCamelCase , metadata={ 'help': ( 'Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain' ' model weights.' ) } , ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' warnings.warn( F'The class {self.__class__} is deprecated. Hugging Face Benchmarking utils' """ are deprecated in general and it is advised to use external Benchmarking libraries """ """ to benchmark Transformer models.""" , snake_case , ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return json.dumps(dataclasses.asdict(self ) , indent=2 ) @property def _UpperCamelCase ( self : int ): '''simple docstring''' if len(self.models ) <= 0: raise ValueError( """Please make sure you provide at least one model name / model identifier, *e.g.* `--models""" """ bert-base-cased` or `args.models = ['bert-base-cased'].""" ) return self.models @property def _UpperCamelCase ( self : Tuple ): '''simple docstring''' if not self.multi_process: return False elif self.is_tpu: logger.info("""Multiprocessing is currently not possible on TPU.""" ) return False else: return True
370
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) def _lowerCAmelCase ( UpperCAmelCase__ : Union[str, Any], UpperCAmelCase__ : Tuple=False ) ->str: A__ : Optional[int] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'blocks.{i}.norm1.weight', f'deit.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((f'blocks.{i}.norm1.bias', f'deit.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append((f'blocks.{i}.attn.proj.weight', f'deit.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append((f'blocks.{i}.attn.proj.bias', f'deit.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((f'blocks.{i}.norm2.weight', f'deit.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((f'blocks.{i}.norm2.bias', f'deit.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append((f'blocks.{i}.mlp.fc1.weight', f'deit.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((f'blocks.{i}.mlp.fc1.bias', f'deit.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((f'blocks.{i}.mlp.fc2.weight', f'deit.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((f'blocks.{i}.mlp.fc2.bias', f'deit.encoder.layer.{i}.output.dense.bias') ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """deit.embeddings.cls_token"""), ("""dist_token""", """deit.embeddings.distillation_token"""), ("""patch_embed.proj.weight""", """deit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """deit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """deit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" A__ : Optional[int] = [(pair[0], pair[1][4:]) if pair[1].startswith("""deit""" ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ("""norm.weight""", """deit.layernorm.weight"""), ("""norm.bias""", """deit.layernorm.bias"""), ("""head.weight""", """cls_classifier.weight"""), ("""head.bias""", """cls_classifier.bias"""), ("""head_dist.weight""", """distillation_classifier.weight"""), ("""head_dist.bias""", """distillation_classifier.bias"""), ] ) return rename_keys def _lowerCAmelCase ( UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : Tuple, UpperCAmelCase__ : List[Any]=False ) ->str: for i in range(config.num_hidden_layers ): if base_model: A__ : Any = """""" else: A__ : Tuple = """deit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) A__ : Any = state_dict.pop(f'blocks.{i}.attn.qkv.weight' ) A__ : Tuple = state_dict.pop(f'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict A__ : List[Any] = in_proj_weight[ : config.hidden_size, : ] A__ : str = in_proj_bias[: config.hidden_size] A__ : Any = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] A__ : Dict = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] A__ : Optional[Any] = in_proj_weight[ -config.hidden_size :, : ] A__ : Any = in_proj_bias[-config.hidden_size :] def _lowerCAmelCase ( UpperCAmelCase__ : List[Any], UpperCAmelCase__ : List[Any], UpperCAmelCase__ : Union[str, Any] ) ->Any: A__ : int = dct.pop(UpperCAmelCase__ ) A__ : Tuple = val def _lowerCAmelCase ( ) ->List[Any]: A__ : Optional[int] = """http://images.cocodataset.org/val2017/000000039769.jpg""" A__ : int = Image.open(requests.get(UpperCAmelCase__, stream=UpperCAmelCase__ ).raw ) return im @torch.no_grad() def _lowerCAmelCase ( UpperCAmelCase__ : Dict, UpperCAmelCase__ : Any ) ->Tuple: A__ : List[Any] = DeiTConfig() # all deit models have fine-tuned heads A__ : Tuple = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size A__ : str = 1_0_0_0 A__ : List[str] = """huggingface/label-files""" A__ : Dict = """imagenet-1k-id2label.json""" A__ : List[str] = json.load(open(hf_hub_download(UpperCAmelCase__, UpperCAmelCase__, repo_type="""dataset""" ), """r""" ) ) A__ : Dict = {int(UpperCAmelCase__ ): v for k, v in idalabel.items()} A__ : Optional[int] = idalabel A__ : Dict = {v: k for k, v in idalabel.items()} A__ : List[str] = int(deit_name[-6:-4] ) A__ : str = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith("""tiny""" ): A__ : List[str] = 1_9_2 A__ : int = 7_6_8 A__ : List[Any] = 1_2 A__ : Dict = 3 elif deit_name[9:].startswith("""small""" ): A__ : List[Any] = 3_8_4 A__ : List[str] = 1_5_3_6 A__ : Any = 1_2 A__ : Union[str, Any] = 6 if deit_name[9:].startswith("""base""" ): pass elif deit_name[4:].startswith("""large""" ): A__ : int = 1_0_2_4 A__ : str = 4_0_9_6 A__ : Any = 2_4 A__ : int = 1_6 # load original model from timm A__ : Dict = timm.create_model(UpperCAmelCase__, pretrained=UpperCAmelCase__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys A__ : Tuple = timm_model.state_dict() A__ : str = create_rename_keys(UpperCAmelCase__, UpperCAmelCase__ ) for src, dest in rename_keys: rename_key(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) read_in_q_k_v(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) # load HuggingFace model A__ : str = DeiTForImageClassificationWithTeacher(UpperCAmelCase__ ).eval() model.load_state_dict(UpperCAmelCase__ ) # Check outputs on an image, prepared by DeiTImageProcessor A__ : int = int( (2_5_6 / 2_2_4) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 A__ : Any = DeiTImageProcessor(size=UpperCAmelCase__, crop_size=config.image_size ) A__ : Union[str, Any] = image_processor(images=prepare_img(), return_tensors="""pt""" ) A__ : Optional[Any] = encoding["""pixel_values"""] A__ : Union[str, Any] = model(UpperCAmelCase__ ) A__ : Union[str, Any] = timm_model(UpperCAmelCase__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(UpperCAmelCase__, outputs.logits, atol=1e-3 ) Path(UpperCAmelCase__ ).mkdir(exist_ok=UpperCAmelCase__ ) print(f'Saving model {deit_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(UpperCAmelCase__ ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(UpperCAmelCase__ ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--deit_name''', default='''vit_deit_base_distilled_patch16_224''', type=str, help='''Name of the DeiT 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.''' ) A_ = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
296
0
"""simple docstring""" def _lowerCAmelCase ( UpperCAmelCase__ : int = 1_0_0_0_0_0_0 ) ->int: A__ : Optional[Any] = 1 A__ : List[Any] = 1 A__ : List[Any] = {1: 1} for inputa in range(2, UpperCAmelCase__ ): A__ : List[str] = 0 A__ : Optional[int] = inputa while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: A__ : List[str] = (3 * number) + 1 counter += 1 if inputa not in counters: A__ : str = counter if counter > pre_counter: A__ : str = inputa A__ : Tuple = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
371
"""simple docstring""" from __future__ import annotations import time from collections.abc import Sequence from random import randint from matplotlib import pyplot as plt def _lowerCAmelCase ( UpperCAmelCase__ : Sequence[float], UpperCAmelCase__ : int, UpperCAmelCase__ : int ) ->tuple[int | None, int | None, float]: if not arr: return None, None, 0 if low == high: return low, high, arr[low] A__ : Optional[int] = (low + high) // 2 A__ , A__ , A__ : List[Any] = max_subarray(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) A__ , A__ , A__ : Union[str, Any] = max_subarray(UpperCAmelCase__, mid + 1, UpperCAmelCase__ ) A__ , A__ , A__ : Union[str, Any] = max_cross_sum(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum return cross_left, cross_right, cross_sum def _lowerCAmelCase ( UpperCAmelCase__ : Sequence[float], UpperCAmelCase__ : int, UpperCAmelCase__ : int, UpperCAmelCase__ : int ) ->tuple[int, int, float]: A__ , A__ : Dict = float("""-inf""" ), -1 A__ , A__ : Optional[Any] = float("""-inf""" ), -1 A__ : int | float = 0 for i in range(UpperCAmelCase__, low - 1, -1 ): summ += arr[i] if summ > left_sum: A__ : Optional[int] = summ A__ : Union[str, Any] = i A__ : Optional[Any] = 0 for i in range(mid + 1, high + 1 ): summ += arr[i] if summ > right_sum: A__ : int = summ A__ : Union[str, Any] = i return max_left, max_right, (left_sum + right_sum) def _lowerCAmelCase ( UpperCAmelCase__ : int ) ->float: A__ : Union[str, Any] = [randint(1, UpperCAmelCase__ ) for _ in range(UpperCAmelCase__ )] A__ : Any = time.time() max_subarray(UpperCAmelCase__, 0, input_size - 1 ) A__ : List[Any] = time.time() return end - start def _lowerCAmelCase ( ) ->None: A__ : List[Any] = [1_0, 1_0_0, 1_0_0_0, 1_0_0_0_0, 5_0_0_0_0, 1_0_0_0_0_0, 2_0_0_0_0_0, 3_0_0_0_0_0, 4_0_0_0_0_0, 5_0_0_0_0_0] A__ : Any = [time_max_subarray(UpperCAmelCase__ ) for input_size in input_sizes] print("""No of Inputs\t\tTime Taken""" ) for input_size, runtime in zip(UpperCAmelCase__, UpperCAmelCase__ ): print(UpperCAmelCase__, """\t\t""", UpperCAmelCase__ ) plt.plot(UpperCAmelCase__, UpperCAmelCase__ ) plt.xlabel("""Number of Inputs""" ) plt.ylabel("""Time taken in seconds""" ) plt.show() if __name__ == "__main__": from doctest import testmod testmod()
296
0
"""simple docstring""" import unittest from transformers import DonutProcessor A_ = '''naver-clova-ix/donut-base''' class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Any = DonutProcessor.from_pretrained(snake_case ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : int = { """name""": """John Doe""", """age""": """99""", """city""": """Atlanta""", """state""": """GA""", """zip""": """30301""", """phone""": """123-4567""", """nicknames""": [{"""nickname""": """Johnny"""}, {"""nickname""": """JD"""}], } A__ : Optional[Any] = ( """<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>""" """<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>""" """<s_nicknames><s_nickname>Johnny</s_nickname>""" """<sep/><s_nickname>JD</s_nickname></s_nicknames>""" ) A__ : int = self.processor.tokenajson(snake_case ) self.assertDictEqual(snake_case , snake_case )
350
"""simple docstring""" from __future__ import annotations class __SCREAMING_SNAKE_CASE : def __init__( self : Dict , snake_case : int ): '''simple docstring''' A__ : List[Any] = order # a_{0} ... a_{k} A__ : List[Any] = [1.0] + [0.0] * order # b_{0} ... b_{k} A__ : str = [1.0] + [0.0] * order # x[n-1] ... x[n-k] A__ : Union[str, Any] = [0.0] * self.order # y[n-1] ... y[n-k] A__ : List[str] = [0.0] * self.order def _UpperCamelCase ( self : Optional[int] , snake_case : list[float] , snake_case : list[float] ): '''simple docstring''' if len(snake_case ) < self.order: A__ : Any = [1.0, *a_coeffs] if len(snake_case ) != self.order + 1: A__ : str = ( F'Expected a_coeffs to have {self.order + 1} elements ' F'for {self.order}-order filter, got {len(snake_case )}' ) raise ValueError(snake_case ) if len(snake_case ) != self.order + 1: A__ : Union[str, Any] = ( F'Expected b_coeffs to have {self.order + 1} elements ' F'for {self.order}-order filter, got {len(snake_case )}' ) raise ValueError(snake_case ) A__ : Dict = a_coeffs A__ : Any = b_coeffs def _UpperCamelCase ( self : List[str] , snake_case : float ): '''simple docstring''' A__ : str = 0.0 # Start at index 1 and do index 0 at the end. for i in range(1 , self.order + 1 ): result += ( self.b_coeffs[i] * self.input_history[i - 1] - self.a_coeffs[i] * self.output_history[i - 1] ) A__ : Dict = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0] A__ : Tuple = self.input_history[:-1] A__ : int = self.output_history[:-1] A__ : Dict = sample A__ : Tuple = result return result
296
0
"""simple docstring""" from typing import List from .keymap import KEYMAP, get_character def _lowerCAmelCase ( UpperCAmelCase__ : str ) ->Optional[Any]: def decorator(UpperCAmelCase__ : List[str] ): A__ : Union[str, Any] = getattr(UpperCAmelCase__, """handle_key""", [] ) handle += [key] setattr(UpperCAmelCase__, """handle_key""", UpperCAmelCase__ ) return func return decorator def _lowerCAmelCase ( *UpperCAmelCase__ : List[str] ) ->List[Any]: def decorator(UpperCAmelCase__ : List[Any] ): A__ : Optional[int] = getattr(UpperCAmelCase__, """handle_key""", [] ) handle += keys setattr(UpperCAmelCase__, """handle_key""", UpperCAmelCase__ ) return func return decorator class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): def __new__( cls : Tuple , snake_case : Optional[Any] , snake_case : List[Any] , snake_case : List[Any] ): '''simple docstring''' A__ : Union[str, Any] = super().__new__(cls , snake_case , snake_case , snake_case ) if not hasattr(snake_case , """key_handler""" ): setattr(snake_case , """key_handler""" , {} ) setattr(snake_case , """handle_input""" , KeyHandler.handle_input ) for value in attrs.values(): A__ : Tuple = getattr(snake_case , """handle_key""" , [] ) for key in handled_keys: A__ : str = value return new_cls @staticmethod def _UpperCamelCase ( cls : str ): '''simple docstring''' A__ : Tuple = get_character() if char != KEYMAP["undefined"]: A__ : int = ord(snake_case ) A__ : Optional[Any] = cls.key_handler.get(snake_case ) if handler: A__ : Union[str, Any] = char return handler(cls ) else: return None def _lowerCAmelCase ( cls : List[str] ) ->Tuple: return KeyHandler(cls.__name__, cls.__bases__, cls.__dict__.copy() )
351
"""simple docstring""" import unittest from parameterized import parameterized from transformers import AutoTokenizer, GPTNeoXConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXModel, ) class __SCREAMING_SNAKE_CASE : def __init__( self : Optional[int] , snake_case : Optional[Any] , snake_case : Tuple=13 , snake_case : Dict=7 , snake_case : Optional[int]=True , snake_case : Union[str, Any]=True , snake_case : Dict=True , snake_case : Any=True , snake_case : List[str]=99 , snake_case : str=64 , snake_case : Optional[int]=5 , snake_case : str=4 , snake_case : List[Any]=37 , snake_case : Optional[Any]="gelu" , snake_case : List[str]=0.1 , snake_case : str=0.1 , snake_case : Optional[int]=512 , snake_case : Dict=16 , snake_case : List[Any]=2 , snake_case : Optional[int]=0.02 , snake_case : Any=3 , snake_case : Union[str, Any]=4 , snake_case : Dict=None , ): '''simple docstring''' A__ : Tuple = parent A__ : Union[str, Any] = batch_size A__ : List[str] = seq_length A__ : Optional[int] = is_training A__ : Dict = use_input_mask A__ : Any = use_token_type_ids A__ : Optional[Any] = use_labels A__ : List[str] = vocab_size A__ : Optional[int] = hidden_size A__ : Optional[Any] = num_hidden_layers A__ : Any = num_attention_heads A__ : List[Any] = intermediate_size A__ : Optional[Any] = hidden_act A__ : Optional[int] = hidden_dropout_prob A__ : Tuple = attention_probs_dropout_prob A__ : str = max_position_embeddings A__ : List[str] = type_vocab_size A__ : Union[str, Any] = type_sequence_label_size A__ : List[Any] = initializer_range A__ : Optional[int] = num_labels A__ : Dict = num_choices A__ : Dict = scope A__ : List[Any] = vocab_size - 1 def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : List[Any] = None if self.use_input_mask: A__ : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) A__ : Union[str, Any] = None if self.use_labels: A__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : Tuple = self.get_config() return config, input_ids, input_mask, token_labels def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' return GPTNeoXConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case , initializer_range=self.initializer_range , pad_token_id=self.pad_token_id , ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ , A__ , A__ , A__ : str = self.prepare_config_and_inputs() A__ : Union[str, Any] = True return config, input_ids, input_mask, token_labels def _UpperCamelCase ( self : Union[str, Any] , snake_case : Optional[int] , snake_case : List[str] , snake_case : int ): '''simple docstring''' A__ : Any = GPTNeoXModel(config=snake_case ) model.to(snake_case ) model.eval() A__ : int = model(snake_case , attention_mask=snake_case ) A__ : Optional[int] = model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : Union[str, Any] , snake_case : str , snake_case : Any , snake_case : Union[str, Any] ): '''simple docstring''' A__ : int = True A__ : str = GPTNeoXModel(snake_case ) model.to(snake_case ) model.eval() A__ : Tuple = model(snake_case , attention_mask=snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : Dict , snake_case : List[Any] , snake_case : str , snake_case : Optional[Any] , snake_case : Any ): '''simple docstring''' A__ : Any = GPTNeoXForCausalLM(config=snake_case ) model.to(snake_case ) model.eval() A__ : Tuple = 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 _UpperCamelCase ( self : List[str] , snake_case : Optional[Any] , snake_case : Optional[Any] , snake_case : Union[str, Any] , snake_case : Tuple ): '''simple docstring''' A__ : int = self.num_labels A__ : int = GPTNeoXForQuestionAnswering(snake_case ) model.to(snake_case ) model.eval() A__ : Optional[Any] = model(snake_case , attention_mask=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 _UpperCamelCase ( self : str , snake_case : Tuple , snake_case : int , snake_case : int , snake_case : Dict ): '''simple docstring''' A__ : List[Any] = self.num_labels A__ : Tuple = GPTNeoXForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : List[str] = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _UpperCamelCase ( self : Any , snake_case : Union[str, Any] , snake_case : int , snake_case : Tuple , snake_case : Any ): '''simple docstring''' A__ : Tuple = self.num_labels A__ : Any = GPTNeoXForTokenClassification(snake_case ) model.to(snake_case ) model.eval() A__ : Dict = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self : List[str] , snake_case : List[str] , snake_case : Tuple , snake_case : Any ): '''simple docstring''' A__ : Optional[int] = True A__ : Any = GPTNeoXForCausalLM(config=snake_case ) model.to(snake_case ) model.eval() # first forward pass A__ : Tuple = model(snake_case , attention_mask=snake_case , use_cache=snake_case ) A__ : str = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A__ : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ : Tuple = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and A__ : Any = torch.cat([input_ids, next_tokens] , dim=-1 ) A__ : Any = torch.cat([input_mask, next_mask] , dim=-1 ) A__ : Tuple = model(snake_case , attention_mask=snake_case , output_hidden_states=snake_case ) A__ : List[Any] = output_from_no_past["""hidden_states"""][0] A__ : List[str] = model( snake_case , attention_mask=snake_case , past_key_values=snake_case , output_hidden_states=snake_case , )["""hidden_states"""][0] # select random slice A__ : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() A__ : List[Any] = output_from_no_past[:, -3:, random_slice_idx].detach() A__ : Any = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(snake_case , snake_case , atol=1e-3 ) ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : str = self.prepare_config_and_inputs() A__ , A__ , A__ , A__ : Dict = config_and_inputs A__ : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase ): snake_case_ = ( ( GPTNeoXModel, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, ) if is_torch_available() else () ) snake_case_ = (GPTNeoXForCausalLM,) if is_torch_available() else () snake_case_ = ( { 'feature-extraction': GPTNeoXModel, 'question-answering': GPTNeoXForQuestionAnswering, 'text-classification': GPTNeoXForSequenceClassification, 'text-generation': GPTNeoXForCausalLM, 'token-classification': GPTNeoXForTokenClassification, 'zero-shot': GPTNeoXForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Any = GPTNeoXModelTester(self ) A__ : Any = ConfigTester(self , config_class=snake_case , hidden_size=64 , num_attention_heads=8 ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self : Any ): '''simple docstring''' A__ , A__ , A__ , A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(snake_case , snake_case , snake_case ) def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ , A__ , A__ , A__ : Dict = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(snake_case , snake_case , snake_case ) def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ , A__ , A__ , A__ : List[str] = self.model_tester.prepare_config_and_inputs_for_decoder() A__ : Optional[Any] = None self.model_tester.create_and_check_model_as_decoder(snake_case , snake_case , snake_case ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ , A__ , A__ , A__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(snake_case , snake_case , snake_case ) def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*snake_case ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case ) @unittest.skip(reason="""Feed forward chunking is not implemented""" ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' pass @parameterized.expand([("""linear""",), ("""dynamic""",)] ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Optional[Any] ): '''simple docstring''' A__ , A__ : int = self.model_tester.prepare_config_and_inputs_for_common() A__ : List[Any] = ids_tensor([1, 10] , config.vocab_size ) A__ : str = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A__ : Union[str, Any] = GPTNeoXModel(snake_case ) original_model.to(snake_case ) original_model.eval() A__ : Optional[int] = original_model(snake_case ).last_hidden_state A__ : List[str] = original_model(snake_case ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights A__ : Optional[int] = {"""type""": scaling_type, """factor""": 10.0} A__ : Optional[int] = GPTNeoXModel(snake_case ) scaled_model.to(snake_case ) scaled_model.eval() A__ : List[str] = scaled_model(snake_case ).last_hidden_state A__ : Tuple = scaled_model(snake_case ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(snake_case , snake_case , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(snake_case , snake_case , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(snake_case , snake_case , atol=1e-5 ) ) @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Any = AutoTokenizer.from_pretrained("""EleutherAI/pythia-410m-deduped""" ) for checkpointing in [True, False]: A__ : Optional[Any] = GPTNeoXForCausalLM.from_pretrained("""EleutherAI/pythia-410m-deduped""" ) if checkpointing: model.gradient_checkpointing_enable() else: model.gradient_checkpointing_disable() model.to(snake_case ) A__ : Optional[Any] = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(snake_case ) # The hub repo. is updated on 2023-04-04, resulting in poor outputs. # See: https://github.com/huggingface/transformers/pull/24193 A__ : Union[str, Any] = """My favorite food is a good old-fashioned, old-fashioned, old-fashioned.\n\nI'm not sure""" A__ : Tuple = model.generate(**snake_case , do_sample=snake_case , max_new_tokens=20 ) A__ : Tuple = tokenizer.batch_decode(snake_case )[0] self.assertEqual(snake_case , snake_case )
296
0
"""simple docstring""" import json import os from typing import Dict, List, Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging A_ = logging.get_logger(__name__) A_ = { '''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_config_file''': '''tokenizer_config.json''', } A_ = { '''vocab_file''': { '''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json''' }, '''merges_file''': { '''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt''' }, '''tokenizer_config_file''': { '''facebook/blenderbot_small-90M''': ( '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json''' ) }, } A_ = {'''facebook/blenderbot_small-90M''': 512} def _lowerCAmelCase ( UpperCAmelCase__ : Optional[Any] ) ->Tuple: A__ : str = set() A__ : List[Any] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) A__ : List[str] = char A__ : List[str] = set(UpperCAmelCase__ ) return pairs class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ['input_ids', 'attention_mask'] def __init__( self : Any , snake_case : Any , snake_case : Optional[int] , snake_case : List[Any]="__start__" , snake_case : str="__end__" , snake_case : str="__unk__" , snake_case : List[str]="__null__" , **snake_case : List[str] , ): '''simple docstring''' super().__init__(unk_token=snake_case , bos_token=snake_case , eos_token=snake_case , pad_token=snake_case , **snake_case ) with open(snake_case , encoding="""utf-8""" ) as vocab_handle: A__ : Tuple = json.load(snake_case ) A__ : List[str] = {v: k for k, v in self.encoder.items()} with open(snake_case , encoding="""utf-8""" ) as merges_handle: A__ : Union[str, Any] = merges_handle.read().split("""\n""" )[1:-1] A__ : Optional[Any] = [tuple(merge.split() ) for merge in merges] A__ : List[str] = dict(zip(snake_case , range(len(snake_case ) ) ) ) A__ : Optional[int] = {} @property def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' return len(self.encoder ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def _UpperCamelCase ( self : Union[str, Any] , snake_case : str ): '''simple docstring''' if token in self.cache: return self.cache[token] A__ : Dict = re.sub("""([.,!?()])""" , r""" \1""" , snake_case ) A__ : List[str] = re.sub("""(')""" , r""" \1 """ , snake_case ) A__ : Optional[Any] = re.sub(r"""\s{2,}""" , """ """ , snake_case ) if "\n" in token: A__ : Optional[int] = token.replace("""\n""" , """ __newln__""" ) A__ : Tuple = token.split(""" """ ) A__ : List[Any] = [] for token in tokens: if not len(snake_case ): continue A__ : Optional[Any] = token.lower() A__ : List[Any] = tuple(snake_case ) A__ : int = tuple(list(word[:-1] ) + [word[-1] + """</w>"""] ) A__ : Any = get_pairs(snake_case ) if not pairs: words.append(snake_case ) continue while True: A__ : Optional[Any] = min(snake_case , key=lambda snake_case : self.bpe_ranks.get(snake_case , float("""inf""" ) ) ) if bigram not in self.bpe_ranks: break A__ : List[Any] = bigram A__ : Dict = [] A__ : List[str] = 0 while i < len(snake_case ): try: A__ : int = word.index(snake_case , snake_case ) new_word.extend(word[i:j] ) A__ : Tuple = j except ValueError: new_word.extend(word[i:] ) break if word[i] == first and i < len(snake_case ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 A__ : Any = tuple(snake_case ) A__ : Optional[int] = new_word if len(snake_case ) == 1: break else: A__ : str = get_pairs(snake_case ) A__ : Dict = """@@ """.join(snake_case ) A__ : str = word[:-4] A__ : Dict = word words.append(snake_case ) return " ".join(snake_case ) def _UpperCamelCase ( self : Optional[int] , snake_case : str ): '''simple docstring''' A__ : str = [] A__ : Union[str, Any] = re.findall(r"""\S+\n?""" , snake_case ) for token in words: split_tokens.extend(list(self.bpe(snake_case ).split(""" """ ) ) ) return split_tokens def _UpperCamelCase ( self : List[Any] , snake_case : str ): '''simple docstring''' A__ : Optional[Any] = token.lower() return self.encoder.get(snake_case , self.encoder.get(self.unk_token ) ) def _UpperCamelCase ( self : List[str] , snake_case : int ): '''simple docstring''' return self.decoder.get(snake_case , self.unk_token ) def _UpperCamelCase ( self : List[Any] , snake_case : List[str] ): '''simple docstring''' A__ : Union[str, Any] = """ """.join(snake_case ).replace("""@@ """ , """""" ).strip() return out_string def _UpperCamelCase ( self : Tuple , snake_case : str , snake_case : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(snake_case ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A__ : Union[str, Any] = os.path.join( snake_case , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) A__ : Any = os.path.join( snake_case , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""] ) with open(snake_case , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=snake_case , ensure_ascii=snake_case ) + """\n""" ) A__ : Tuple = 0 with open(snake_case , """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 snake_case : 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!""" ) A__ : Tuple = token_index writer.write(""" """.join(snake_case ) + """\n""" ) index += 1 return vocab_file, merge_file
352
"""simple docstring""" from collections import defaultdict from math import gcd def _lowerCAmelCase ( UpperCAmelCase__ : int = 1_5_0_0_0_0_0 ) ->int: A__ : defaultdict = defaultdict(UpperCAmelCase__ ) A__ : Any = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1, UpperCAmelCase__, 2 ): if gcd(UpperCAmelCase__, UpperCAmelCase__ ) > 1: continue A__ : str = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(UpperCAmelCase__, limit + 1, UpperCAmelCase__ ): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1 ) if __name__ == "__main__": print(F'{solution() = }')
296
0
"""simple docstring""" import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort A_ = logging.get_logger(__name__) A_ = { '''tensor(bool)''': np.bool_, '''tensor(int8)''': np.inta, '''tensor(uint8)''': np.uinta, '''tensor(int16)''': np.intaa, '''tensor(uint16)''': np.uintaa, '''tensor(int32)''': np.intaa, '''tensor(uint32)''': np.uintaa, '''tensor(int64)''': np.intaa, '''tensor(uint64)''': np.uintaa, '''tensor(float16)''': np.floataa, '''tensor(float)''': np.floataa, '''tensor(double)''': np.floataa, } class __SCREAMING_SNAKE_CASE : def __init__( self : Any , snake_case : str=None , **snake_case : Tuple ): '''simple docstring''' logger.info("""`diffusers.OnnxRuntimeModel` is experimental and might change in the future.""" ) A__ : Optional[Any] = model A__ : Optional[int] = kwargs.get("""model_save_dir""" , snake_case ) A__ : str = kwargs.get("""latest_model_name""" , snake_case ) def __call__( self : str , **snake_case : Optional[int] ): '''simple docstring''' A__ : List[Any] = {k: np.array(snake_case ) for k, v in kwargs.items()} return self.model.run(snake_case , snake_case ) @staticmethod def _UpperCamelCase ( snake_case : Union[str, Path] , snake_case : str=None , snake_case : Any=None ): '''simple docstring''' if provider is None: logger.info("""No onnxruntime provider specified, using CPUExecutionProvider""" ) A__ : List[Any] = """CPUExecutionProvider""" return ort.InferenceSession(snake_case , providers=[provider] , sess_options=snake_case ) def _UpperCamelCase ( self : Tuple , snake_case : Union[str, Path] , snake_case : Optional[str] = None , **snake_case : Dict ): '''simple docstring''' A__ : Optional[int] = file_name if file_name is not None else ONNX_WEIGHTS_NAME A__ : Optional[Any] = self.model_save_dir.joinpath(self.latest_model_name ) A__ : Optional[Any] = Path(snake_case ).joinpath(snake_case ) try: shutil.copyfile(snake_case , snake_case ) except shutil.SameFileError: pass # copy external weights (for models >2GB) A__ : List[str] = self.model_save_dir.joinpath(snake_case ) if src_path.exists(): A__ : Tuple = Path(snake_case ).joinpath(snake_case ) try: shutil.copyfile(snake_case , snake_case ) except shutil.SameFileError: pass def _UpperCamelCase ( self : List[Any] , snake_case : Union[str, os.PathLike] , **snake_case : Optional[int] , ): '''simple docstring''' if os.path.isfile(snake_case ): logger.error(F'Provided path ({save_directory}) should be a directory, not a file' ) return os.makedirs(snake_case , exist_ok=snake_case ) # saving model weights/files self._save_pretrained(snake_case , **snake_case ) @classmethod def _UpperCamelCase ( cls : List[str] , snake_case : Union[str, Path] , snake_case : Optional[Union[bool, str, None]] = None , snake_case : Optional[Union[str, None]] = None , snake_case : bool = False , snake_case : Optional[str] = None , snake_case : Optional[str] = None , snake_case : Optional[str] = None , snake_case : Optional["ort.SessionOptions"] = None , **snake_case : str , ): '''simple docstring''' A__ : Optional[Any] = file_name if file_name is not None else ONNX_WEIGHTS_NAME # load model from local directory if os.path.isdir(snake_case ): A__ : Dict = OnnxRuntimeModel.load_model( os.path.join(snake_case , snake_case ) , provider=snake_case , sess_options=snake_case ) A__ : Any = Path(snake_case ) # load model from hub else: # download model A__ : Union[str, Any] = hf_hub_download( repo_id=snake_case , filename=snake_case , use_auth_token=snake_case , revision=snake_case , cache_dir=snake_case , force_download=snake_case , ) A__ : List[Any] = Path(snake_case ).parent A__ : Optional[int] = Path(snake_case ).name A__ : Any = OnnxRuntimeModel.load_model(snake_case , provider=snake_case , sess_options=snake_case ) return cls(model=snake_case , **snake_case ) @classmethod def _UpperCamelCase ( cls : Optional[int] , snake_case : Union[str, Path] , snake_case : bool = True , snake_case : Optional[str] = None , snake_case : Optional[str] = None , **snake_case : Optional[Any] , ): '''simple docstring''' A__ : Dict = None if len(str(snake_case ).split("""@""" ) ) == 2: A__ : str = model_id.split("""@""" ) return cls._from_pretrained( model_id=snake_case , revision=snake_case , cache_dir=snake_case , force_download=snake_case , use_auth_token=snake_case , **snake_case , )
353
"""simple docstring""" import os from distutils.util import strtobool def _lowerCAmelCase ( UpperCAmelCase__ : List[Any], UpperCAmelCase__ : Optional[Any] ) ->List[str]: for e in env_keys: A__ : List[Any] = int(os.environ.get(UpperCAmelCase__, -1 ) ) if val >= 0: return val return default def _lowerCAmelCase ( UpperCAmelCase__ : Tuple, UpperCAmelCase__ : str=False ) ->List[str]: A__ : List[Any] = os.environ.get(UpperCAmelCase__, str(UpperCAmelCase__ ) ) return strtobool(UpperCAmelCase__ ) == 1 # As its name indicates `strtobool` actually returns an int... def _lowerCAmelCase ( UpperCAmelCase__ : Tuple, UpperCAmelCase__ : List[Any]="no" ) ->int: A__ : str = os.environ.get(UpperCAmelCase__, str(UpperCAmelCase__ ) ) return value
296
0
"""simple docstring""" import contextlib import copy import random from typing import Any, Dict, Iterable, Optional, Union import numpy as np import torch from .utils import deprecate, is_transformers_available if is_transformers_available(): import transformers def _lowerCAmelCase ( UpperCAmelCase__ : int ) ->Optional[int]: random.seed(UpperCAmelCase__ ) np.random.seed(UpperCAmelCase__ ) torch.manual_seed(UpperCAmelCase__ ) torch.cuda.manual_seed_all(UpperCAmelCase__ ) # ^^ safe to call this function even if cuda is not available class __SCREAMING_SNAKE_CASE : def __init__( self : Any , snake_case : Iterable[torch.nn.Parameter] , snake_case : float = 0.9999 , snake_case : float = 0.0 , snake_case : int = 0 , snake_case : bool = False , snake_case : Union[float, int] = 1.0 , snake_case : Union[float, int] = 2 / 3 , snake_case : Optional[Any] = None , snake_case : Dict[str, Any] = None , **snake_case : Tuple , ): '''simple docstring''' if isinstance(snake_case , torch.nn.Module ): A__ : Any = ( """Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. """ """Please pass the parameters of the module instead.""" ) deprecate( """passing a `torch.nn.Module` to `ExponentialMovingAverage`""" , """1.0.0""" , snake_case , standard_warn=snake_case , ) A__ : int = parameters.parameters() # set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility A__ : Any = True if kwargs.get("""max_value""" , snake_case ) is not None: A__ : Union[str, Any] = """The `max_value` argument is deprecated. Please use `decay` instead.""" deprecate("""max_value""" , """1.0.0""" , snake_case , standard_warn=snake_case ) A__ : Tuple = kwargs["""max_value"""] if kwargs.get("""min_value""" , snake_case ) is not None: A__ : List[str] = """The `min_value` argument is deprecated. Please use `min_decay` instead.""" deprecate("""min_value""" , """1.0.0""" , snake_case , standard_warn=snake_case ) A__ : List[str] = kwargs["""min_value"""] A__ : Any = list(snake_case ) A__ : Optional[Any] = [p.clone().detach() for p in parameters] if kwargs.get("""device""" , snake_case ) is not None: A__ : str = """The `device` argument is deprecated. Please use `to` instead.""" deprecate("""device""" , """1.0.0""" , snake_case , standard_warn=snake_case ) self.to(device=kwargs["""device"""] ) A__ : List[str] = None A__ : Union[str, Any] = decay A__ : Tuple = min_decay A__ : Tuple = update_after_step A__ : Optional[Any] = use_ema_warmup A__ : List[Any] = inv_gamma A__ : Optional[int] = power A__ : Optional[Any] = 0 A__ : int = None # set in `step()` A__ : int = model_cls A__ : Any = model_config @classmethod def _UpperCamelCase ( cls : str , snake_case : Tuple , snake_case : Optional[Any] ): '''simple docstring''' A__ : str = model_cls.load_config(snake_case , return_unused_kwargs=snake_case ) A__ : Union[str, Any] = model_cls.from_pretrained(snake_case ) A__ : List[Any] = cls(model.parameters() , model_cls=snake_case , model_config=model.config ) ema_model.load_state_dict(snake_case ) return ema_model def _UpperCamelCase ( self : int , snake_case : Optional[Any] ): '''simple docstring''' if self.model_cls is None: raise ValueError("""`save_pretrained` can only be used if `model_cls` was defined at __init__.""" ) if self.model_config is None: raise ValueError("""`save_pretrained` can only be used if `model_config` was defined at __init__.""" ) A__ : List[Any] = self.model_cls.from_config(self.model_config ) A__ : List[str] = self.state_dict() state_dict.pop("""shadow_params""" , snake_case ) model.register_to_config(**snake_case ) self.copy_to(model.parameters() ) model.save_pretrained(snake_case ) def _UpperCamelCase ( self : str , snake_case : int ): '''simple docstring''' A__ : Any = max(0 , optimization_step - self.update_after_step - 1 ) if step <= 0: return 0.0 if self.use_ema_warmup: A__ : Optional[Any] = 1 - (1 + step / self.inv_gamma) ** -self.power else: A__ : Optional[int] = (1 + step) / (10 + step) A__ : Dict = min(snake_case , self.decay ) # make sure decay is not smaller than min_decay A__ : Dict = max(snake_case , self.min_decay ) return cur_decay_value @torch.no_grad() def _UpperCamelCase ( self : Optional[int] , snake_case : Iterable[torch.nn.Parameter] ): '''simple docstring''' if isinstance(snake_case , torch.nn.Module ): A__ : Any = ( """Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. """ """Please pass the parameters of the module instead.""" ) deprecate( """passing a `torch.nn.Module` to `ExponentialMovingAverage.step`""" , """1.0.0""" , snake_case , standard_warn=snake_case , ) A__ : Dict = parameters.parameters() A__ : str = list(snake_case ) self.optimization_step += 1 # Compute the decay factor for the exponential moving average. A__ : str = self.get_decay(self.optimization_step ) A__ : Any = decay A__ : str = 1 - decay A__ : List[str] = contextlib.nullcontext if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): import deepspeed for s_param, param in zip(self.shadow_params , snake_case ): if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): A__ : int = deepspeed.zero.GatheredParameters(snake_case , modifier_rank=snake_case ) with context_manager(): if param.requires_grad: s_param.sub_(one_minus_decay * (s_param - param) ) else: s_param.copy_(snake_case ) def _UpperCamelCase ( self : Tuple , snake_case : Iterable[torch.nn.Parameter] ): '''simple docstring''' A__ : Tuple = list(snake_case ) for s_param, param in zip(self.shadow_params , snake_case ): param.data.copy_(s_param.to(param.device ).data ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Any=None , snake_case : List[Any]=None ): '''simple docstring''' A__ : str = [ p.to(device=snake_case , dtype=snake_case ) if p.is_floating_point() else p.to(device=snake_case ) for p in self.shadow_params ] def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' return { "decay": self.decay, "min_decay": self.min_decay, "optimization_step": self.optimization_step, "update_after_step": self.update_after_step, "use_ema_warmup": self.use_ema_warmup, "inv_gamma": self.inv_gamma, "power": self.power, "shadow_params": self.shadow_params, } def _UpperCamelCase ( self : Union[str, Any] , snake_case : Iterable[torch.nn.Parameter] ): '''simple docstring''' A__ : int = [param.detach().cpu().clone() for param in parameters] def _UpperCamelCase ( self : int , snake_case : Iterable[torch.nn.Parameter] ): '''simple docstring''' if self.temp_stored_params is None: raise RuntimeError("""This ExponentialMovingAverage has no `store()`ed weights """ """to `restore()`""" ) for c_param, param in zip(self.temp_stored_params , snake_case ): param.data.copy_(c_param.data ) # Better memory-wise. A__ : Any = None def _UpperCamelCase ( self : Union[str, Any] , snake_case : dict ): '''simple docstring''' A__ : int = copy.deepcopy(snake_case ) A__ : str = state_dict.get("""decay""" , self.decay ) if self.decay < 0.0 or self.decay > 1.0: raise ValueError("""Decay must be between 0 and 1""" ) A__ : Tuple = state_dict.get("""min_decay""" , self.min_decay ) if not isinstance(self.min_decay , snake_case ): raise ValueError("""Invalid min_decay""" ) A__ : List[Any] = state_dict.get("""optimization_step""" , self.optimization_step ) if not isinstance(self.optimization_step , snake_case ): raise ValueError("""Invalid optimization_step""" ) A__ : Optional[Any] = state_dict.get("""update_after_step""" , self.update_after_step ) if not isinstance(self.update_after_step , snake_case ): raise ValueError("""Invalid update_after_step""" ) A__ : Optional[int] = state_dict.get("""use_ema_warmup""" , self.use_ema_warmup ) if not isinstance(self.use_ema_warmup , snake_case ): raise ValueError("""Invalid use_ema_warmup""" ) A__ : List[Any] = state_dict.get("""inv_gamma""" , self.inv_gamma ) if not isinstance(self.inv_gamma , (float, int) ): raise ValueError("""Invalid inv_gamma""" ) A__ : Optional[int] = state_dict.get("""power""" , self.power ) if not isinstance(self.power , (float, int) ): raise ValueError("""Invalid power""" ) A__ : str = state_dict.get("""shadow_params""" , snake_case ) if shadow_params is not None: A__ : Optional[Any] = shadow_params if not isinstance(self.shadow_params , snake_case ): raise ValueError("""shadow_params must be a list""" ) if not all(isinstance(snake_case , torch.Tensor ) for p in self.shadow_params ): raise ValueError("""shadow_params must all be Tensors""" )
354
"""simple docstring""" import cva import numpy as np class __SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , snake_case : float , snake_case : int ): '''simple docstring''' if k in (0.04, 0.06): A__ : Optional[int] = k A__ : int = window_size else: raise ValueError("""invalid k value""" ) def __str__( self : List[Any] ): '''simple docstring''' return str(self.k ) def _UpperCamelCase ( self : int , snake_case : str ): '''simple docstring''' A__ : List[str] = cva.imread(snake_case , 0 ) A__ , A__ : Union[str, Any] = img.shape A__ : list[list[int]] = [] A__ : Optional[Any] = img.copy() A__ : List[str] = cva.cvtColor(snake_case , cva.COLOR_GRAY2RGB ) A__ , A__ : List[Any] = np.gradient(snake_case ) A__ : List[Any] = dx**2 A__ : Any = dy**2 A__ : Dict = dx * dy A__ : Any = 0.04 A__ : Optional[Any] = self.window_size // 2 for y in range(snake_case , h - offset ): for x in range(snake_case , w - offset ): A__ : List[str] = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() A__ : Tuple = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() A__ : Optional[int] = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() A__ : int = (wxx * wyy) - (wxy**2) A__ : Any = wxx + wyy A__ : List[str] = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 255 ) return color_img, corner_list if __name__ == "__main__": A_ = HarrisCorner(0.04, 3) A_ , A_ = edge_detect.detect('''path_to_image''') cva.imwrite('''detect.png''', color_img)
296
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor A_ = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): def __init__( self : Union[str, Any] , *snake_case : Tuple , **snake_case : Optional[int] ): '''simple docstring''' warnings.warn( """The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use LayoutLMv2ImageProcessor instead.""" , snake_case , ) super().__init__(*snake_case , **snake_case )
355
"""simple docstring""" from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING A_ = logging.get_logger(__name__) A_ = Dict[str, Any] A_ = List[Prediction] @add_end_docstrings(UpperCamelCase ) class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): def __init__( self : str , *snake_case : Tuple , **snake_case : Tuple ): '''simple docstring''' super().__init__(*snake_case , **snake_case ) if self.framework == "tf": raise ValueError(F'The {self.__class__} is only available in PyTorch.' ) requires_backends(self , """vision""" ) self.check_model_type( dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items() ) ) def _UpperCamelCase ( self : List[Any] , **snake_case : Optional[int] ): '''simple docstring''' A__ : Dict = {} if "threshold" in kwargs: A__ : int = kwargs["""threshold"""] return {}, {}, postprocess_kwargs def __call__( self : Tuple , *snake_case : Union[str, Any] , **snake_case : Union[str, Any] ): '''simple docstring''' return super().__call__(*snake_case , **snake_case ) def _UpperCamelCase ( self : str , snake_case : int ): '''simple docstring''' A__ : List[str] = load_image(snake_case ) A__ : int = torch.IntTensor([[image.height, image.width]] ) A__ : Union[str, Any] = self.image_processor(images=[image] , return_tensors="""pt""" ) if self.tokenizer is not None: A__ : str = self.tokenizer(text=inputs["""words"""] , boxes=inputs["""boxes"""] , return_tensors="""pt""" ) A__ : List[str] = target_size return inputs def _UpperCamelCase ( self : Optional[int] , snake_case : List[Any] ): '''simple docstring''' A__ : str = model_inputs.pop("""target_size""" ) A__ : Dict = self.model(**snake_case ) A__ : Optional[Any] = outputs.__class__({"""target_size""": target_size, **outputs} ) if self.tokenizer is not None: A__ : str = model_inputs["""bbox"""] return model_outputs def _UpperCamelCase ( self : Tuple , snake_case : Optional[int] , snake_case : int=0.9 ): '''simple docstring''' A__ : Any = model_outputs["""target_size"""] if self.tokenizer is not None: # This is a LayoutLMForTokenClassification variant. # The OCR got the boxes and the model classified the words. A__ , A__ : Tuple = target_size[0].tolist() def unnormalize(snake_case : Optional[int] ): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ] ) ) A__ , A__ : Optional[int] = model_outputs["""logits"""].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 ) A__ : Optional[Any] = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] A__ : List[str] = [unnormalize(snake_case ) for bbox in model_outputs["""bbox"""].squeeze(0 )] A__ : Tuple = ["""score""", """label""", """box"""] A__ : Any = [dict(zip(snake_case , snake_case ) ) for vals in zip(scores.tolist() , snake_case , snake_case ) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel A__ : Union[str, Any] = self.image_processor.post_process_object_detection(snake_case , snake_case , snake_case ) A__ : str = raw_annotations[0] A__ : str = raw_annotation["""scores"""] A__ : List[Any] = raw_annotation["""labels"""] A__ : int = raw_annotation["""boxes"""] A__ : str = scores.tolist() A__ : Any = [self.model.config.idalabel[label.item()] for label in labels] A__ : int = [self._get_bounding_box(snake_case ) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] A__ : str = ["""score""", """label""", """box"""] A__ : Dict = [ dict(zip(snake_case , snake_case ) ) for vals in zip(raw_annotation["""scores"""] , raw_annotation["""labels"""] , raw_annotation["""boxes"""] ) ] return annotation def _UpperCamelCase ( self : Union[str, Any] , snake_case : "torch.Tensor" ): '''simple docstring''' if self.framework != "pt": raise ValueError("""The ObjectDetectionPipeline is only available in PyTorch.""" ) A__ , A__ , A__ , A__ : Any = box.int().tolist() A__ : Any = { """xmin""": xmin, """ymin""": ymin, """xmax""": xmax, """ymax""": ymax, } return bbox
296
0
"""simple docstring""" def _lowerCAmelCase ( UpperCAmelCase__ : int = 1_0_0 ) ->int: A__ : Union[str, Any] = n * (n + 1) * (2 * n + 1) / 6 A__ : Tuple = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F'{solution() = }')
356
"""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 A_ = logging.get_logger(__name__) A_ = { '''microsoft/table-transformer-detection''': ( '''https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json''' ), } class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = 'table-transformer' snake_case_ = ['past_key_values'] snake_case_ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Dict , snake_case : int=True , snake_case : Dict=None , snake_case : Union[str, Any]=3 , snake_case : Dict=100 , snake_case : Tuple=6 , snake_case : Optional[int]=2048 , snake_case : int=8 , snake_case : Dict=6 , snake_case : Any=2048 , snake_case : str=8 , snake_case : Union[str, Any]=0.0 , snake_case : List[str]=0.0 , snake_case : List[str]=True , snake_case : Any="relu" , snake_case : str=256 , snake_case : int=0.1 , snake_case : Dict=0.0 , snake_case : str=0.0 , snake_case : Union[str, Any]=0.02 , snake_case : Union[str, Any]=1.0 , snake_case : Optional[Any]=False , snake_case : int="sine" , snake_case : Optional[Any]="resnet50" , snake_case : Optional[int]=True , snake_case : Any=False , snake_case : int=1 , snake_case : Tuple=5 , snake_case : Optional[int]=2 , snake_case : Tuple=1 , snake_case : Optional[Any]=1 , snake_case : Optional[Any]=5 , snake_case : Dict=2 , snake_case : Any=0.1 , **snake_case : Any , ): '''simple docstring''' 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.""" ) A__ : Optional[Any] = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(snake_case , snake_case ): A__ : Optional[int] = backbone_config.get("""model_type""" ) A__ : Optional[int] = CONFIG_MAPPING[backbone_model_type] A__ : List[str] = config_class.from_dict(snake_case ) # set timm attributes to None A__ , A__ , A__ : str = None, None, None A__ : Tuple = use_timm_backbone A__ : str = backbone_config A__ : str = num_channels A__ : List[Any] = num_queries A__ : Optional[Any] = d_model A__ : Tuple = encoder_ffn_dim A__ : Union[str, Any] = encoder_layers A__ : List[Any] = encoder_attention_heads A__ : Optional[int] = decoder_ffn_dim A__ : Any = decoder_layers A__ : int = decoder_attention_heads A__ : Any = dropout A__ : Dict = attention_dropout A__ : Dict = activation_dropout A__ : Tuple = activation_function A__ : List[str] = init_std A__ : List[str] = init_xavier_std A__ : Any = encoder_layerdrop A__ : Optional[Any] = decoder_layerdrop A__ : Union[str, Any] = encoder_layers A__ : Dict = auxiliary_loss A__ : List[Any] = position_embedding_type A__ : Optional[Any] = backbone A__ : str = use_pretrained_backbone A__ : Union[str, Any] = dilation # Hungarian matcher A__ : Tuple = class_cost A__ : Optional[Any] = bbox_cost A__ : Dict = giou_cost # Loss coefficients A__ : Any = mask_loss_coefficient A__ : str = dice_loss_coefficient A__ : str = bbox_loss_coefficient A__ : Union[str, Any] = giou_loss_coefficient A__ : List[str] = eos_coefficient super().__init__(is_encoder_decoder=snake_case , **snake_case ) @property def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return self.encoder_attention_heads @property def _UpperCamelCase ( self : Dict ): '''simple docstring''' return self.d_model class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = version.parse('1.11' ) @property def _UpperCamelCase ( self : Any ): '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' return 1e-5 @property def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return 12
296
0
"""simple docstring""" def _lowerCAmelCase ( UpperCAmelCase__ : float ) ->float: return 1_0 - x * x def _lowerCAmelCase ( UpperCAmelCase__ : float, UpperCAmelCase__ : float ) ->float: # Bolzano theory in order to find if there is a root between a and b if equation(UpperCAmelCase__ ) * equation(UpperCAmelCase__ ) >= 0: raise ValueError("""Wrong space!""" ) A__ : Dict = a while (b - a) >= 0.01: # Find middle point A__ : Union[str, Any] = (a + b) / 2 # Check if middle point is root if equation(UpperCAmelCase__ ) == 0.0: break # Decide the side to repeat the steps if equation(UpperCAmelCase__ ) * equation(UpperCAmelCase__ ) < 0: A__ : int = c else: A__ : List[Any] = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
357
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = 'Salesforce/blip-image-captioning-base' snake_case_ = ( 'This is a tool that generates a description of an image. It takes an input named `image` which should be the ' 'image to caption, and returns a text that contains the description in English.' ) snake_case_ = 'image_captioner' snake_case_ = AutoModelForVisionaSeq snake_case_ = ['image'] snake_case_ = ['text'] def __init__( self : int , *snake_case : Optional[int] , **snake_case : Optional[int] ): '''simple docstring''' requires_backends(self , ["""vision"""] ) super().__init__(*snake_case , **snake_case ) def _UpperCamelCase ( self : int , snake_case : "Image" ): '''simple docstring''' return self.pre_processor(images=snake_case , return_tensors="""pt""" ) def _UpperCamelCase ( self : int , snake_case : List[Any] ): '''simple docstring''' return self.model.generate(**snake_case ) def _UpperCamelCase ( self : Optional[int] , snake_case : Any ): '''simple docstring''' return self.pre_processor.batch_decode(snake_case , skip_special_tokens=snake_case )[0].strip()
296
0
"""simple docstring""" import json import logging import os import re import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import datasets import numpy as np import torch import torchaudio from packaging import version from torch import nn import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaProcessor, is_apex_available, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse('''1.6'''): A_ = True from torch.cuda.amp import autocast A_ = logging.getLogger(__name__) def _lowerCAmelCase ( UpperCAmelCase__ : List[Any]=None, UpperCAmelCase__ : Optional[int]=None ) ->Tuple: return field(default_factory=lambda: default, metadata=UpperCAmelCase__ ) @dataclass class __SCREAMING_SNAKE_CASE : snake_case_ = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) snake_case_ = field( default=UpperCamelCase , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) snake_case_ = field( default=UpperCamelCase , metadata={'help': 'Whether to freeze the feature extractor layers of the model.'} ) snake_case_ = field( default=0.1 , metadata={'help': 'The dropout ratio for the attention probabilities.'} ) snake_case_ = field( default=0.1 , metadata={'help': 'The dropout ratio for activations inside the fully connected layer.'} ) snake_case_ = field( default=0.1 , metadata={ 'help': 'The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.' } , ) snake_case_ = field( default=0.1 , metadata={'help': 'The dropout probabilitiy for all 1D convolutional layers in feature extractor.'} , ) snake_case_ = field( default=0.0_5 , metadata={ 'help': ( 'Propability of each feature vector along the time axis to be chosen as the start of the vector' 'span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature' 'vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.' ) } , ) snake_case_ = field(default=0.0 , metadata={'help': 'The LayerDrop probability.'} ) @dataclass class __SCREAMING_SNAKE_CASE : snake_case_ = field( default=UpperCamelCase , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) snake_case_ = field( default='train+validation' , metadata={ 'help': 'The name of the training data set split to use (via the datasets library). Defaults to \'train\'' } , ) snake_case_ = field( default=UpperCamelCase , metadata={'help': 'Overwrite the cached preprocessed datasets or not.'} ) snake_case_ = field( default=UpperCamelCase , metadata={'help': 'The number of processes to use for the preprocessing.'} , ) snake_case_ = field( default=UpperCamelCase , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) snake_case_ = field( default=UpperCamelCase , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of validation examples to this ' 'value if set.' ) } , ) snake_case_ = list_field( default=[',', '?', '.', '!', '-', ';', ':', '""', '%', '\'', '"', '�'] , metadata={'help': 'A list of characters to remove from the transcripts.'} , ) @dataclass class __SCREAMING_SNAKE_CASE : snake_case_ = 42 snake_case_ = True snake_case_ = None snake_case_ = None snake_case_ = None snake_case_ = None def __call__( self : int , snake_case : List[Dict[str, Union[List[int], torch.Tensor]]] ): '''simple docstring''' A__ : Any = [{"""input_values""": feature["""input_values"""]} for feature in features] A__ : Optional[int] = [{"""input_ids""": feature["""labels"""]} for feature in features] A__ : Optional[Any] = self.processor.pad( snake_case , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="""pt""" , ) A__ : List[str] = self.processor.pad( labels=snake_case , padding=self.padding , max_length=self.max_length_labels , pad_to_multiple_of=self.pad_to_multiple_of_labels , return_tensors="""pt""" , ) # replace padding with -100 to ignore loss correctly A__ : Optional[Any] = labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1 ) , -100 ) A__ : Dict = labels return batch class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): def _UpperCamelCase ( self : Optional[Any] , snake_case : nn.Module , snake_case : Dict[str, Union[torch.Tensor, Any]] ): '''simple docstring''' model.train() A__ : Optional[int] = self._prepare_inputs(snake_case ) if self.use_amp: with autocast(): A__ : Optional[Any] = self.compute_loss(snake_case , snake_case ) else: A__ : str = self.compute_loss(snake_case , snake_case ) if self.args.n_gpu > 1: if model.module.config.ctc_loss_reduction == "mean": A__ : str = loss.mean() elif model.module.config.ctc_loss_reduction == "sum": A__ : Dict = loss.sum() / (inputs["""labels"""] >= 0).sum() else: raise ValueError(F'{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']' ) if self.args.gradient_accumulation_steps > 1: A__ : str = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(snake_case ).backward() elif self.use_apex: with amp.scale_loss(snake_case , self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(snake_case ) else: loss.backward() return loss.detach() def _lowerCAmelCase ( ) ->Union[str, Any]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. A__ : List[str] = 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. A__ : Tuple = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: A__ : int = parser.parse_args_into_dataclasses() # Detecting last checkpoint. A__ : Optional[Any] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: A__ : str = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f'Output directory ({training_args.output_dir}) already exists and is not empty. ' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None: logger.info( f'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", handlers=[logging.StreamHandler(sys.stdout )], ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # Log on each process the small summary: logger.warning( f'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + f'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) # 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() logger.info("""Training/evaluation parameters %s""", UpperCAmelCase__ ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: A__ : List[Any] = datasets.load_dataset( """common_voice""", data_args.dataset_config_name, split=data_args.train_split_name ) A__ : Optional[int] = datasets.load_dataset("""common_voice""", data_args.dataset_config_name, split="""test""" ) # Create and save tokenizer A__ : List[str] = f'[{"".join(data_args.chars_to_ignore )}]' def remove_special_characters(UpperCAmelCase__ : Dict ): A__ : Optional[Any] = re.sub(UpperCAmelCase__, """""", batch["""sentence"""] ).lower() + """ """ return batch A__ : Any = train_dataset.map(UpperCAmelCase__, remove_columns=["""sentence"""] ) A__ : List[Any] = eval_dataset.map(UpperCAmelCase__, remove_columns=["""sentence"""] ) def extract_all_chars(UpperCAmelCase__ : Dict ): A__ : Any = """ """.join(batch["""text"""] ) A__ : Optional[Any] = list(set(UpperCAmelCase__ ) ) return {"vocab": [vocab], "all_text": [all_text]} A__ : str = train_dataset.map( UpperCAmelCase__, batched=UpperCAmelCase__, batch_size=-1, keep_in_memory=UpperCAmelCase__, remove_columns=train_dataset.column_names, ) A__ : int = train_dataset.map( UpperCAmelCase__, batched=UpperCAmelCase__, batch_size=-1, keep_in_memory=UpperCAmelCase__, remove_columns=eval_dataset.column_names, ) A__ : int = list(set(vocab_train["""vocab"""][0] ) | set(vocab_test["""vocab"""][0] ) ) A__ : str = {v: k for k, v in enumerate(UpperCAmelCase__ )} A__ : Optional[Any] = vocab_dict[""" """] del vocab_dict[" "] A__ : List[str] = len(UpperCAmelCase__ ) A__ : Any = len(UpperCAmelCase__ ) with open("""vocab.json""", """w""" ) as vocab_file: json.dump(UpperCAmelCase__, UpperCAmelCase__ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. A__ : List[Any] = WavaVecaCTCTokenizer( """vocab.json""", unk_token="""[UNK]""", pad_token="""[PAD]""", word_delimiter_token="""|""", ) A__ : int = WavaVecaFeatureExtractor( feature_size=1, sampling_rate=1_6_0_0_0, padding_value=0.0, do_normalize=UpperCAmelCase__, return_attention_mask=UpperCAmelCase__ ) A__ : Optional[Any] = WavaVecaProcessor(feature_extractor=UpperCAmelCase__, tokenizer=UpperCAmelCase__ ) A__ : int = WavaVecaForCTC.from_pretrained( model_args.model_name_or_path, cache_dir=model_args.cache_dir, activation_dropout=model_args.activation_dropout, attention_dropout=model_args.attention_dropout, hidden_dropout=model_args.hidden_dropout, feat_proj_dropout=model_args.feat_proj_dropout, mask_time_prob=model_args.mask_time_prob, gradient_checkpointing=training_args.gradient_checkpointing, layerdrop=model_args.layerdrop, ctc_loss_reduction="""mean""", pad_token_id=processor.tokenizer.pad_token_id, vocab_size=len(processor.tokenizer ), ) if data_args.max_train_samples is not None: A__ : Tuple = min(len(UpperCAmelCase__ ), data_args.max_train_samples ) A__ : Optional[int] = train_dataset.select(range(UpperCAmelCase__ ) ) if data_args.max_val_samples is not None: A__ : List[Any] = eval_dataset.select(range(data_args.max_val_samples ) ) A__ : int = torchaudio.transforms.Resample(4_8_0_0_0, 1_6_0_0_0 ) # Preprocessing the datasets. # We need to read the aduio files as arrays and tokenize the targets. def speech_file_to_array_fn(UpperCAmelCase__ : Any ): A__ : Dict = torchaudio.load(batch["""path"""] ) A__ : Union[str, Any] = resampler(UpperCAmelCase__ ).squeeze().numpy() A__ : Any = 1_6_0_0_0 A__ : Any = batch["""text"""] return batch A__ : Any = train_dataset.map( UpperCAmelCase__, remove_columns=train_dataset.column_names, num_proc=data_args.preprocessing_num_workers, ) A__ : Optional[Any] = eval_dataset.map( UpperCAmelCase__, remove_columns=eval_dataset.column_names, num_proc=data_args.preprocessing_num_workers, ) def prepare_dataset(UpperCAmelCase__ : List[Any] ): # check that all files have the correct sampling rate assert ( len(set(batch["""sampling_rate"""] ) ) == 1 ), f'Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.' A__ : Any = processor( audio=batch["""speech"""], text=batch["""target_text"""], sampling_rate=batch["""sampling_rate"""][0] ) batch.update(UpperCAmelCase__ ) return batch A__ : Optional[int] = train_dataset.map( UpperCAmelCase__, remove_columns=train_dataset.column_names, batch_size=training_args.per_device_train_batch_size, batched=UpperCAmelCase__, num_proc=data_args.preprocessing_num_workers, ) A__ : int = eval_dataset.map( UpperCAmelCase__, remove_columns=eval_dataset.column_names, batch_size=training_args.per_device_train_batch_size, batched=UpperCAmelCase__, num_proc=data_args.preprocessing_num_workers, ) # Metric A__ : Optional[int] = datasets.load_metric("""wer""" ) def compute_metrics(UpperCAmelCase__ : List[str] ): A__ : str = pred.predictions A__ : List[Any] = np.argmax(UpperCAmelCase__, axis=-1 ) A__ : Dict = processor.tokenizer.pad_token_id A__ : Optional[int] = processor.batch_decode(UpperCAmelCase__ ) # we do not want to group tokens when computing the metrics A__ : Tuple = processor.batch_decode(pred.label_ids, group_tokens=UpperCAmelCase__ ) A__ : int = wer_metric.compute(predictions=UpperCAmelCase__, references=UpperCAmelCase__ ) return {"wer": wer} if model_args.freeze_feature_extractor: model.freeze_feature_extractor() # Data collator A__ : Any = DataCollatorCTCWithPadding(processor=UpperCAmelCase__, padding=UpperCAmelCase__ ) # Initialize our Trainer A__ : Any = CTCTrainer( model=UpperCAmelCase__, data_collator=UpperCAmelCase__, args=UpperCAmelCase__, compute_metrics=UpperCAmelCase__, train_dataset=train_dataset if training_args.do_train else None, eval_dataset=eval_dataset if training_args.do_eval else None, tokenizer=processor.feature_extractor, ) # Training if training_args.do_train: if last_checkpoint is not None: A__ : Optional[Any] = last_checkpoint elif os.path.isdir(model_args.model_name_or_path ): A__ : Any = model_args.model_name_or_path else: A__ : int = None # Save the feature_extractor and the tokenizer if is_main_process(training_args.local_rank ): processor.save_pretrained(training_args.output_dir ) A__ : List[Any] = trainer.train(resume_from_checkpoint=UpperCAmelCase__ ) trainer.save_model() A__ : int = train_result.metrics A__ : List[str] = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(UpperCAmelCase__ ) ) A__ : List[Any] = min(UpperCAmelCase__, len(UpperCAmelCase__ ) ) trainer.log_metrics("""train""", UpperCAmelCase__ ) trainer.save_metrics("""train""", UpperCAmelCase__ ) trainer.save_state() # Evaluation A__ : str = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) A__ : Dict = trainer.evaluate() A__ : Optional[Any] = data_args.max_val_samples if data_args.max_val_samples is not None else len(UpperCAmelCase__ ) A__ : str = min(UpperCAmelCase__, len(UpperCAmelCase__ ) ) trainer.log_metrics("""eval""", UpperCAmelCase__ ) trainer.save_metrics("""eval""", UpperCAmelCase__ ) return results if __name__ == "__main__": main()
358
"""simple docstring""" import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : List[Any] ): '''simple docstring''' super().__init__() A__ : int = nn.Linear(3 , 4 ) A__ : Union[str, Any] = nn.BatchNormad(4 ) A__ : Union[str, Any] = nn.Linear(4 , 5 ) def _UpperCamelCase ( self : str , snake_case : List[str] ): '''simple docstring''' return self.lineara(self.batchnorm(self.lineara(snake_case ) ) ) class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : int = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(snake_case , model.state_dict() ) A__ : List[str] = os.path.join(snake_case , """index.json""" ) self.assertTrue(os.path.isfile(snake_case ) ) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: A__ : List[str] = os.path.join(snake_case , F'{key}.dat' ) self.assertTrue(os.path.isfile(snake_case ) ) # TODO: add tests on the fact weights are properly loaded def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Union[str, Any] = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: A__ : str = torch.randn(2 , 3 , dtype=snake_case ) with TemporaryDirectory() as tmp_dir: A__ : List[str] = offload_weight(snake_case , """weight""" , snake_case , {} ) A__ : Union[str, Any] = os.path.join(snake_case , """weight.dat""" ) self.assertTrue(os.path.isfile(snake_case ) ) self.assertDictEqual(snake_case , {"""weight""": {"""shape""": [2, 3], """dtype""": str(snake_case ).split(""".""" )[1]}} ) A__ : str = load_offloaded_weight(snake_case , index["""weight"""] ) self.assertTrue(torch.equal(snake_case , snake_case ) ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : str = ModelForTest() A__ : Union[str, Any] = model.state_dict() A__ : Optional[int] = {k: v for k, v in state_dict.items() if """linear2""" not in k} A__ : List[Any] = {k: v for k, v in state_dict.items() if """linear2""" in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(snake_case , snake_case ) A__ : Dict = OffloadedWeightsLoader(state_dict=snake_case , save_folder=snake_case ) # Every key is there with the right value self.assertEqual(sorted(snake_case ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(snake_case , weight_map[key] ) ) A__ : int = {k: v for k, v in state_dict.items() if """weight""" in k} A__ : Tuple = {k: v for k, v in state_dict.items() if """weight""" not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(snake_case , snake_case ) A__ : Optional[Any] = OffloadedWeightsLoader(state_dict=snake_case , save_folder=snake_case ) # Every key is there with the right value self.assertEqual(sorted(snake_case ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(snake_case , weight_map[key] ) ) with TemporaryDirectory() as tmp_dir: offload_state_dict(snake_case , snake_case ) # Duplicates are removed A__ : int = OffloadedWeightsLoader(state_dict=snake_case , save_folder=snake_case ) # Every key is there with the right value self.assertEqual(sorted(snake_case ) , sorted(state_dict.keys() ) ) for key, param in state_dict.items(): self.assertTrue(torch.allclose(snake_case , weight_map[key] ) ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : List[str] = {"""a.1""": 0, """a.10""": 1, """a.2""": 2} A__ : str = extract_submodules_state_dict(snake_case , ["""a.1""", """a.2"""] ) self.assertDictEqual(snake_case , {"""a.1""": 0, """a.2""": 2} ) A__ : Dict = {"""a.1.a""": 0, """a.10.a""": 1, """a.2.a""": 2} A__ : int = extract_submodules_state_dict(snake_case , ["""a.1""", """a.2"""] ) self.assertDictEqual(snake_case , {"""a.1.a""": 0, """a.2.a""": 2} )
296
0
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices A_ = logging.get_logger(__name__) A_ = { '''microsoft/focalnet-tiny''': '''https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json''', } class __SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase ): snake_case_ = 'focalnet' def __init__( self : Union[str, Any] , snake_case : Tuple=224 , snake_case : Tuple=4 , snake_case : List[Any]=3 , snake_case : int=96 , snake_case : List[Any]=False , snake_case : List[Any]=[192, 384, 768, 768] , snake_case : Union[str, Any]=[2, 2, 6, 2] , snake_case : str=[2, 2, 2, 2] , snake_case : Tuple=[3, 3, 3, 3] , snake_case : List[str]="gelu" , snake_case : Any=4.0 , snake_case : Any=0.0 , snake_case : Optional[Any]=0.1 , snake_case : Union[str, Any]=False , snake_case : Any=1e-4 , snake_case : Dict=False , snake_case : Optional[Any]=False , snake_case : Dict=False , snake_case : Optional[Any]=0.02 , snake_case : Dict=1e-5 , snake_case : Optional[int]=32 , snake_case : int=None , snake_case : List[Any]=None , **snake_case : Any , ): '''simple docstring''' super().__init__(**snake_case ) A__ : Tuple = image_size A__ : Dict = patch_size A__ : Tuple = num_channels A__ : str = embed_dim A__ : Union[str, Any] = use_conv_embed A__ : Union[str, Any] = hidden_sizes A__ : int = depths A__ : str = focal_levels A__ : str = focal_windows A__ : Union[str, Any] = hidden_act A__ : Any = mlp_ratio A__ : Any = hidden_dropout_prob A__ : str = drop_path_rate A__ : Dict = use_layerscale A__ : str = layerscale_value A__ : Optional[Any] = use_post_layernorm A__ : Any = use_post_layernorm_in_modulation A__ : Optional[int] = normalize_modulator A__ : Dict = initializer_range A__ : str = layer_norm_eps A__ : int = encoder_stride A__ : List[Any] = ["""stem"""] + [F'stage{idx}' for idx in range(1 , len(self.depths ) + 1 )] A__ : str = get_aligned_output_features_output_indices( out_features=snake_case , out_indices=snake_case , stage_names=self.stage_names )
359
"""simple docstring""" import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class __SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , snake_case : str , snake_case : List[Any]=13 , snake_case : Union[str, Any]=7 , snake_case : Optional[Any]=True , snake_case : str=True , snake_case : Dict=False , snake_case : Union[str, Any]=True , snake_case : Optional[Any]=99 , snake_case : str=32 , snake_case : Tuple=5 , snake_case : List[str]=4 , snake_case : Optional[int]=37 , snake_case : str="gelu" , snake_case : Tuple=0.1 , snake_case : Optional[int]=0.1 , snake_case : int=512 , snake_case : List[str]=16 , snake_case : str=2 , snake_case : Optional[int]=0.02 , snake_case : str=3 , snake_case : Dict=4 , snake_case : Optional[Any]=None , ): '''simple docstring''' A__ : int = parent A__ : Union[str, Any] = batch_size A__ : Optional[int] = seq_length A__ : List[Any] = is_training A__ : List[str] = use_input_mask A__ : Optional[Any] = use_token_type_ids A__ : List[Any] = use_labels A__ : Union[str, Any] = vocab_size A__ : List[Any] = hidden_size A__ : Any = num_hidden_layers A__ : Any = num_attention_heads A__ : Optional[int] = intermediate_size A__ : Any = hidden_act A__ : Tuple = hidden_dropout_prob A__ : Dict = attention_probs_dropout_prob A__ : Optional[int] = max_position_embeddings A__ : Tuple = type_vocab_size A__ : Union[str, Any] = type_sequence_label_size A__ : List[str] = initializer_range A__ : Any = num_labels A__ : Any = num_choices A__ : int = scope def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Tuple = None if self.use_input_mask: A__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) A__ : Union[str, Any] = None if self.use_token_type_ids: A__ : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A__ : int = None A__ : int = None A__ : List[str] = None if self.use_labels: A__ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : Dict = ids_tensor([self.batch_size] , self.num_choices ) A__ : Union[str, Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCamelCase ( self : Tuple ): '''simple docstring''' return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case , initializer_range=self.initializer_range , ) def _UpperCamelCase ( self : Optional[int] , snake_case : Dict , snake_case : Any , snake_case : Dict , snake_case : Any , snake_case : Union[str, Any] , snake_case : Tuple , snake_case : Optional[Any] ): '''simple docstring''' A__ : Optional[Any] = BioGptModel(config=snake_case ) model.to(snake_case ) model.eval() A__ : List[Any] = model(snake_case , attention_mask=snake_case ) A__ : Dict = model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : Optional[int] , snake_case : Dict , snake_case : Optional[int] , snake_case : List[str] , snake_case : str , snake_case : Optional[Any] , snake_case : List[str] , snake_case : List[Any] , snake_case : Tuple , snake_case : Optional[Any] , ): '''simple docstring''' A__ : List[str] = BioGptForCausalLM(config=snake_case ) model.to(snake_case ) model.eval() A__ : Union[str, Any] = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCamelCase ( self : Any , snake_case : str , snake_case : Tuple , snake_case : int , snake_case : Optional[Any] , snake_case : Any , *snake_case : Dict ): '''simple docstring''' A__ : Union[str, Any] = BioGptModel(config=snake_case ) model.to(snake_case ) model.eval() # create attention mask A__ : List[Any] = torch.ones(input_ids.shape , dtype=torch.long , device=snake_case ) A__ : Any = self.seq_length // 2 A__ : str = 0 # first forward pass A__ , A__ : List[Any] = model(snake_case , attention_mask=snake_case ).to_tuple() # create hypothetical next token and extent to next_input_ids A__ : int = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids A__ : List[str] = ids_tensor((1,) , snake_case ).item() + 1 A__ : Optional[int] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) A__ : int = random_other_next_tokens # append to next input_ids and attn_mask A__ : str = torch.cat([input_ids, next_tokens] , dim=-1 ) A__ : List[Any] = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=snake_case )] , dim=1 , ) # get two different outputs A__ : Union[str, Any] = model(snake_case , attention_mask=snake_case )["""last_hidden_state"""] A__ : Optional[int] = model(snake_case , past_key_values=snake_case , attention_mask=snake_case )["""last_hidden_state"""] # select random slice A__ : List[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() A__ : List[str] = output_from_no_past[:, -1, random_slice_idx].detach() A__ : Any = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(snake_case , snake_case , atol=1e-3 ) ) def _UpperCamelCase ( self : int , snake_case : Optional[Any] , snake_case : Optional[Any] , snake_case : str , snake_case : int , snake_case : Optional[Any] , *snake_case : str ): '''simple docstring''' A__ : Dict = BioGptModel(config=snake_case ).to(snake_case ).eval() A__ : Tuple = torch.ones(input_ids.shape , dtype=torch.long , device=snake_case ) # first forward pass A__ : Dict = model(snake_case , attention_mask=snake_case , use_cache=snake_case ) A__ , A__ : List[Any] = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids A__ : Union[str, Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ : int = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and A__ : str = torch.cat([input_ids, next_tokens] , dim=-1 ) A__ : Optional[int] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) A__ : Any = model(snake_case , attention_mask=snake_case )["""last_hidden_state"""] A__ : Union[str, Any] = model(snake_case , attention_mask=snake_case , past_key_values=snake_case )[ """last_hidden_state""" ] # select random slice A__ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() A__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() A__ : List[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(snake_case , snake_case , atol=1e-3 ) ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Tuple , snake_case : Union[str, Any] , snake_case : Optional[Any] , snake_case : Any , snake_case : Tuple , *snake_case : Union[str, Any] , snake_case : Union[str, Any]=False ): '''simple docstring''' A__ : Tuple = BioGptForCausalLM(snake_case ) model.to(snake_case ) if gradient_checkpointing: model.gradient_checkpointing_enable() A__ : Optional[Any] = model(snake_case , labels=snake_case ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def _UpperCamelCase ( self : int , snake_case : Optional[Any] , *snake_case : Optional[int] ): '''simple docstring''' A__ : int = BioGptModel(snake_case ) A__ : Union[str, Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def _UpperCamelCase ( self : Any , snake_case : Dict , snake_case : Tuple , snake_case : int , snake_case : Union[str, Any] , snake_case : Dict , *snake_case : Any ): '''simple docstring''' A__ : Union[str, Any] = self.num_labels A__ : int = BioGptForTokenClassification(snake_case ) model.to(snake_case ) model.eval() A__ : str = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : List[str] = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) : str = config_and_inputs A__ : Union[str, Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase ): snake_case_ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) snake_case_ = (BioGptForCausalLM,) if is_torch_available() else () snake_case_ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = False def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : List[str] = BioGptModelTester(self ) A__ : List[Any] = ConfigTester(self , config_class=snake_case , hidden_size=37 ) def _UpperCamelCase ( self : int ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Any ): '''simple docstring''' A__ : int = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A__ : str = type self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*snake_case ) def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*snake_case , gradient_checkpointing=snake_case ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*snake_case ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*snake_case ) def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*snake_case ) @slow def _UpperCamelCase ( self : str ): '''simple docstring''' A__ : Tuple = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(snake_case ) A__ : Optional[int] = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) A__ : Any = """left""" # Define PAD Token = EOS Token = 50256 A__ : Optional[int] = tokenizer.eos_token A__ : Dict = model.config.eos_token_id # use different length sentences to test batching A__ : Union[str, Any] = [ """Hello, my dog is a little""", """Today, I""", ] A__ : List[str] = tokenizer(snake_case , return_tensors="""pt""" , padding=snake_case ) A__ : str = inputs["""input_ids"""].to(snake_case ) A__ : Dict = model.generate( input_ids=snake_case , attention_mask=inputs["""attention_mask"""].to(snake_case ) , ) A__ : Optional[int] = tokenizer(sentences[0] , return_tensors="""pt""" ).input_ids.to(snake_case ) A__ : Any = model.generate(input_ids=snake_case ) A__ : List[str] = inputs_non_padded.shape[-1] - inputs["""attention_mask"""][-1].long().sum().cpu().item() A__ : str = tokenizer(sentences[1] , return_tensors="""pt""" ).input_ids.to(snake_case ) A__ : Dict = model.generate(input_ids=snake_case , max_length=model.config.max_length - num_paddings ) A__ : Optional[Any] = tokenizer.batch_decode(snake_case , skip_special_tokens=snake_case ) A__ : List[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=snake_case ) A__ : str = tokenizer.decode(output_padded[0] , skip_special_tokens=snake_case ) A__ : Optional[int] = [ """Hello, my dog is a little bit bigger than a little bit.""", """Today, I have a good idea of how to use the information""", ] self.assertListEqual(snake_case , snake_case ) self.assertListEqual(snake_case , [non_padded_sentence, padded_sentence] ) @slow def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ : Optional[Any] = BioGptModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) def _UpperCamelCase ( self : str ): '''simple docstring''' A__ , A__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() A__ : Optional[int] = 3 A__ : List[Any] = input_dict["""input_ids"""] A__ : Dict = input_ids.ne(1 ).to(snake_case ) A__ : Optional[Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) A__ : Union[str, Any] = BioGptForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : int = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ , A__ : str = self.model_tester.prepare_config_and_inputs_for_common() A__ : Any = 3 A__ : List[Any] = """multi_label_classification""" A__ : Dict = input_dict["""input_ids"""] A__ : Tuple = input_ids.ne(1 ).to(snake_case ) A__ : Any = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) A__ : Tuple = BioGptForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : List[str] = model(snake_case , attention_mask=snake_case , labels=snake_case ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _UpperCamelCase ( self : List[str] ): '''simple docstring''' A__ : Optional[Any] = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) A__ : str = torch.tensor([[2, 4805, 9, 656, 21]] ) A__ : Dict = model(snake_case )[0] A__ : Tuple = 4_2384 A__ : str = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , snake_case ) A__ : str = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) ) @slow def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : Tuple = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) A__ : Any = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(snake_case ) torch.manual_seed(0 ) A__ : Tuple = tokenizer("""COVID-19 is""" , return_tensors="""pt""" ).to(snake_case ) A__ : Optional[int] = model.generate( **snake_case , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=snake_case , ) A__ : Optional[int] = tokenizer.decode(output_ids[0] , skip_special_tokens=snake_case ) A__ : List[str] = ( """COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the""" """ causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and""" """ territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),""" """ and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and""" """ more than 800,000 deaths.""" ) self.assertEqual(snake_case , snake_case )
296
0
"""simple docstring""" import argparse import requests import torch from PIL import Image from transformers import SwinConfig, SwinForMaskedImageModeling, ViTImageProcessor def _lowerCAmelCase ( UpperCAmelCase__ : Optional[Any] ) ->str: A__ : List[str] = SwinConfig(image_size=1_9_2 ) if "base" in model_name: A__ : Optional[Any] = 6 A__ : Union[str, Any] = 1_2_8 A__ : Dict = (2, 2, 1_8, 2) A__ : Optional[int] = (4, 8, 1_6, 3_2) elif "large" in model_name: A__ : Any = 1_2 A__ : str = 1_9_2 A__ : List[str] = (2, 2, 1_8, 2) A__ : Any = (6, 1_2, 2_4, 4_8) else: raise ValueError("""Model not supported, only supports base and large variants""" ) A__ : Optional[int] = window_size A__ : Optional[int] = embed_dim A__ : Dict = depths A__ : List[str] = num_heads return config def _lowerCAmelCase ( UpperCAmelCase__ : Optional[Any] ) ->Optional[int]: if "encoder.mask_token" in name: A__ : Dict = name.replace("""encoder.mask_token""", """embeddings.mask_token""" ) if "encoder.patch_embed.proj" in name: A__ : List[str] = name.replace("""encoder.patch_embed.proj""", """embeddings.patch_embeddings.projection""" ) if "encoder.patch_embed.norm" in name: A__ : Union[str, Any] = name.replace("""encoder.patch_embed.norm""", """embeddings.norm""" ) if "attn.proj" in name: A__ : List[Any] = name.replace("""attn.proj""", """attention.output.dense""" ) if "attn" in name: A__ : List[str] = name.replace("""attn""", """attention.self""" ) if "norm1" in name: A__ : Tuple = name.replace("""norm1""", """layernorm_before""" ) if "norm2" in name: A__ : Optional[Any] = name.replace("""norm2""", """layernorm_after""" ) if "mlp.fc1" in name: A__ : str = name.replace("""mlp.fc1""", """intermediate.dense""" ) if "mlp.fc2" in name: A__ : str = name.replace("""mlp.fc2""", """output.dense""" ) if name == "encoder.norm.weight": A__ : List[str] = """layernorm.weight""" if name == "encoder.norm.bias": A__ : Dict = """layernorm.bias""" if "decoder" in name: pass else: A__ : Tuple = """swin.""" + name return name def _lowerCAmelCase ( UpperCAmelCase__ : str, UpperCAmelCase__ : List[Any] ) ->Tuple: for key in orig_state_dict.copy().keys(): A__ : str = orig_state_dict.pop(UpperCAmelCase__ ) if "attn_mask" in key: pass elif "qkv" in key: A__ : Optional[Any] = key.split(""".""" ) A__ : Union[str, Any] = int(key_split[2] ) A__ : Tuple = int(key_split[4] ) A__ : int = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: A__ : Optional[Any] = val[:dim, :] A__ : int = val[ dim : dim * 2, : ] A__ : Union[str, Any] = val[-dim:, :] else: A__ : List[Any] = val[ :dim ] A__ : List[str] = val[ dim : dim * 2 ] A__ : int = val[ -dim: ] else: A__ : Optional[Any] = val return orig_state_dict def _lowerCAmelCase ( UpperCAmelCase__ : List[str], UpperCAmelCase__ : Any, UpperCAmelCase__ : int, UpperCAmelCase__ : Tuple ) ->List[Any]: A__ : Tuple = torch.load(UpperCAmelCase__, map_location="""cpu""" )["""model"""] A__ : List[Any] = get_swin_config(UpperCAmelCase__ ) A__ : Tuple = SwinForMaskedImageModeling(UpperCAmelCase__ ) model.eval() A__ : Dict = convert_state_dict(UpperCAmelCase__, UpperCAmelCase__ ) model.load_state_dict(UpperCAmelCase__ ) A__ : Optional[int] = """http://images.cocodataset.org/val2017/000000039769.jpg""" A__ : Tuple = ViTImageProcessor(size={"""height""": 1_9_2, """width""": 1_9_2} ) A__ : str = Image.open(requests.get(UpperCAmelCase__, stream=UpperCAmelCase__ ).raw ) A__ : List[Any] = image_processor(images=UpperCAmelCase__, return_tensors="""pt""" ) with torch.no_grad(): A__ : Optional[Any] = model(**UpperCAmelCase__ ).logits print(outputs.keys() ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(f'Saving model {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(UpperCAmelCase__ ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(UpperCAmelCase__ ) if push_to_hub: print(f'Pushing model and image processor for {model_name} to hub' ) model.push_to_hub(f'microsoft/{model_name}' ) image_processor.push_to_hub(f'microsoft/{model_name}' ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''swin-base-simmim-window6-192''', type=str, choices=['''swin-base-simmim-window6-192''', '''swin-large-simmim-window12-192'''], help='''Name of the Swin SimMIM model you\'d like to convert.''', ) parser.add_argument( '''--checkpoint_path''', default='''/Users/nielsrogge/Documents/SwinSimMIM/simmim_pretrain__swin_base__img192_window6__100ep.pth''', type=str, help='''Path to the original PyTorch checkpoint (.pth file).''', ) 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 or not to push the converted model to the 🤗 hub.''' ) A_ = parser.parse_args() convert_swin_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
360
"""simple docstring""" 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 SPIECE_UNDERLINE, logging A_ = logging.get_logger(__name__) A_ = {'''vocab_file''': '''spiece.model'''} A_ = { '''vocab_file''': { '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model''', '''xlnet-large-cased''': '''https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model''', } } A_ = { '''xlnet-base-cased''': None, '''xlnet-large-cased''': None, } # Segments (not really needed) A_ = 0 A_ = 1 A_ = 2 A_ = 3 A_ = 4 class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = 'left' def __init__( self : Dict , snake_case : int , snake_case : List[Any]=False , snake_case : List[str]=True , snake_case : Dict=False , snake_case : Optional[Any]="<s>" , snake_case : List[str]="</s>" , snake_case : Tuple="<unk>" , snake_case : Tuple="<sep>" , snake_case : Union[str, Any]="<pad>" , snake_case : Dict="<cls>" , snake_case : Optional[Any]="<mask>" , snake_case : Optional[int]=["<eop>", "<eod>"] , snake_case : Optional[Dict[str, Any]] = None , **snake_case : Dict , ): '''simple docstring''' A__ : Optional[int] = AddedToken(snake_case , lstrip=snake_case , rstrip=snake_case ) if isinstance(snake_case , snake_case ) else mask_token A__ : Union[str, Any] = {} 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 , additional_special_tokens=snake_case , sp_model_kwargs=self.sp_model_kwargs , **snake_case , ) A__ : str = 3 A__ : str = do_lower_case A__ : Optional[Any] = remove_space A__ : List[Any] = keep_accents A__ : Union[str, Any] = vocab_file A__ : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(snake_case ) @property def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' return len(self.sp_model ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : 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 : str ): '''simple docstring''' A__ : int = self.__dict__.copy() A__ : int = None return state def __setstate__( self : Tuple , snake_case : Union[str, Any] ): '''simple docstring''' A__ : int = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): A__ : Optional[int] = {} A__ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _UpperCamelCase ( self : List[str] , snake_case : Optional[Any] ): '''simple docstring''' if self.remove_space: A__ : Optional[Any] = """ """.join(inputs.strip().split() ) else: A__ : Dict = inputs A__ : str = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: A__ : Any = unicodedata.normalize("""NFKD""" , snake_case ) A__ : Optional[int] = """""".join([c for c in outputs if not unicodedata.combining(snake_case )] ) if self.do_lower_case: A__ : Any = outputs.lower() return outputs def _UpperCamelCase ( self : Union[str, Any] , snake_case : str ): '''simple docstring''' A__ : Dict = self.preprocess_text(snake_case ) A__ : Dict = self.sp_model.encode(snake_case , out_type=snake_case ) A__ : Optional[int] = [] for piece in pieces: if len(snake_case ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): A__ : Optional[Any] = 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__ : Any = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(snake_case ) else: new_pieces.append(snake_case ) return new_pieces def _UpperCamelCase ( self : List[str] , snake_case : Tuple ): '''simple docstring''' return self.sp_model.PieceToId(snake_case ) def _UpperCamelCase ( self : List[str] , snake_case : Any ): '''simple docstring''' return self.sp_model.IdToPiece(snake_case ) def _UpperCamelCase ( self : Optional[int] , snake_case : Any ): '''simple docstring''' A__ : Union[str, Any] = """""".join(snake_case ).replace(snake_case , """ """ ).strip() return out_string def _UpperCamelCase ( self : int , snake_case : List[int] , snake_case : bool = False , snake_case : bool = None , snake_case : bool = True , **snake_case : Union[str, Any] , ): '''simple docstring''' A__ : List[str] = kwargs.pop("""use_source_tokenizer""" , snake_case ) A__ : Any = self.convert_ids_to_tokens(snake_case , skip_special_tokens=snake_case ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 A__ : Any = [] A__ : Any = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(snake_case ) ) A__ : str = [] sub_texts.append(snake_case ) else: current_sub_text.append(snake_case ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(snake_case ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens A__ : Dict = """""".join(snake_case ) A__ : int = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: A__ : Tuple = self.clean_up_tokenization(snake_case ) return clean_text else: return text def _UpperCamelCase ( self : str , snake_case : List[int] , snake_case : Optional[List[int]] = None ): '''simple docstring''' A__ : Tuple = [self.sep_token_id] A__ : Dict = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _UpperCamelCase ( self : Dict , snake_case : List[int] , snake_case : Optional[List[int]] = None , snake_case : bool = False ): '''simple docstring''' 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 ([0] * len(snake_case )) + [1] + ([0] * len(snake_case )) + [1, 1] return ([0] * len(snake_case )) + [1, 1] def _UpperCamelCase ( self : str , snake_case : List[int] , snake_case : Optional[List[int]] = None ): '''simple docstring''' A__ : Any = [self.sep_token_id] A__ : int = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _UpperCamelCase ( self : Optional[Any] , snake_case : str , snake_case : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(snake_case ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A__ : List[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__ : Optional[Any] = self.sp_model.serialized_model_proto() fi.write(snake_case ) return (out_vocab_file,)
296
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ =logging.get_logger(__name__) A_ ={ '''YituTech/conv-bert-base''': '''https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json''', '''YituTech/conv-bert-medium-small''': ( '''https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json''' ), '''YituTech/conv-bert-small''': '''https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json''', # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = 'convbert' def __init__( self : Optional[int] , snake_case : Optional[Any]=3_0522 , snake_case : List[Any]=768 , snake_case : Tuple=12 , snake_case : Any=12 , snake_case : str=3072 , snake_case : Optional[int]="gelu" , snake_case : Any=0.1 , snake_case : int=0.1 , snake_case : Dict=512 , snake_case : Optional[Any]=2 , snake_case : Optional[int]=0.02 , snake_case : Optional[int]=1e-12 , snake_case : str=1 , snake_case : Optional[Any]=0 , snake_case : str=2 , snake_case : int=768 , snake_case : Union[str, Any]=2 , snake_case : Optional[int]=9 , snake_case : Optional[int]=1 , snake_case : str=None , **snake_case : List[Any] , ): '''simple docstring''' super().__init__( pad_token_id=snake_case , bos_token_id=snake_case , eos_token_id=snake_case , **snake_case , ) A__ : Dict = vocab_size A__ : Dict = hidden_size A__ : int = num_hidden_layers A__ : Any = num_attention_heads A__ : Dict = intermediate_size A__ : Union[str, Any] = hidden_act A__ : List[Any] = hidden_dropout_prob A__ : Tuple = attention_probs_dropout_prob A__ : Optional[Any] = max_position_embeddings A__ : Dict = type_vocab_size A__ : Optional[int] = initializer_range A__ : Union[str, Any] = layer_norm_eps A__ : str = embedding_size A__ : int = head_ratio A__ : Optional[Any] = conv_kernel_size A__ : List[str] = num_groups A__ : Union[str, Any] = classifier_dropout class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): @property def _UpperCamelCase ( self : str ): '''simple docstring''' if self.task == "multiple-choice": A__ : str = {0: """batch""", 1: """choice""", 2: """sequence"""} else: A__ : List[Any] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
361
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) def _lowerCAmelCase ( UpperCAmelCase__ : List[Any] ) ->List[str]: A__ : Union[str, Any] = DPTConfig() if "large" in checkpoint_url: A__ : int = 1_0_2_4 A__ : Union[str, Any] = 4_0_9_6 A__ : Optional[int] = 2_4 A__ : int = 1_6 A__ : Union[str, Any] = [5, 1_1, 1_7, 2_3] A__ : Tuple = [2_5_6, 5_1_2, 1_0_2_4, 1_0_2_4] A__ : Tuple = (1, 3_8_4, 3_8_4) if "ade" in checkpoint_url: A__ : Optional[int] = True A__ : int = 1_5_0 A__ : Union[str, Any] = """huggingface/label-files""" A__ : List[Any] = """ade20k-id2label.json""" A__ : Union[str, Any] = json.load(open(cached_download(hf_hub_url(UpperCAmelCase__, UpperCAmelCase__, repo_type="""dataset""" ) ), """r""" ) ) A__ : List[Any] = {int(UpperCAmelCase__ ): v for k, v in idalabel.items()} A__ : Dict = idalabel A__ : List[Any] = {v: k for k, v in idalabel.items()} A__ : Optional[Any] = [1, 1_5_0, 4_8_0, 4_8_0] return config, expected_shape def _lowerCAmelCase ( UpperCAmelCase__ : int ) ->Any: A__ : List[Any] = ["""pretrained.model.head.weight""", """pretrained.model.head.bias"""] for k in ignore_keys: state_dict.pop(UpperCAmelCase__, UpperCAmelCase__ ) def _lowerCAmelCase ( UpperCAmelCase__ : Union[str, Any] ) ->List[str]: if ( "pretrained.model" in name and "cls_token" not in name and "pos_embed" not in name and "patch_embed" not in name ): A__ : str = name.replace("""pretrained.model""", """dpt.encoder""" ) if "pretrained.model" in name: A__ : Dict = name.replace("""pretrained.model""", """dpt.embeddings""" ) if "patch_embed" in name: A__ : List[Any] = name.replace("""patch_embed""", """patch_embeddings""" ) if "pos_embed" in name: A__ : int = name.replace("""pos_embed""", """position_embeddings""" ) if "attn.proj" in name: A__ : Tuple = name.replace("""attn.proj""", """attention.output.dense""" ) if "proj" in name and "project" not in name: A__ : List[Any] = name.replace("""proj""", """projection""" ) if "blocks" in name: A__ : Optional[Any] = name.replace("""blocks""", """layer""" ) if "mlp.fc1" in name: A__ : int = name.replace("""mlp.fc1""", """intermediate.dense""" ) if "mlp.fc2" in name: A__ : List[str] = name.replace("""mlp.fc2""", """output.dense""" ) if "norm1" in name: A__ : Any = name.replace("""norm1""", """layernorm_before""" ) if "norm2" in name: A__ : List[str] = name.replace("""norm2""", """layernorm_after""" ) if "scratch.output_conv" in name: A__ : Optional[int] = name.replace("""scratch.output_conv""", """head""" ) if "scratch" in name: A__ : List[str] = name.replace("""scratch""", """neck""" ) if "layer1_rn" in name: A__ : List[str] = name.replace("""layer1_rn""", """convs.0""" ) if "layer2_rn" in name: A__ : Optional[int] = name.replace("""layer2_rn""", """convs.1""" ) if "layer3_rn" in name: A__ : Any = name.replace("""layer3_rn""", """convs.2""" ) if "layer4_rn" in name: A__ : Any = name.replace("""layer4_rn""", """convs.3""" ) if "refinenet" in name: A__ : Union[str, Any] = int(name[len("""neck.refinenet""" ) : len("""neck.refinenet""" ) + 1] ) # tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3 A__ : str = name.replace(f'refinenet{layer_idx}', f'fusion_stage.layers.{abs(layer_idx-4 )}' ) if "out_conv" in name: A__ : Optional[Any] = name.replace("""out_conv""", """projection""" ) if "resConfUnit1" in name: A__ : List[Any] = name.replace("""resConfUnit1""", """residual_layer1""" ) if "resConfUnit2" in name: A__ : Tuple = name.replace("""resConfUnit2""", """residual_layer2""" ) if "conv1" in name: A__ : Tuple = name.replace("""conv1""", """convolution1""" ) if "conv2" in name: A__ : List[Any] = name.replace("""conv2""", """convolution2""" ) # readout blocks if "pretrained.act_postprocess1.0.project.0" in name: A__ : Union[str, Any] = name.replace("""pretrained.act_postprocess1.0.project.0""", """neck.reassemble_stage.readout_projects.0.0""" ) if "pretrained.act_postprocess2.0.project.0" in name: A__ : Tuple = name.replace("""pretrained.act_postprocess2.0.project.0""", """neck.reassemble_stage.readout_projects.1.0""" ) if "pretrained.act_postprocess3.0.project.0" in name: A__ : Optional[Any] = name.replace("""pretrained.act_postprocess3.0.project.0""", """neck.reassemble_stage.readout_projects.2.0""" ) if "pretrained.act_postprocess4.0.project.0" in name: A__ : Optional[Any] = name.replace("""pretrained.act_postprocess4.0.project.0""", """neck.reassemble_stage.readout_projects.3.0""" ) # resize blocks if "pretrained.act_postprocess1.3" in name: A__ : Any = name.replace("""pretrained.act_postprocess1.3""", """neck.reassemble_stage.layers.0.projection""" ) if "pretrained.act_postprocess1.4" in name: A__ : List[Any] = name.replace("""pretrained.act_postprocess1.4""", """neck.reassemble_stage.layers.0.resize""" ) if "pretrained.act_postprocess2.3" in name: A__ : Dict = name.replace("""pretrained.act_postprocess2.3""", """neck.reassemble_stage.layers.1.projection""" ) if "pretrained.act_postprocess2.4" in name: A__ : Optional[Any] = name.replace("""pretrained.act_postprocess2.4""", """neck.reassemble_stage.layers.1.resize""" ) if "pretrained.act_postprocess3.3" in name: A__ : Union[str, Any] = name.replace("""pretrained.act_postprocess3.3""", """neck.reassemble_stage.layers.2.projection""" ) if "pretrained.act_postprocess4.3" in name: A__ : Optional[int] = name.replace("""pretrained.act_postprocess4.3""", """neck.reassemble_stage.layers.3.projection""" ) if "pretrained.act_postprocess4.4" in name: A__ : Dict = name.replace("""pretrained.act_postprocess4.4""", """neck.reassemble_stage.layers.3.resize""" ) if "pretrained" in name: A__ : Union[str, Any] = name.replace("""pretrained""", """dpt""" ) if "bn" in name: A__ : Union[str, Any] = name.replace("""bn""", """batch_norm""" ) if "head" in name: A__ : Dict = name.replace("""head""", """head.head""" ) if "encoder.norm" in name: A__ : Optional[int] = name.replace("""encoder.norm""", """layernorm""" ) if "auxlayer" in name: A__ : List[str] = name.replace("""auxlayer""", """auxiliary_head.head""" ) return name def _lowerCAmelCase ( UpperCAmelCase__ : int, UpperCAmelCase__ : Dict ) ->str: for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) A__ : Any = state_dict.pop(f'dpt.encoder.layer.{i}.attn.qkv.weight' ) A__ : Tuple = state_dict.pop(f'dpt.encoder.layer.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict A__ : List[str] = in_proj_weight[: config.hidden_size, :] A__ : int = in_proj_bias[: config.hidden_size] A__ : Tuple = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] A__ : Any = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] A__ : str = in_proj_weight[ -config.hidden_size :, : ] A__ : Optional[Any] = in_proj_bias[-config.hidden_size :] def _lowerCAmelCase ( ) ->List[str]: A__ : int = """http://images.cocodataset.org/val2017/000000039769.jpg""" A__ : int = Image.open(requests.get(UpperCAmelCase__, stream=UpperCAmelCase__ ).raw ) return im @torch.no_grad() def _lowerCAmelCase ( UpperCAmelCase__ : int, UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : str, UpperCAmelCase__ : int ) ->str: A__ , A__ : Dict = get_dpt_config(UpperCAmelCase__ ) # load original state_dict from URL A__ : Any = torch.hub.load_state_dict_from_url(UpperCAmelCase__, map_location="""cpu""" ) # remove certain keys remove_ignore_keys_(UpperCAmelCase__ ) # rename keys for key in state_dict.copy().keys(): A__ : int = state_dict.pop(UpperCAmelCase__ ) A__ : str = val # read in qkv matrices read_in_q_k_v(UpperCAmelCase__, UpperCAmelCase__ ) # load HuggingFace model A__ : Optional[Any] = DPTForSemanticSegmentation(UpperCAmelCase__ ) if """ade""" in checkpoint_url else DPTForDepthEstimation(UpperCAmelCase__ ) model.load_state_dict(UpperCAmelCase__ ) model.eval() # Check outputs on an image A__ : Optional[Any] = 4_8_0 if """ade""" in checkpoint_url else 3_8_4 A__ : Dict = DPTImageProcessor(size=UpperCAmelCase__ ) A__ : Optional[int] = prepare_img() A__ : Any = image_processor(UpperCAmelCase__, return_tensors="""pt""" ) # forward pass A__ : List[str] = model(**UpperCAmelCase__ ).logits if """ade""" in checkpoint_url else model(**UpperCAmelCase__ ).predicted_depth # Assert logits A__ : Optional[Any] = torch.tensor([[6.3199, 6.3629, 6.4148], [6.3850, 6.3615, 6.4166], [6.3519, 6.3176, 6.3575]] ) if "ade" in checkpoint_url: A__ : Optional[int] = torch.tensor([[4.0480, 4.2420, 4.4360], [4.3124, 4.5693, 4.8261], [4.5768, 4.8965, 5.2163]] ) assert outputs.shape == torch.Size(UpperCAmelCase__ ) assert ( torch.allclose(outputs[0, 0, :3, :3], UpperCAmelCase__, atol=1e-4 ) if "ade" in checkpoint_url else torch.allclose(outputs[0, :3, :3], UpperCAmelCase__ ) ) Path(UpperCAmelCase__ ).mkdir(exist_ok=UpperCAmelCase__ ) print(f'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(UpperCAmelCase__ ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(UpperCAmelCase__ ) if push_to_hub: print("""Pushing model to hub...""" ) model.push_to_hub( repo_path_or_name=Path(UpperCAmelCase__, UpperCAmelCase__ ), organization="""nielsr""", commit_message="""Add model""", use_temp_dir=UpperCAmelCase__, ) image_processor.push_to_hub( repo_path_or_name=Path(UpperCAmelCase__, UpperCAmelCase__ ), organization="""nielsr""", commit_message="""Add image processor""", use_temp_dir=UpperCAmelCase__, ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt''', type=str, help='''URL of the original DPT checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', action='''store_true''', ) parser.add_argument( '''--model_name''', default='''dpt-large''', type=str, help='''Name of the model, in case you\'re pushing to the hub.''', ) A_ = parser.parse_args() convert_dpt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
296
0
"""simple docstring""" import collections import importlib.util import os import re from pathlib import Path A_ = '''src/transformers''' # Matches is_xxx_available() A_ = re.compile(r'''is\_([a-z_]*)_available()''') # Catches a one-line _import_struct = {xxx} A_ = re.compile(r'''^_import_structure\s+=\s+\{([^\}]+)\}''') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] A_ = re.compile(r'''\s+"\S*":\s+\[([^\]]*)\]''') # Catches a line if not is_foo_available A_ = re.compile(r'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''') # Catches a line _import_struct["bla"].append("foo") A_ = re.compile(r'''^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)''') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] A_ = re.compile(r'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''') # Catches a line with an object between quotes and a comma: "MyModel", A_ = re.compile('''^\s+"([^"]+)",''') # Catches a line with objects between brackets only: ["foo", "bar"], A_ = re.compile('''^\s+\[([^\]]+)\]''') # Catches a line with from foo import bar, bla, boo A_ = re.compile(r'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') # Catches a line with try: A_ = re.compile(r'''^\s*try:''') # Catches a line with else: A_ = re.compile(r'''^\s*else:''') def _lowerCAmelCase ( UpperCAmelCase__ : str ) ->Union[str, Any]: if _re_test_backend.search(UpperCAmelCase__ ) is None: return None A__ : Tuple = [b[0] for b in _re_backend.findall(UpperCAmelCase__ )] backends.sort() return "_and_".join(UpperCAmelCase__ ) def _lowerCAmelCase ( UpperCAmelCase__ : str ) ->str: with open(UpperCAmelCase__, """r""", encoding="""utf-8""", newline="""\n""" ) as f: A__ : Union[str, Any] = f.readlines() A__ : List[str] = 0 while line_index < len(UpperCAmelCase__ ) and not lines[line_index].startswith("""_import_structure = {""" ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(UpperCAmelCase__ ): return None # First grab the objects without a specific backend in _import_structure A__ : List[Any] = [] while not lines[line_index].startswith("""if TYPE_CHECKING""" ) and find_backend(lines[line_index] ) is None: A__ : Optional[Any] = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(UpperCAmelCase__ ): A__ : Optional[int] = _re_one_line_import_struct.search(UpperCAmelCase__ ).groups()[0] A__ : int = re.findall("""\[([^\]]+)\]""", UpperCAmelCase__ ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(""", """ )] ) line_index += 1 continue A__ : Optional[Any] = _re_import_struct_key_value.search(UpperCAmelCase__ ) if single_line_import_search is not None: A__ : List[str] = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(""", """ ) if len(UpperCAmelCase__ ) > 0] objects.extend(UpperCAmelCase__ ) elif line.startswith(""" """ * 8 + """\"""" ): objects.append(line[9:-3] ) line_index += 1 A__ : str = {"""none""": objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith("""if TYPE_CHECKING""" ): # If the line is an if not is_backend_available, we grab all objects associated. A__ : str = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: A__ : List[str] = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 A__ : Tuple = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 4 ): A__ : Any = lines[line_index] if _re_import_struct_add_one.search(UpperCAmelCase__ ) is not None: objects.append(_re_import_struct_add_one.search(UpperCAmelCase__ ).groups()[0] ) elif _re_import_struct_add_many.search(UpperCAmelCase__ ) is not None: A__ : Optional[int] = _re_import_struct_add_many.search(UpperCAmelCase__ ).groups()[0].split(""", """ ) A__ : Tuple = [obj[1:-1] for obj in imports if len(UpperCAmelCase__ ) > 0] objects.extend(UpperCAmelCase__ ) elif _re_between_brackets.search(UpperCAmelCase__ ) is not None: A__ : Any = _re_between_brackets.search(UpperCAmelCase__ ).groups()[0].split(""", """ ) A__ : Tuple = [obj[1:-1] for obj in imports if len(UpperCAmelCase__ ) > 0] objects.extend(UpperCAmelCase__ ) elif _re_quote_object.search(UpperCAmelCase__ ) is not None: objects.append(_re_quote_object.search(UpperCAmelCase__ ).groups()[0] ) elif line.startswith(""" """ * 8 + """\"""" ): objects.append(line[9:-3] ) elif line.startswith(""" """ * 1_2 + """\"""" ): objects.append(line[1_3:-3] ) line_index += 1 A__ : str = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend A__ : Union[str, Any] = [] while ( line_index < len(UpperCAmelCase__ ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith("""else""" ) ): A__ : Optional[Any] = lines[line_index] A__ : List[str] = _re_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 A__ : List[Any] = {"""none""": objects} # Let's continue with backend-specific objects while line_index < len(UpperCAmelCase__ ): # If the line is an if is_backend_available, we grab all objects associated. A__ : Dict = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: A__ : List[Any] = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 A__ : Optional[int] = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 8 ): A__ : int = lines[line_index] A__ : List[Any] = _re_import.search(UpperCAmelCase__ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(""", """ ) ) elif line.startswith(""" """ * 1_2 ): objects.append(line[1_2:-2] ) line_index += 1 A__ : Tuple = objects else: line_index += 1 return import_dict_objects, type_hint_objects def _lowerCAmelCase ( UpperCAmelCase__ : int, UpperCAmelCase__ : int ) ->List[str]: def find_duplicates(UpperCAmelCase__ : str ): return [k for k, v in collections.Counter(UpperCAmelCase__ ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] A__ : int = [] for key in import_dict_objects.keys(): A__ : Tuple = find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(f'Duplicate _import_structure definitions for: {duplicate_imports}' ) A__ : Optional[Any] = find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(f'Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}' ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): A__ : List[Any] = """base imports""" if key == """none""" else f'{key} backend' errors.append(f'Differences for {name}:' ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(f' {a} in TYPE_HINT but not in _import_structure.' ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(f' {a} in _import_structure but not in TYPE_HINT.' ) return errors def _lowerCAmelCase ( ) ->Optional[Any]: A__ : str = [] for root, _, files in os.walk(UpperCAmelCase__ ): if "__init__.py" in files: A__ : str = os.path.join(UpperCAmelCase__, """__init__.py""" ) A__ : Tuple = parse_init(UpperCAmelCase__ ) if objects is not None: A__ : str = analyze_results(*UpperCAmelCase__ ) if len(UpperCAmelCase__ ) > 0: A__ : Any = f'Problem in {fname}, both halves do not define the same objects.\n{errors[0]}' failures.append("""\n""".join(UpperCAmelCase__ ) ) if len(UpperCAmelCase__ ) > 0: raise ValueError("""\n\n""".join(UpperCAmelCase__ ) ) def _lowerCAmelCase ( ) ->Optional[int]: A__ : List[Any] = [] for path, directories, files in os.walk(UpperCAmelCase__ ): for folder in directories: # Ignore private modules if folder.startswith("""_""" ): directories.remove(UpperCAmelCase__ ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(UpperCAmelCase__ ) / folder).glob("""*.py""" ) ) ) == 0: continue A__ : Any = str((Path(UpperCAmelCase__ ) / folder).relative_to(UpperCAmelCase__ ) ) A__ : Optional[int] = short_path.replace(os.path.sep, """.""" ) submodules.append(UpperCAmelCase__ ) for fname in files: if fname == "__init__.py": continue A__ : Union[str, Any] = str((Path(UpperCAmelCase__ ) / fname).relative_to(UpperCAmelCase__ ) ) A__ : Any = short_path.replace(""".py""", """""" ).replace(os.path.sep, """.""" ) if len(submodule.split(""".""" ) ) == 1: submodules.append(UpperCAmelCase__ ) return submodules A_ = [ '''convert_pytorch_checkpoint_to_tf2''', '''modeling_flax_pytorch_utils''', ] def _lowerCAmelCase ( ) ->Optional[int]: # This is to make sure the transformers module imported is the one in the repo. A__ : Dict = importlib.util.spec_from_file_location( """transformers""", os.path.join(UpperCAmelCase__, """__init__.py""" ), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) A__ : Any = spec.loader.load_module() A__ : Optional[Any] = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(UpperCAmelCase__ ) > 0: A__ : Any = """\n""".join(f'- {module}' for module in module_not_registered ) raise ValueError( """The following submodules are not properly registered in the main init of Transformers:\n""" f'{list_of_modules}\n' """Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.""" ) if __name__ == "__main__": check_all_inits() check_submodules()
362
"""simple docstring""" import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py A_ = '''src/diffusers''' A_ = '''.''' # This is to make sure the diffusers module imported is the one in the repo. A_ = importlib.util.spec_from_file_location( '''diffusers''', os.path.join(DIFFUSERS_PATH, '''__init__.py'''), submodule_search_locations=[DIFFUSERS_PATH], ) A_ = spec.loader.load_module() def _lowerCAmelCase ( UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : Optional[Any] ) ->Any: return line.startswith(UpperCAmelCase__ ) or len(UpperCAmelCase__ ) <= 1 or re.search(R"""^\s*\)(\s*->.*:|:)\s*$""", UpperCAmelCase__ ) is not None def _lowerCAmelCase ( UpperCAmelCase__ : List[str] ) ->Union[str, Any]: A__ : Any = object_name.split(""".""" ) A__ : int = 0 # First let's find the module where our object lives. A__ : str = parts[i] while i < len(UpperCAmelCase__ ) and not os.path.isfile(os.path.join(UpperCAmelCase__, f'{module}.py' ) ): i += 1 if i < len(UpperCAmelCase__ ): A__ : Union[str, Any] = os.path.join(UpperCAmelCase__, parts[i] ) if i >= len(UpperCAmelCase__ ): raise ValueError(f'`object_name` should begin with the name of a module of diffusers but got {object_name}.' ) with open(os.path.join(UpperCAmelCase__, f'{module}.py' ), """r""", encoding="""utf-8""", newline="""\n""" ) as f: A__ : List[Any] = f.readlines() # Now let's find the class / func in the code! A__ : Optional[Any] = """""" A__ : Any = 0 for name in parts[i + 1 :]: while ( line_index < len(UpperCAmelCase__ ) and re.search(Rf'^{indent}(class|def)\s+{name}(\(|\:)', lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(UpperCAmelCase__ ): raise ValueError(f' {object_name} does not match any function or class in {module}.' ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). A__ : List[Any] = line_index while line_index < len(UpperCAmelCase__ ) and _should_continue(lines[line_index], UpperCAmelCase__ ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 A__ : List[Any] = lines[start_index:line_index] return "".join(UpperCAmelCase__ ) A_ = re.compile(r'''^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)''') A_ = re.compile(r'''^\s*(\S+)->(\S+)(\s+.*|$)''') A_ = re.compile(r'''<FILL\s+[^>]*>''') def _lowerCAmelCase ( UpperCAmelCase__ : List[str] ) ->Optional[Any]: A__ : Dict = code.split("""\n""" ) A__ : List[Any] = 0 while idx < len(UpperCAmelCase__ ) and len(lines[idx] ) == 0: idx += 1 if idx < len(UpperCAmelCase__ ): return re.search(R"""^(\s*)\S""", lines[idx] ).groups()[0] return "" def _lowerCAmelCase ( UpperCAmelCase__ : Optional[Any] ) ->int: A__ : str = len(get_indent(UpperCAmelCase__ ) ) > 0 if has_indent: A__ : Union[str, Any] = f'class Bla:\n{code}' A__ : Optional[Any] = black.Mode(target_versions={black.TargetVersion.PYaa}, line_length=1_1_9, preview=UpperCAmelCase__ ) A__ : Tuple = black.format_str(UpperCAmelCase__, mode=UpperCAmelCase__ ) A__ , A__ : List[Any] = style_docstrings_in_code(UpperCAmelCase__ ) return result[len("""class Bla:\n""" ) :] if has_indent else result def _lowerCAmelCase ( UpperCAmelCase__ : Any, UpperCAmelCase__ : Dict=False ) ->List[Any]: with open(UpperCAmelCase__, """r""", encoding="""utf-8""", newline="""\n""" ) as f: A__ : int = f.readlines() A__ : Dict = [] A__ : List[str] = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(UpperCAmelCase__ ): A__ : Dict = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. A__ , A__ , A__ : Dict = search.groups() A__ : Tuple = find_code_in_diffusers(UpperCAmelCase__ ) A__ : int = get_indent(UpperCAmelCase__ ) A__ : List[str] = line_index + 1 if indent == theoretical_indent else line_index + 2 A__ : Tuple = theoretical_indent A__ : Optional[Any] = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. A__ : Tuple = True while line_index < len(UpperCAmelCase__ ) and should_continue: line_index += 1 if line_index >= len(UpperCAmelCase__ ): break A__ : Optional[int] = lines[line_index] A__ : Tuple = _should_continue(UpperCAmelCase__, UpperCAmelCase__ ) and re.search(f'^{indent}# End copy', UpperCAmelCase__ ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 A__ : Dict = lines[start_index:line_index] A__ : Tuple = """""".join(UpperCAmelCase__ ) # Remove any nested `Copied from` comments to avoid circular copies A__ : Optional[int] = [line for line in theoretical_code.split("""\n""" ) if _re_copy_warning.search(UpperCAmelCase__ ) is None] A__ : Optional[Any] = """\n""".join(UpperCAmelCase__ ) # Before comparing, use the `replace_pattern` on the original code. if len(UpperCAmelCase__ ) > 0: A__ : int = replace_pattern.replace("""with""", """""" ).split(""",""" ) A__ : List[Any] = [_re_replace_pattern.search(UpperCAmelCase__ ) for p in patterns] for pattern in patterns: if pattern is None: continue A__ , A__ , A__ : Union[str, Any] = pattern.groups() A__ : Union[str, Any] = re.sub(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) if option.strip() == "all-casing": A__ : List[Any] = re.sub(obja.lower(), obja.lower(), UpperCAmelCase__ ) A__ : Tuple = re.sub(obja.upper(), obja.upper(), UpperCAmelCase__ ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line A__ : Optional[int] = blackify(lines[start_index - 1] + theoretical_code ) A__ : List[Any] = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: A__ : List[Any] = lines[:start_index] + [theoretical_code] + lines[line_index:] A__ : Tuple = start_index + 1 if overwrite and len(UpperCAmelCase__ ) > 0: # Warn the user a file has been modified. print(f'Detected changes, rewriting {filename}.' ) with open(UpperCAmelCase__, """w""", encoding="""utf-8""", newline="""\n""" ) as f: f.writelines(UpperCAmelCase__ ) return diffs def _lowerCAmelCase ( UpperCAmelCase__ : bool = False ) ->Any: A__ : Dict = glob.glob(os.path.join(UpperCAmelCase__, """**/*.py""" ), recursive=UpperCAmelCase__ ) A__ : str = [] for filename in all_files: A__ : Any = is_copy_consistent(UpperCAmelCase__, UpperCAmelCase__ ) diffs += [f'- {filename}: copy does not match {d[0]} at line {d[1]}' for d in new_diffs] if not overwrite and len(UpperCAmelCase__ ) > 0: A__ : Any = """\n""".join(UpperCAmelCase__ ) raise Exception( """Found the following copy inconsistencies:\n""" + diff + """\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.""" ) if __name__ == "__main__": A_ = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') A_ = parser.parse_args() check_copies(args.fix_and_overwrite)
296
0
"""simple docstring""" import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, 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_poolformer import PoolFormerConfig A_ = logging.get_logger(__name__) # General docstring A_ = '''PoolFormerConfig''' # Base docstring A_ = '''sail/poolformer_s12''' A_ = [1, 512, 7, 7] # Image classification docstring A_ = '''sail/poolformer_s12''' A_ = '''tabby, tabby cat''' A_ = [ '''sail/poolformer_s12''', # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def _lowerCAmelCase ( UpperCAmelCase__ : Dict, UpperCAmelCase__ : float = 0.0, UpperCAmelCase__ : bool = False ) ->Union[str, Any]: if drop_prob == 0.0 or not training: return input A__ : Optional[int] = 1 - drop_prob A__ : Optional[Any] = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets A__ : Optional[Any] = keep_prob + torch.rand(UpperCAmelCase__, dtype=input.dtype, device=input.device ) random_tensor.floor_() # binarize A__ : int = input.div(UpperCAmelCase__ ) * random_tensor return output class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Optional[Any] , snake_case : Optional[float] = None ): '''simple docstring''' super().__init__() A__ : int = drop_prob def _UpperCamelCase ( self : List[Any] , snake_case : torch.Tensor ): '''simple docstring''' return drop_path(snake_case , self.drop_prob , self.training ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' return "p={}".format(self.drop_prob ) class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Union[str, Any] , snake_case : Optional[Any] , snake_case : Optional[int] , snake_case : List[Any] , snake_case : Optional[Any] , snake_case : Union[str, Any] , snake_case : Dict=None ): '''simple docstring''' super().__init__() A__ : str = patch_size if isinstance(snake_case , collections.abc.Iterable ) else (patch_size, patch_size) A__ : Any = stride if isinstance(snake_case , collections.abc.Iterable ) else (stride, stride) A__ : Dict = padding if isinstance(snake_case , collections.abc.Iterable ) else (padding, padding) A__ : List[str] = nn.Convad(snake_case , snake_case , kernel_size=snake_case , stride=snake_case , padding=snake_case ) A__ : int = norm_layer(snake_case ) if norm_layer else nn.Identity() def _UpperCamelCase ( self : int , snake_case : Dict ): '''simple docstring''' A__ : Tuple = self.projection(snake_case ) A__ : List[Any] = self.norm(snake_case ) return embeddings class __SCREAMING_SNAKE_CASE ( nn.GroupNorm ): def __init__( self : str , snake_case : str , **snake_case : Optional[Any] ): '''simple docstring''' super().__init__(1 , snake_case , **snake_case ) class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : int , snake_case : Dict ): '''simple docstring''' super().__init__() A__ : Optional[int] = nn.AvgPoolad(snake_case , stride=1 , padding=pool_size // 2 , count_include_pad=snake_case ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Optional[int] ): '''simple docstring''' return self.pool(snake_case ) - hidden_states class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Optional[Any] , snake_case : List[str] , snake_case : Union[str, Any] , snake_case : Any , snake_case : Optional[Any] ): '''simple docstring''' super().__init__() A__ : Any = nn.Convad(snake_case , snake_case , 1 ) A__ : Dict = nn.Convad(snake_case , snake_case , 1 ) A__ : List[Any] = PoolFormerDropPath(snake_case ) if isinstance(config.hidden_act , snake_case ): A__ : Optional[int] = ACTaFN[config.hidden_act] else: A__ : int = config.hidden_act def _UpperCamelCase ( self : Optional[int] , snake_case : Tuple ): '''simple docstring''' A__ : Dict = self.conva(snake_case ) A__ : Union[str, Any] = self.act_fn(snake_case ) A__ : Dict = self.drop(snake_case ) A__ : Tuple = self.conva(snake_case ) A__ : Dict = self.drop(snake_case ) return hidden_states class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Union[str, Any] , snake_case : Any , snake_case : int , snake_case : Tuple , snake_case : List[Any] , snake_case : List[str] , snake_case : Dict ): '''simple docstring''' super().__init__() A__ : Any = PoolFormerPooling(snake_case ) A__ : Tuple = PoolFormerOutput(snake_case , snake_case , snake_case , snake_case ) A__ : Dict = PoolFormerGroupNorm(snake_case ) A__ : Any = PoolFormerGroupNorm(snake_case ) # Useful for training neural nets A__ : Dict = PoolFormerDropPath(snake_case ) if drop_path > 0.0 else nn.Identity() A__ : str = config.use_layer_scale if config.use_layer_scale: A__ : Tuple = nn.Parameter( config.layer_scale_init_value * torch.ones((snake_case) ) , requires_grad=snake_case ) A__ : int = nn.Parameter( config.layer_scale_init_value * torch.ones((snake_case) ) , requires_grad=snake_case ) def _UpperCamelCase ( self : int , snake_case : Union[str, Any] ): '''simple docstring''' if self.use_layer_scale: A__ : List[str] = self.pooling(self.before_norm(snake_case ) ) A__ : Union[str, Any] = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection A__ : Tuple = hidden_states + self.drop_path(snake_case ) A__ : Dict = () A__ : List[Any] = self.output(self.after_norm(snake_case ) ) A__ : List[Any] = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection A__ : int = hidden_states + self.drop_path(snake_case ) A__ : Union[str, Any] = (output,) + outputs return outputs else: A__ : Tuple = self.drop_path(self.pooling(self.before_norm(snake_case ) ) ) # First residual connection A__ : str = pooling_output + hidden_states A__ : Any = () # Second residual connection inside the PoolFormerOutput block A__ : Dict = self.drop_path(self.output(self.after_norm(snake_case ) ) ) A__ : List[Any] = hidden_states + layer_output A__ : Any = (output,) + outputs return outputs class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Optional[int] , snake_case : Optional[int] ): '''simple docstring''' super().__init__() A__ : Optional[Any] = config # stochastic depth decay rule A__ : Dict = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings A__ : Optional[int] = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) A__ : Union[str, Any] = nn.ModuleList(snake_case ) # Transformer blocks A__ : Dict = [] A__ : Union[str, Any] = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers A__ : List[Any] = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( snake_case , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(snake_case ) ) A__ : List[str] = nn.ModuleList(snake_case ) def _UpperCamelCase ( self : Any , snake_case : Tuple , snake_case : Optional[int]=False , snake_case : Any=True ): '''simple docstring''' A__ : Optional[Any] = () if output_hidden_states else None A__ : str = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): A__ : List[Any] = layers # Get patch embeddings from hidden_states A__ : Optional[int] = embedding_layer(snake_case ) # Send the embeddings through the blocks for _, blk in enumerate(snake_case ): A__ : List[Any] = blk(snake_case ) A__ : Union[str, Any] = layer_outputs[0] if output_hidden_states: A__ : Union[str, Any] = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=snake_case , hidden_states=snake_case ) class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = PoolFormerConfig snake_case_ = 'poolformer' snake_case_ = 'pixel_values' snake_case_ = True def _UpperCamelCase ( self : Optional[Any] , snake_case : Union[str, Any] ): '''simple docstring''' if isinstance(snake_case , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(snake_case , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def _UpperCamelCase ( self : Union[str, Any] , snake_case : str , snake_case : List[Any]=False ): '''simple docstring''' if isinstance(snake_case , snake_case ): A__ : Union[str, Any] = value A_ = r''' This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' A_ = r''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`PoolFormerImageProcessor.__call__`] for details. ''' @add_start_docstrings( 'The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.' , UpperCamelCase , ) class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): def __init__( self : Optional[Any] , snake_case : Optional[Any] ): '''simple docstring''' super().__init__(snake_case ) A__ : Optional[int] = config A__ : int = PoolFormerEncoder(snake_case ) # Initialize weights and apply final processing self.post_init() def _UpperCamelCase ( self : str ): '''simple docstring''' return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(snake_case ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=snake_case , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def _UpperCamelCase ( self : Tuple , snake_case : Optional[torch.FloatTensor] = None , snake_case : Optional[bool] = None , snake_case : Optional[bool] = None , ): '''simple docstring''' A__ : Optional[int] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) A__ : str = 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__ : Optional[int] = self.encoder( snake_case , output_hidden_states=snake_case , return_dict=snake_case , ) A__ : Tuple = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=snake_case , hidden_states=encoder_outputs.hidden_states , ) class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Optional[int] , snake_case : Optional[int] ): '''simple docstring''' super().__init__() A__ : Optional[Any] = nn.Linear(config.hidden_size , config.hidden_size ) def _UpperCamelCase ( self : Tuple , snake_case : Optional[Any] ): '''simple docstring''' A__ : Tuple = self.dense(snake_case ) return output @add_start_docstrings( '\n PoolFormer Model transformer with an image classification head on top\n ' , UpperCamelCase , ) class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): def __init__( self : Dict , snake_case : Dict ): '''simple docstring''' super().__init__(snake_case ) A__ : List[str] = config.num_labels A__ : Optional[int] = PoolFormerModel(snake_case ) # Final norm A__ : Any = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head A__ : Any = ( nn.Linear(config.hidden_sizes[-1] , 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(snake_case ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=snake_case , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def _UpperCamelCase ( self : List[Any] , snake_case : Optional[torch.FloatTensor] = None , snake_case : Optional[torch.LongTensor] = None , snake_case : Optional[bool] = None , snake_case : Optional[bool] = None , ): '''simple docstring''' A__ : int = return_dict if return_dict is not None else self.config.use_return_dict A__ : Any = self.poolformer( snake_case , output_hidden_states=snake_case , return_dict=snake_case , ) A__ : List[str] = outputs[0] A__ : Dict = self.classifier(self.norm(snake_case ).mean([-2, -1] ) ) A__ : List[str] = 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__ : Tuple = """single_label_classification""" else: A__ : int = """multi_label_classification""" if self.config.problem_type == "regression": A__ : Any = MSELoss() if self.num_labels == 1: A__ : str = loss_fct(logits.squeeze() , labels.squeeze() ) else: A__ : str = loss_fct(snake_case , snake_case ) elif self.config.problem_type == "single_label_classification": A__ : Optional[Any] = CrossEntropyLoss() A__ : Optional[Any] = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": A__ : Union[str, Any] = BCEWithLogitsLoss() A__ : Tuple = loss_fct(snake_case , snake_case ) if not return_dict: A__ : Union[str, Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=snake_case , logits=snake_case , hidden_states=outputs.hidden_states )
363
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) A_ = { '''configuration_llama''': ['''LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LlamaConfig'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ['''LlamaTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = ['''LlamaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''LlamaForCausalLM''', '''LlamaModel''', '''LlamaPreTrainedModel''', '''LlamaForSequenceClassification''', ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
296
0
"""simple docstring""" import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets A_ = '''\ @inproceedings{lin-2004-rouge, title = "{ROUGE}: A Package for Automatic Evaluation of Summaries", author = "Lin, Chin-Yew", booktitle = "Text Summarization Branches Out", month = jul, year = "2004", address = "Barcelona, Spain", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/W04-1013", pages = "74--81", } ''' A_ = '''\ ROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for evaluating automatic summarization and machine translation software in natural language processing. The metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation. Note that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters. This metrics is a wrapper around Google Research reimplementation of ROUGE: https://github.com/google-research/google-research/tree/master/rouge ''' A_ = ''' Calculates average rouge scores for a list of hypotheses and references Args: predictions: list of predictions to score. Each prediction should be a string with tokens separated by spaces. references: list of reference for each prediction. Each reference should be a string with tokens separated by spaces. rouge_types: A list of rouge types to calculate. Valid names: `"rouge{n}"` (e.g. `"rouge1"`, `"rouge2"`) where: {n} is the n-gram based scoring, `"rougeL"`: Longest common subsequence based scoring. `"rougeLSum"`: rougeLsum splits text using `"\n"`. See details in https://github.com/huggingface/datasets/issues/617 use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes. use_aggregator: Return aggregates if this is set to True Returns: rouge1: rouge_1 (precision, recall, f1), rouge2: rouge_2 (precision, recall, f1), rougeL: rouge_l (precision, recall, f1), rougeLsum: rouge_lsum (precision, recall, f1) Examples: >>> rouge = datasets.load_metric(\'rouge\') >>> predictions = ["hello there", "general kenobi"] >>> references = ["hello there", "general kenobi"] >>> results = rouge.compute(predictions=predictions, references=references) >>> print(list(results.keys())) [\'rouge1\', \'rouge2\', \'rougeL\', \'rougeLsum\'] >>> print(results["rouge1"]) AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0)) >>> print(results["rouge1"].mid.fmeasure) 1.0 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE ( datasets.Metric ): def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/google-research/google-research/tree/master/rouge"""] , reference_urls=[ """https://en.wikipedia.org/wiki/ROUGE_(metric)""", """https://github.com/google-research/google-research/tree/master/rouge""", ] , ) def _UpperCamelCase ( self : str , snake_case : Optional[Any] , snake_case : List[Any] , snake_case : Union[str, Any]=None , snake_case : Dict=True , snake_case : List[str]=False ): '''simple docstring''' if rouge_types is None: A__ : int = ["""rouge1""", """rouge2""", """rougeL""", """rougeLsum"""] A__ : List[str] = rouge_scorer.RougeScorer(rouge_types=snake_case , use_stemmer=snake_case ) if use_aggregator: A__ : Any = scoring.BootstrapAggregator() else: A__ : str = [] for ref, pred in zip(snake_case , snake_case ): A__ : Tuple = scorer.score(snake_case , snake_case ) if use_aggregator: aggregator.add_scores(snake_case ) else: scores.append(snake_case ) if use_aggregator: A__ : Optional[int] = aggregator.aggregate() else: A__ : Union[str, Any] = {} for key in scores[0]: A__ : int = [score[key] for score in scores] return result
364
"""simple docstring""" import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels A_ = object() # For specifying empty leaf dict `{}` A_ = object() def _lowerCAmelCase ( UpperCAmelCase__ : Tuple, UpperCAmelCase__ : List[Any] ) ->Dict: A__ : Union[str, Any] = tuple((re.compile(x + """$""" ) for x in qs) ) for i in range(len(UpperCAmelCase__ ) - len(UpperCAmelCase__ ) + 1 ): A__ : Optional[Any] = [x.match(UpperCAmelCase__ ) for x, y in zip(UpperCAmelCase__, ks[i:] )] if matches and all(UpperCAmelCase__ ): return True return False def _lowerCAmelCase ( UpperCAmelCase__ : List[Any] ) ->Dict: def replace(UpperCAmelCase__ : int, UpperCAmelCase__ : List[str] ): for rule, replacement in rules: if _match(UpperCAmelCase__, UpperCAmelCase__ ): return replacement return val return replace def _lowerCAmelCase ( ) ->Tuple: return [ # embeddings (("transformer", "wpe", "embedding"), P("""mp""", UpperCAmelCase__ )), (("transformer", "wte", "embedding"), P("""mp""", UpperCAmelCase__ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(UpperCAmelCase__, """mp""" )), (("attention", "out_proj", "kernel"), P("""mp""", UpperCAmelCase__ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(UpperCAmelCase__, """mp""" )), (("mlp", "c_fc", "bias"), P("""mp""" )), (("mlp", "c_proj", "kernel"), P("""mp""", UpperCAmelCase__ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def _lowerCAmelCase ( UpperCAmelCase__ : Tuple ) ->Any: A__ : Union[str, Any] = _get_partition_rules() A__ : int = _replacement_rules(UpperCAmelCase__ ) A__ : Tuple = {k: _unmatched for k in flatten_dict(UpperCAmelCase__ )} A__ : Optional[int] = {k: replace(UpperCAmelCase__, UpperCAmelCase__ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(UpperCAmelCase__ ) )
296
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : List[str] , snake_case : Optional[Any] , snake_case : str=7 , snake_case : Tuple=3 , snake_case : List[Any]=18 , snake_case : Any=30 , snake_case : Optional[Any]=400 , snake_case : Any=True , snake_case : List[Any]=None , snake_case : Optional[Any]=True , snake_case : int=None , snake_case : int=True , snake_case : List[str]=[0.5, 0.5, 0.5] , snake_case : Optional[int]=[0.5, 0.5, 0.5] , ): '''simple docstring''' A__ : Any = size if size is not None else {"""shortest_edge""": 18} A__ : Dict = crop_size if crop_size is not None else {"""height""": 18, """width""": 18} A__ : Dict = parent A__ : Optional[Any] = batch_size A__ : Tuple = num_channels A__ : List[Any] = image_size A__ : List[Any] = min_resolution A__ : List[str] = max_resolution A__ : Optional[int] = do_resize A__ : Optional[int] = size A__ : Optional[int] = do_center_crop A__ : Optional[int] = crop_size A__ : Tuple = do_normalize A__ : Union[str, Any] = image_mean A__ : Union[str, Any] = image_std def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "do_center_crop": self.do_center_crop, "size": self.size, "crop_size": self.crop_size, } @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( UpperCamelCase , unittest.TestCase ): snake_case_ = LevitImageProcessor if is_vision_available() else None def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : List[str] = LevitImageProcessingTester(self ) @property def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(snake_case , """image_mean""" ) ) self.assertTrue(hasattr(snake_case , """image_std""" ) ) self.assertTrue(hasattr(snake_case , """do_normalize""" ) ) self.assertTrue(hasattr(snake_case , """do_resize""" ) ) self.assertTrue(hasattr(snake_case , """do_center_crop""" ) ) self.assertTrue(hasattr(snake_case , """size""" ) ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : Dict = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 18} ) self.assertEqual(image_processor.crop_size , {"""height""": 18, """width""": 18} ) A__ : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"""shortest_edge""": 42} ) self.assertEqual(image_processor.crop_size , {"""height""": 84, """width""": 84} ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' pass def _UpperCamelCase ( self : Optional[Any] ): '''simple docstring''' A__ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PIL images A__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case ) for image in image_inputs: self.assertIsInstance(snake_case , Image.Image ) # 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.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched A__ : Optional[Any] = image_processing(snake_case , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A__ : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case , numpify=snake_case ) for image in image_inputs: self.assertIsInstance(snake_case , 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.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched A__ : Union[str, Any] = image_processing(snake_case , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A__ : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case , torchify=snake_case ) for image in image_inputs: self.assertIsInstance(snake_case , torch.Tensor ) # Test not batched input A__ : Optional[int] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched A__ : Dict = image_processing(snake_case , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , )
365
"""simple docstring""" import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class __SCREAMING_SNAKE_CASE : def __init__( self : List[str] , snake_case : Tuple , snake_case : List[str]=2 , snake_case : List[str]=8 , snake_case : List[Any]=True , snake_case : Optional[Any]=True , snake_case : List[Any]=True , snake_case : Dict=True , snake_case : Tuple=99 , snake_case : Dict=16 , snake_case : Dict=5 , snake_case : int=2 , snake_case : Any=36 , snake_case : str="gelu" , snake_case : Dict=0.0 , snake_case : List[Any]=0.0 , snake_case : int=512 , snake_case : List[Any]=16 , snake_case : Tuple=2 , snake_case : Any=0.02 , snake_case : Optional[Any]=3 , snake_case : List[Any]=4 , snake_case : str=None , ): '''simple docstring''' A__ : Union[str, Any] = parent A__ : Optional[Any] = batch_size A__ : Dict = seq_length A__ : str = is_training A__ : Tuple = use_input_mask A__ : Dict = use_token_type_ids A__ : Dict = use_labels A__ : int = vocab_size A__ : List[str] = hidden_size A__ : Union[str, Any] = num_hidden_layers A__ : int = num_attention_heads A__ : List[str] = intermediate_size A__ : int = hidden_act A__ : str = hidden_dropout_prob A__ : Tuple = attention_probs_dropout_prob A__ : Any = max_position_embeddings A__ : Optional[int] = type_vocab_size A__ : int = type_sequence_label_size A__ : Optional[Any] = initializer_range A__ : int = num_labels A__ : Optional[int] = num_choices A__ : Optional[int] = scope def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Any = None if self.use_input_mask: A__ : Any = random_attention_mask([self.batch_size, self.seq_length] ) A__ : Optional[int] = None if self.use_token_type_ids: A__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A__ : Dict = None A__ : List[str] = None A__ : Union[str, Any] = None if self.use_labels: A__ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : Any = ids_tensor([self.batch_size] , self.num_choices ) A__ : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCamelCase ( self : List[str] ): '''simple docstring''' return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case , initializer_range=self.initializer_range , ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Any = self.get_config() A__ : List[str] = 300 return config def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) : Tuple = self.prepare_config_and_inputs() A__ : List[str] = True A__ : List[str] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) A__ : int = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def _UpperCamelCase ( self : Any , snake_case : Any , snake_case : Tuple , snake_case : Any , snake_case : Optional[int] , snake_case : Optional[int] , snake_case : Optional[int] , snake_case : Dict ): '''simple docstring''' A__ : List[str] = MraModel(config=snake_case ) model.to(snake_case ) model.eval() A__ : Dict = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case ) A__ : List[str] = model(snake_case , token_type_ids=snake_case ) A__ : Union[str, Any] = model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : Optional[Any] , snake_case : List[Any] , snake_case : Any , snake_case : Optional[Any] , snake_case : Union[str, Any] , snake_case : Tuple , snake_case : Dict , snake_case : str , snake_case : Dict , snake_case : str , ): '''simple docstring''' A__ : Dict = True A__ : Optional[Any] = MraModel(snake_case ) model.to(snake_case ) model.eval() A__ : Union[str, Any] = model( snake_case , attention_mask=snake_case , token_type_ids=snake_case , encoder_hidden_states=snake_case , encoder_attention_mask=snake_case , ) A__ : str = model( snake_case , attention_mask=snake_case , token_type_ids=snake_case , encoder_hidden_states=snake_case , ) A__ : Optional[int] = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self : int , snake_case : Optional[Any] , snake_case : Optional[int] , snake_case : int , snake_case : str , snake_case : Union[str, Any] , snake_case : Dict , snake_case : List[str] ): '''simple docstring''' A__ : Union[str, Any] = MraForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() A__ : List[Any] = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCamelCase ( self : Optional[Any] , snake_case : Dict , snake_case : Dict , snake_case : Dict , snake_case : List[str] , snake_case : List[str] , snake_case : Tuple , snake_case : Union[str, Any] ): '''simple docstring''' A__ : Dict = MraForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() A__ : str = model( 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 _UpperCamelCase ( self : Tuple , snake_case : List[Any] , snake_case : Optional[Any] , snake_case : Optional[Any] , snake_case : List[str] , snake_case : Optional[int] , snake_case : List[str] , snake_case : Union[str, Any] ): '''simple docstring''' A__ : str = self.num_labels A__ : Optional[Any] = MraForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() A__ : str = model(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 _UpperCamelCase ( self : Union[str, Any] , snake_case : Dict , snake_case : str , snake_case : List[Any] , snake_case : Any , snake_case : Dict , snake_case : Tuple , snake_case : Optional[Any] ): '''simple docstring''' A__ : str = self.num_labels A__ : Union[str, Any] = MraForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() A__ : str = model(snake_case , attention_mask=snake_case , token_type_ids=snake_case , labels=snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self : Tuple , snake_case : Optional[Any] , snake_case : Optional[int] , snake_case : int , snake_case : Optional[Any] , snake_case : List[str] , snake_case : Dict , snake_case : Optional[Any] ): '''simple docstring''' A__ : List[str] = self.num_choices A__ : str = MraForMultipleChoice(config=snake_case ) model.to(snake_case ) model.eval() A__ : int = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ : str = model( 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_choices) ) def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : List[str] = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) : Dict = config_and_inputs A__ : Optional[int] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( UpperCamelCase , unittest.TestCase ): snake_case_ = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = () def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Optional[Any] = MraModelTester(self ) A__ : List[str] = ConfigTester(self , config_class=snake_case , hidden_size=37 ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A__ : List[str] = type self.model_tester.create_and_check_model(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case ) def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case ) def _UpperCamelCase ( self : int ): '''simple docstring''' A__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case ) def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case ) @slow def _UpperCamelCase ( self : Any ): '''simple docstring''' for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ : str = MraModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @unittest.skip(reason="""MRA does not output attentions""" ) def _UpperCamelCase ( self : Tuple ): '''simple docstring''' return @require_torch class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @slow def _UpperCamelCase ( self : Union[str, Any] ): '''simple docstring''' A__ : str = MraModel.from_pretrained("""uw-madison/mra-base-512-4""" ) A__ : Any = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): A__ : List[Any] = model(snake_case )[0] A__ : List[Any] = torch.Size((1, 256, 768) ) self.assertEqual(output.shape , snake_case ) A__ : int = torch.tensor( [[[-0.0140, 0.0830, -0.0381], [0.1546, 0.1402, 0.0220], [0.1162, 0.0851, 0.0165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) ) @slow def _UpperCamelCase ( self : List[Any] ): '''simple docstring''' A__ : Union[str, Any] = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-512-4""" ) A__ : Tuple = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): A__ : List[Any] = model(snake_case )[0] A__ : Dict = 5_0265 A__ : List[str] = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape , snake_case ) A__ : List[Any] = torch.tensor( [[[9.2595, -3.6038, 11.8819], [9.3869, -3.2693, 11.0956], [11.8524, -3.4938, 13.1210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) ) @slow def _UpperCamelCase ( self : Dict ): '''simple docstring''' A__ : Any = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-4096-8-d3""" ) A__ : List[Any] = torch.arange(4096 ).unsqueeze(0 ) with torch.no_grad(): A__ : List[Any] = model(snake_case )[0] A__ : Union[str, Any] = 5_0265 A__ : Optional[Any] = torch.Size((1, 4096, vocab_size) ) self.assertEqual(output.shape , snake_case ) A__ : Optional[int] = torch.tensor( [[[5.4789, -2.3564, 7.5064], [7.9067, -1.3369, 9.9668], [9.0712, -1.8106, 7.0380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case , atol=1e-4 ) )
296
0