code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging lowerCamelCase : List[Any] = logging.get_logger(__name__) if is_vision_available(): import PIL class A__ ( A__ ): A__ = ['pixel_values'] def __init__( self : int , _a : bool = True , _a : Dict[str, int] = None , _a : PILImageResampling = PILImageResampling.BICUBIC , _a : bool = True , _a : Dict[str, int] = None , _a : bool = True , _a : Union[int, float] = 1 / 255 , _a : bool = True , _a : Optional[Union[float, List[float]]] = None , _a : Optional[Union[float, List[float]]] = None , _a : bool = True , **_a : Any , ) -> None: '''simple docstring''' super().__init__(**_a ) _SCREAMING_SNAKE_CASE =size if size is not None else {'shortest_edge': 224} _SCREAMING_SNAKE_CASE =get_size_dict(_a , default_to_square=_a ) _SCREAMING_SNAKE_CASE =crop_size if crop_size is not None else {'height': 224, 'width': 224} _SCREAMING_SNAKE_CASE =get_size_dict(_a , default_to_square=_a , param_name='crop_size' ) _SCREAMING_SNAKE_CASE =do_resize _SCREAMING_SNAKE_CASE =size _SCREAMING_SNAKE_CASE =resample _SCREAMING_SNAKE_CASE =do_center_crop _SCREAMING_SNAKE_CASE =crop_size _SCREAMING_SNAKE_CASE =do_rescale _SCREAMING_SNAKE_CASE =rescale_factor _SCREAMING_SNAKE_CASE =do_normalize _SCREAMING_SNAKE_CASE =image_mean if image_mean is not None else OPENAI_CLIP_MEAN _SCREAMING_SNAKE_CASE =image_std if image_std is not None else OPENAI_CLIP_STD _SCREAMING_SNAKE_CASE =do_convert_rgb def A ( self : int , _a : np.ndarray , _a : Dict[str, int] , _a : PILImageResampling = PILImageResampling.BICUBIC , _a : Optional[Union[str, ChannelDimension]] = None , **_a : str , ) -> np.ndarray: '''simple docstring''' _SCREAMING_SNAKE_CASE =get_size_dict(_a , default_to_square=_a ) if "shortest_edge" not in size: raise ValueError(f"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}" ) _SCREAMING_SNAKE_CASE =get_resize_output_image_size(_a , size=size['shortest_edge'] , default_to_square=_a ) return resize(_a , size=_a , resample=_a , data_format=_a , **_a ) def A ( self : Optional[Any] , _a : np.ndarray , _a : Dict[str, int] , _a : Optional[Union[str, ChannelDimension]] = None , **_a : Optional[Any] , ) -> np.ndarray: '''simple docstring''' _SCREAMING_SNAKE_CASE =get_size_dict(_a ) if "height" not in size or "width" not in size: raise ValueError(f"The `size` parameter must contain the keys (height, width). Got {size.keys()}" ) return center_crop(_a , size=(size['height'], size['width']) , data_format=_a , **_a ) def A ( self : List[Any] , _a : np.ndarray , _a : Union[int, float] , _a : Optional[Union[str, ChannelDimension]] = None , **_a : str , ) -> str: '''simple docstring''' return rescale(_a , scale=_a , data_format=_a , **_a ) def A ( self : List[Any] , _a : np.ndarray , _a : Union[float, List[float]] , _a : Union[float, List[float]] , _a : Optional[Union[str, ChannelDimension]] = None , **_a : Optional[Any] , ) -> np.ndarray: '''simple docstring''' return normalize(_a , mean=_a , std=_a , data_format=_a , **_a ) def A ( self : Tuple , _a : ImageInput , _a : bool = None , _a : Dict[str, int] = None , _a : PILImageResampling = None , _a : bool = None , _a : int = None , _a : bool = None , _a : float = None , _a : bool = None , _a : Optional[Union[float, List[float]]] = None , _a : Optional[Union[float, List[float]]] = None , _a : bool = None , _a : Optional[Union[str, TensorType]] = None , _a : Optional[ChannelDimension] = ChannelDimension.FIRST , **_a : Optional[Any] , ) -> PIL.Image.Image: '''simple docstring''' _SCREAMING_SNAKE_CASE =do_resize if do_resize is not None else self.do_resize _SCREAMING_SNAKE_CASE =size if size is not None else self.size _SCREAMING_SNAKE_CASE =get_size_dict(_a , param_name='size' , default_to_square=_a ) _SCREAMING_SNAKE_CASE =resample if resample is not None else self.resample _SCREAMING_SNAKE_CASE =do_center_crop if do_center_crop is not None else self.do_center_crop _SCREAMING_SNAKE_CASE =crop_size if crop_size is not None else self.crop_size _SCREAMING_SNAKE_CASE =get_size_dict(_a , param_name='crop_size' , default_to_square=_a ) _SCREAMING_SNAKE_CASE =do_rescale if do_rescale is not None else self.do_rescale _SCREAMING_SNAKE_CASE =rescale_factor if rescale_factor is not None else self.rescale_factor _SCREAMING_SNAKE_CASE =do_normalize if do_normalize is not None else self.do_normalize _SCREAMING_SNAKE_CASE =image_mean if image_mean is not None else self.image_mean _SCREAMING_SNAKE_CASE =image_std if image_std is not None else self.image_std _SCREAMING_SNAKE_CASE =do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb _SCREAMING_SNAKE_CASE =make_list_of_images(_a ) if not valid_images(_a ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # PIL RGBA images are converted to RGB if do_convert_rgb: _SCREAMING_SNAKE_CASE =[convert_to_rgb(_a ) for image in images] # All transformations expect numpy arrays. _SCREAMING_SNAKE_CASE =[to_numpy_array(_a ) for image in images] if do_resize: _SCREAMING_SNAKE_CASE =[self.resize(image=_a , size=_a , resample=_a ) for image in images] if do_center_crop: _SCREAMING_SNAKE_CASE =[self.center_crop(image=_a , size=_a ) for image in images] if do_rescale: _SCREAMING_SNAKE_CASE =[self.rescale(image=_a , scale=_a ) for image in images] if do_normalize: _SCREAMING_SNAKE_CASE =[self.normalize(image=_a , mean=_a , std=_a ) for image in images] _SCREAMING_SNAKE_CASE =[to_channel_dimension_format(_a , _a ) for image in images] _SCREAMING_SNAKE_CASE ={'pixel_values': images} return BatchFeature(data=_a , tensor_type=_a )
47
'''simple docstring''' import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device lowerCamelCase : Optional[int] = False class A__ ( unittest.TestCase ): pass @slow @require_torch_gpu class A__ ( unittest.TestCase ): def A ( self : Tuple ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =VersatileDiffusionImageVariationPipeline.from_pretrained('shi-labs/versatile-diffusion' ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) _SCREAMING_SNAKE_CASE =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg' ) _SCREAMING_SNAKE_CASE =torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE =pipe( image=_a , generator=_a , guidance_scale=7.5 , num_inference_steps=50 , output_type='numpy' , ).images _SCREAMING_SNAKE_CASE =image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) _SCREAMING_SNAKE_CASE =np.array([0.04_41, 0.04_69, 0.05_07, 0.05_75, 0.06_32, 0.06_50, 0.08_65, 0.09_09, 0.09_45] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
47
1
'''simple docstring''' import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging logging.set_verbosity_info() def _lowerCAmelCase ( _UpperCamelCase : str , _UpperCamelCase : str , _UpperCamelCase : str ) -> Union[str, Any]: """simple docstring""" def get_masked_lm_array(_UpperCamelCase : str ): _SCREAMING_SNAKE_CASE =f"masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE" _SCREAMING_SNAKE_CASE =tf.train.load_variable(_UpperCamelCase , _UpperCamelCase ) if "kernel" in name: _SCREAMING_SNAKE_CASE =array.transpose() return torch.from_numpy(_UpperCamelCase ) def get_encoder_array(_UpperCamelCase : str ): _SCREAMING_SNAKE_CASE =f"encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE" _SCREAMING_SNAKE_CASE =tf.train.load_variable(_UpperCamelCase , _UpperCamelCase ) if "kernel" in name: _SCREAMING_SNAKE_CASE =array.transpose() return torch.from_numpy(_UpperCamelCase ) def get_encoder_layer_array(_UpperCamelCase : int , _UpperCamelCase : str ): _SCREAMING_SNAKE_CASE =f"encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE" _SCREAMING_SNAKE_CASE =tf.train.load_variable(_UpperCamelCase , _UpperCamelCase ) if "kernel" in name: _SCREAMING_SNAKE_CASE =array.transpose() return torch.from_numpy(_UpperCamelCase ) def get_encoder_attention_layer_array(_UpperCamelCase : int , _UpperCamelCase : str , _UpperCamelCase : str ): _SCREAMING_SNAKE_CASE =f"encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE" _SCREAMING_SNAKE_CASE =tf.train.load_variable(_UpperCamelCase , _UpperCamelCase ) _SCREAMING_SNAKE_CASE =array.reshape(_UpperCamelCase ) if "kernel" in name: _SCREAMING_SNAKE_CASE =array.transpose() return torch.from_numpy(_UpperCamelCase ) print(f"Loading model based on config from {config_path}..." ) _SCREAMING_SNAKE_CASE =BertConfig.from_json_file(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =BertForMaskedLM(_UpperCamelCase ) # Layers for layer_index in range(0 , config.num_hidden_layers ): _SCREAMING_SNAKE_CASE =model.bert.encoder.layer[layer_index] # Self-attention _SCREAMING_SNAKE_CASE =layer.attention.self _SCREAMING_SNAKE_CASE =get_encoder_attention_layer_array( _UpperCamelCase , '_query_dense/kernel' , self_attn.query.weight.data.shape ) _SCREAMING_SNAKE_CASE =get_encoder_attention_layer_array( _UpperCamelCase , '_query_dense/bias' , self_attn.query.bias.data.shape ) _SCREAMING_SNAKE_CASE =get_encoder_attention_layer_array( _UpperCamelCase , '_key_dense/kernel' , self_attn.key.weight.data.shape ) _SCREAMING_SNAKE_CASE =get_encoder_attention_layer_array( _UpperCamelCase , '_key_dense/bias' , self_attn.key.bias.data.shape ) _SCREAMING_SNAKE_CASE =get_encoder_attention_layer_array( _UpperCamelCase , '_value_dense/kernel' , self_attn.value.weight.data.shape ) _SCREAMING_SNAKE_CASE =get_encoder_attention_layer_array( _UpperCamelCase , '_value_dense/bias' , self_attn.value.bias.data.shape ) # Self-attention Output _SCREAMING_SNAKE_CASE =layer.attention.output _SCREAMING_SNAKE_CASE =get_encoder_attention_layer_array( _UpperCamelCase , '_output_dense/kernel' , self_output.dense.weight.data.shape ) _SCREAMING_SNAKE_CASE =get_encoder_attention_layer_array( _UpperCamelCase , '_output_dense/bias' , self_output.dense.bias.data.shape ) _SCREAMING_SNAKE_CASE =get_encoder_layer_array(_UpperCamelCase , '_attention_layer_norm/gamma' ) _SCREAMING_SNAKE_CASE =get_encoder_layer_array(_UpperCamelCase , '_attention_layer_norm/beta' ) # Intermediate _SCREAMING_SNAKE_CASE =layer.intermediate _SCREAMING_SNAKE_CASE =get_encoder_layer_array(_UpperCamelCase , '_intermediate_dense/kernel' ) _SCREAMING_SNAKE_CASE =get_encoder_layer_array(_UpperCamelCase , '_intermediate_dense/bias' ) # Output _SCREAMING_SNAKE_CASE =layer.output _SCREAMING_SNAKE_CASE =get_encoder_layer_array(_UpperCamelCase , '_output_dense/kernel' ) _SCREAMING_SNAKE_CASE =get_encoder_layer_array(_UpperCamelCase , '_output_dense/bias' ) _SCREAMING_SNAKE_CASE =get_encoder_layer_array(_UpperCamelCase , '_output_layer_norm/gamma' ) _SCREAMING_SNAKE_CASE =get_encoder_layer_array(_UpperCamelCase , '_output_layer_norm/beta' ) # Embeddings _SCREAMING_SNAKE_CASE =get_encoder_array('_position_embedding_layer/embeddings' ) _SCREAMING_SNAKE_CASE =get_encoder_array('_type_embedding_layer/embeddings' ) _SCREAMING_SNAKE_CASE =get_encoder_array('_embedding_norm_layer/gamma' ) _SCREAMING_SNAKE_CASE =get_encoder_array('_embedding_norm_layer/beta' ) # LM Head _SCREAMING_SNAKE_CASE =model.cls.predictions.transform _SCREAMING_SNAKE_CASE =get_masked_lm_array('dense/kernel' ) _SCREAMING_SNAKE_CASE =get_masked_lm_array('dense/bias' ) _SCREAMING_SNAKE_CASE =get_masked_lm_array('layer_norm/gamma' ) _SCREAMING_SNAKE_CASE =get_masked_lm_array('layer_norm/beta' ) _SCREAMING_SNAKE_CASE =get_masked_lm_array('embedding_table' ) # Pooling _SCREAMING_SNAKE_CASE =BertPooler(config=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =get_encoder_array('_pooler_layer/kernel' ) _SCREAMING_SNAKE_CASE =get_encoder_array('_pooler_layer/bias' ) # Export final model model.save_pretrained(_UpperCamelCase ) # Integration test - should load without any errors ;) _SCREAMING_SNAKE_CASE =BertForMaskedLM.from_pretrained(_UpperCamelCase ) print(new_model.eval() ) print('Model conversion was done sucessfully!' ) if __name__ == "__main__": lowerCamelCase : Optional[Any] = argparse.ArgumentParser() parser.add_argument( "--tf_checkpoint_path", type=str, required=True, help="Path to the TensorFlow Token Dropping checkpoint path." ) parser.add_argument( "--bert_config_file", type=str, required=True, help="The config json file corresponding to the BERT model. This specifies the model architecture.", ) parser.add_argument( "--pytorch_dump_path", type=str, required=True, help="Path to the output PyTorch model.", ) lowerCamelCase : Union[str, Any] = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
47
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase : Any = { "configuration_funnel": ["FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP", "FunnelConfig"], "convert_funnel_original_tf_checkpoint_to_pytorch": [], "tokenization_funnel": ["FunnelTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[Any] = ["FunnelTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[str] = [ "FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST", "FunnelBaseModel", "FunnelForMaskedLM", "FunnelForMultipleChoice", "FunnelForPreTraining", "FunnelForQuestionAnswering", "FunnelForSequenceClassification", "FunnelForTokenClassification", "FunnelModel", "FunnelPreTrainedModel", "load_tf_weights_in_funnel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Union[str, Any] = [ "TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST", "TFFunnelBaseModel", "TFFunnelForMaskedLM", "TFFunnelForMultipleChoice", "TFFunnelForPreTraining", "TFFunnelForQuestionAnswering", "TFFunnelForSequenceClassification", "TFFunnelForTokenClassification", "TFFunnelModel", "TFFunnelPreTrainedModel", ] if TYPE_CHECKING: from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig from .tokenization_funnel import FunnelTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_funnel_fast import FunnelTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_funnel import ( FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, FunnelBaseModel, FunnelForMaskedLM, FunnelForMultipleChoice, FunnelForPreTraining, FunnelForQuestionAnswering, FunnelForSequenceClassification, FunnelForTokenClassification, FunnelModel, FunnelPreTrainedModel, load_tf_weights_in_funnel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_funnel import ( TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, TFFunnelPreTrainedModel, ) else: import sys lowerCamelCase : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
47
1
'''simple docstring''' from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef import datasets lowerCamelCase : List[Any] = "\\n@inproceedings{wang2019glue,\n title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding},\n author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.},\n note={In the Proceedings of ICLR.},\n year={2019}\n}\n" lowerCamelCase : Optional[int] = "\\nGLUE, the General Language Understanding Evaluation benchmark\n(https://gluebenchmark.com/) is a collection of resources for training,\nevaluating, and analyzing natural language understanding systems.\n" lowerCamelCase : Dict = "\nCompute GLUE evaluation metric associated to each GLUE dataset.\nArgs:\n predictions: list of predictions to score.\n Each translation should be tokenized into a list of tokens.\n references: list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\nReturns: depending on the GLUE subset, one or several of:\n \"accuracy\": Accuracy\n \"f1\": F1 score\n \"pearson\": Pearson Correlation\n \"spearmanr\": Spearman Correlation\n \"matthews_correlation\": Matthew Correlation\nExamples:\n\n >>> glue_metric = datasets.load_metric('glue', 'sst2') # 'sst2' or any of [\"mnli\", \"mnli_mismatched\", \"mnli_matched\", \"qnli\", \"rte\", \"wnli\", \"hans\"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> glue_metric = datasets.load_metric('glue', 'mrpc') # 'mrpc' or 'qqp'\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> glue_metric = datasets.load_metric('glue', 'stsb')\n >>> references = [0., 1., 2., 3., 4., 5.]\n >>> predictions = [0., 1., 2., 3., 4., 5.]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print({\"pearson\": round(results[\"pearson\"], 2), \"spearmanr\": round(results[\"spearmanr\"], 2)})\n {'pearson': 1.0, 'spearmanr': 1.0}\n\n >>> glue_metric = datasets.load_metric('glue', 'cola')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'matthews_correlation': 1.0}\n" def _lowerCAmelCase ( _UpperCamelCase : List[Any] , _UpperCamelCase : Optional[Any] ) -> Dict: """simple docstring""" return float((preds == labels).mean() ) def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =simple_accuracy(_UpperCamelCase , _UpperCamelCase ) _SCREAMING_SNAKE_CASE =float(fa_score(y_true=_UpperCamelCase , y_pred=_UpperCamelCase ) ) return { "accuracy": acc, "f1": fa, } def _lowerCAmelCase ( _UpperCamelCase : List[Any] , _UpperCamelCase : str ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE =float(pearsonr(_UpperCamelCase , _UpperCamelCase )[0] ) _SCREAMING_SNAKE_CASE =float(spearmanr(_UpperCamelCase , _UpperCamelCase )[0] ) return { "pearson": pearson_corr, "spearmanr": spearman_corr, } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def A ( self : List[str] ) -> List[str]: '''simple docstring''' if self.config_name not in [ "sst2", "mnli", "mnli_mismatched", "mnli_matched", "cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans", ]: raise KeyError( 'You should supply a configuration name selected in ' '["sst2", "mnli", "mnli_mismatched", "mnli_matched", ' '"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('int64' if self.config_name != 'stsb' else 'float32' ), 'references': datasets.Value('int64' if self.config_name != 'stsb' else 'float32' ), } ) , codebase_urls=[] , reference_urls=[] , format='numpy' , ) def A ( self : int , _a : Any , _a : int ) -> Tuple: '''simple docstring''' if self.config_name == "cola": return {"matthews_correlation": matthews_corrcoef(_a , _a )} elif self.config_name == "stsb": return pearson_and_spearman(_a , _a ) elif self.config_name in ["mrpc", "qqp"]: return acc_and_fa(_a , _a ) elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]: return {"accuracy": simple_accuracy(_a , _a )} else: raise KeyError( 'You should supply a configuration name selected in ' '["sst2", "mnli", "mnli_mismatched", "mnli_matched", ' '"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]' )
47
'''simple docstring''' import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def _lowerCAmelCase ( _UpperCamelCase : Dict , _UpperCamelCase : Any=False ) -> Optional[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =OmegaConf.load(_UpperCamelCase ) if display: print(yaml.dump(OmegaConf.to_container(_UpperCamelCase ) ) ) return config def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : Optional[Any]=None , _UpperCamelCase : Union[str, Any]=None ) -> Optional[Any]: """simple docstring""" if conf_path is None: _SCREAMING_SNAKE_CASE ='./model_checkpoints/vqgan_only.yaml' _SCREAMING_SNAKE_CASE =load_config(_UpperCamelCase , display=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =VQModel(**config.model.params ) if ckpt_path is None: _SCREAMING_SNAKE_CASE ='./model_checkpoints/vqgan_only.pt' _SCREAMING_SNAKE_CASE =torch.load(_UpperCamelCase , map_location=_UpperCamelCase ) if ".ckpt" in ckpt_path: _SCREAMING_SNAKE_CASE =sd['state_dict'] model.load_state_dict(_UpperCamelCase , strict=_UpperCamelCase ) model.to(_UpperCamelCase ) del sd return model def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : int ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =model.encode(_UpperCamelCase ) print(f"VQGAN --- {model.__class__.__name__}: latent shape: {z.shape[2:]}" ) _SCREAMING_SNAKE_CASE =model.decode(_UpperCamelCase ) return xrec def _lowerCAmelCase ( _UpperCamelCase : Dict , _UpperCamelCase : List[str]=False ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =string.rsplit('.' , 1 ) if reload: _SCREAMING_SNAKE_CASE =importlib.import_module(_UpperCamelCase ) importlib.reload(_UpperCamelCase ) return getattr(importlib.import_module(_UpperCamelCase , package=_UpperCamelCase ) , cls ) def _lowerCAmelCase ( _UpperCamelCase : str ) -> List[str]: """simple docstring""" if "target" not in config: raise KeyError('Expected key `target` to instantiate.' ) return get_obj_from_str(config['target'] )(**config.get('params' , {} ) ) def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : List[Any] , _UpperCamelCase : List[str]=True , _UpperCamelCase : int=True ) -> Union[str, Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =instantiate_from_config(_UpperCamelCase ) if sd is not None: model.load_state_dict(_UpperCamelCase ) if gpu: model.cuda() if eval_mode: model.eval() return {"model": model} def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Optional[Any] , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Optional[int] ) -> List[Any]: """simple docstring""" if ckpt: _SCREAMING_SNAKE_CASE =torch.load(_UpperCamelCase , map_location='cpu' ) _SCREAMING_SNAKE_CASE =pl_sd['global_step'] print(f"loaded model from global step {global_step}." ) else: _SCREAMING_SNAKE_CASE ={'state_dict': None} _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =load_model_from_config(config.model , pl_sd['state_dict'] , gpu=_UpperCamelCase , eval_mode=_UpperCamelCase )['model'] return model, global_step
47
1
'''simple docstring''' import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated lowerCamelCase : Dict = collections.namedtuple("_Datasets", ["train", "validation", "test"]) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ lowerCamelCase : int = "https://storage.googleapis.com/cvdf-datasets/mnist/" def _lowerCAmelCase ( _UpperCamelCase : Dict ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =numpy.dtype(numpy.uintaa ).newbyteorder('>' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=_UpperCamelCase )[0] @deprecated(_UpperCamelCase , 'Please use tf.data to implement this functionality.' ) def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] ) -> List[Any]: """simple docstring""" print('Extracting' , f.name ) with gzip.GzipFile(fileobj=_UpperCamelCase ) as bytestream: _SCREAMING_SNAKE_CASE =_readaa(_UpperCamelCase ) if magic != 20_51: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % (magic, f.name) ) _SCREAMING_SNAKE_CASE =_readaa(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =_readaa(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =_readaa(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =bytestream.read(rows * cols * num_images ) _SCREAMING_SNAKE_CASE =numpy.frombuffer(_UpperCamelCase , dtype=numpy.uinta ) _SCREAMING_SNAKE_CASE =data.reshape(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , 1 ) return data @deprecated(_UpperCamelCase , 'Please use tf.one_hot on tensors.' ) def _lowerCAmelCase ( _UpperCamelCase : int , _UpperCamelCase : int ) -> Optional[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =labels_dense.shape[0] _SCREAMING_SNAKE_CASE =numpy.arange(_UpperCamelCase ) * num_classes _SCREAMING_SNAKE_CASE =numpy.zeros((num_labels, num_classes) ) _SCREAMING_SNAKE_CASE =1 return labels_one_hot @deprecated(_UpperCamelCase , 'Please use tf.data to implement this functionality.' ) def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Tuple=False , _UpperCamelCase : Tuple=10 ) -> str: """simple docstring""" print('Extracting' , f.name ) with gzip.GzipFile(fileobj=_UpperCamelCase ) as bytestream: _SCREAMING_SNAKE_CASE =_readaa(_UpperCamelCase ) if magic != 20_49: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (magic, f.name) ) _SCREAMING_SNAKE_CASE =_readaa(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =bytestream.read(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =numpy.frombuffer(_UpperCamelCase , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(_UpperCamelCase , _UpperCamelCase ) return labels class A__ : @deprecated( _a , 'Please use alternatives such as official/mnist/_DataSet.py' ' from tensorflow/models.' , ) def __init__( self : Any , _a : Union[str, Any] , _a : Optional[int] , _a : Dict=False , _a : Tuple=False , _a : List[Any]=dtypes.floataa , _a : Optional[int]=True , _a : List[Any]=None , ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =random_seed.get_seed(_a ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) _SCREAMING_SNAKE_CASE =dtypes.as_dtype(_a ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('Invalid image dtype %r, expected uint8 or float32' % dtype ) if fake_data: _SCREAMING_SNAKE_CASE =1_0000 _SCREAMING_SNAKE_CASE =one_hot else: assert ( images.shape[0] == labels.shape[0] ), f"images.shape: {images.shape} labels.shape: {labels.shape}" _SCREAMING_SNAKE_CASE =images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 _SCREAMING_SNAKE_CASE =images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. _SCREAMING_SNAKE_CASE =images.astype(numpy.floataa ) _SCREAMING_SNAKE_CASE =numpy.multiply(_a , 1.0 / 2_55.0 ) _SCREAMING_SNAKE_CASE =images _SCREAMING_SNAKE_CASE =labels _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 @property def A ( self : Union[str, Any] ) -> Dict: '''simple docstring''' return self._images @property def A ( self : str ) -> List[str]: '''simple docstring''' return self._labels @property def A ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' return self._num_examples @property def A ( self : Optional[int] ) -> List[str]: '''simple docstring''' return self._epochs_completed def A ( self : Dict , _a : Dict , _a : Dict=False , _a : Tuple=True ) -> Optional[Any]: '''simple docstring''' if fake_data: _SCREAMING_SNAKE_CASE =[1] * 784 _SCREAMING_SNAKE_CASE =[1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(_a )], [fake_label for _ in range(_a )], ) _SCREAMING_SNAKE_CASE =self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: _SCREAMING_SNAKE_CASE =numpy.arange(self._num_examples ) numpy.random.shuffle(_a ) _SCREAMING_SNAKE_CASE =self.images[perma] _SCREAMING_SNAKE_CASE =self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch _SCREAMING_SNAKE_CASE =self._num_examples - start _SCREAMING_SNAKE_CASE =self._images[start : self._num_examples] _SCREAMING_SNAKE_CASE =self._labels[start : self._num_examples] # Shuffle the data if shuffle: _SCREAMING_SNAKE_CASE =numpy.arange(self._num_examples ) numpy.random.shuffle(_a ) _SCREAMING_SNAKE_CASE =self.images[perm] _SCREAMING_SNAKE_CASE =self.labels[perm] # Start next epoch _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =batch_size - rest_num_examples _SCREAMING_SNAKE_CASE =self._index_in_epoch _SCREAMING_SNAKE_CASE =self._images[start:end] _SCREAMING_SNAKE_CASE =self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size _SCREAMING_SNAKE_CASE =self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(_UpperCamelCase , 'Please write your own downloading logic.' ) def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Optional[int] , _UpperCamelCase : List[Any] ) -> int: """simple docstring""" if not gfile.Exists(_UpperCamelCase ): gfile.MakeDirs(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =os.path.join(_UpperCamelCase , _UpperCamelCase ) if not gfile.Exists(_UpperCamelCase ): urllib.request.urlretrieve(_UpperCamelCase , _UpperCamelCase ) # noqa: S310 with gfile.GFile(_UpperCamelCase ) as f: _SCREAMING_SNAKE_CASE =f.size() print('Successfully downloaded' , _UpperCamelCase , _UpperCamelCase , 'bytes.' ) return filepath @deprecated( _UpperCamelCase , 'Please use alternatives such as:' ' tensorflow_datasets.load(\'mnist\')' ) def _lowerCAmelCase ( _UpperCamelCase : Optional[Any] , _UpperCamelCase : str=False , _UpperCamelCase : str=False , _UpperCamelCase : Any=dtypes.floataa , _UpperCamelCase : Any=True , _UpperCamelCase : Any=50_00 , _UpperCamelCase : Optional[int]=None , _UpperCamelCase : List[Any]=DEFAULT_SOURCE_URL , ) -> Optional[Any]: """simple docstring""" if fake_data: def fake(): return _DataSet( [] , [] , fake_data=_UpperCamelCase , one_hot=_UpperCamelCase , dtype=_UpperCamelCase , seed=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =fake() _SCREAMING_SNAKE_CASE =fake() _SCREAMING_SNAKE_CASE =fake() return _Datasets(train=_UpperCamelCase , validation=_UpperCamelCase , test=_UpperCamelCase ) if not source_url: # empty string check _SCREAMING_SNAKE_CASE =DEFAULT_SOURCE_URL _SCREAMING_SNAKE_CASE ='train-images-idx3-ubyte.gz' _SCREAMING_SNAKE_CASE ='train-labels-idx1-ubyte.gz' _SCREAMING_SNAKE_CASE ='t10k-images-idx3-ubyte.gz' _SCREAMING_SNAKE_CASE ='t10k-labels-idx1-ubyte.gz' _SCREAMING_SNAKE_CASE =_maybe_download( _UpperCamelCase , _UpperCamelCase , source_url + train_images_file ) with gfile.Open(_UpperCamelCase , 'rb' ) as f: _SCREAMING_SNAKE_CASE =_extract_images(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =_maybe_download( _UpperCamelCase , _UpperCamelCase , source_url + train_labels_file ) with gfile.Open(_UpperCamelCase , 'rb' ) as f: _SCREAMING_SNAKE_CASE =_extract_labels(_UpperCamelCase , one_hot=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =_maybe_download( _UpperCamelCase , _UpperCamelCase , source_url + test_images_file ) with gfile.Open(_UpperCamelCase , 'rb' ) as f: _SCREAMING_SNAKE_CASE =_extract_images(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =_maybe_download( _UpperCamelCase , _UpperCamelCase , source_url + test_labels_file ) with gfile.Open(_UpperCamelCase , 'rb' ) as f: _SCREAMING_SNAKE_CASE =_extract_labels(_UpperCamelCase , one_hot=_UpperCamelCase ) if not 0 <= validation_size <= len(_UpperCamelCase ): _SCREAMING_SNAKE_CASE =( 'Validation size should be between 0 and ' f"{len(_UpperCamelCase )}. Received: {validation_size}." ) raise ValueError(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =train_images[:validation_size] _SCREAMING_SNAKE_CASE =train_labels[:validation_size] _SCREAMING_SNAKE_CASE =train_images[validation_size:] _SCREAMING_SNAKE_CASE =train_labels[validation_size:] _SCREAMING_SNAKE_CASE ={'dtype': dtype, 'reshape': reshape, 'seed': seed} _SCREAMING_SNAKE_CASE =_DataSet(_UpperCamelCase , _UpperCamelCase , **_UpperCamelCase ) _SCREAMING_SNAKE_CASE =_DataSet(_UpperCamelCase , _UpperCamelCase , **_UpperCamelCase ) _SCREAMING_SNAKE_CASE =_DataSet(_UpperCamelCase , _UpperCamelCase , **_UpperCamelCase ) return _Datasets(train=_UpperCamelCase , validation=_UpperCamelCase , test=_UpperCamelCase )
47
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase : int = {"configuration_mbart": ["MBART_PRETRAINED_CONFIG_ARCHIVE_MAP", "MBartConfig", "MBartOnnxConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[Any] = ["MBartTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Dict = ["MBartTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : int = [ "MBART_PRETRAINED_MODEL_ARCHIVE_LIST", "MBartForCausalLM", "MBartForConditionalGeneration", "MBartForQuestionAnswering", "MBartForSequenceClassification", "MBartModel", "MBartPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Union[str, Any] = [ "TFMBartForConditionalGeneration", "TFMBartModel", "TFMBartPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[Any] = [ "FlaxMBartForConditionalGeneration", "FlaxMBartForQuestionAnswering", "FlaxMBartForSequenceClassification", "FlaxMBartModel", "FlaxMBartPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys lowerCamelCase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
47
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowerCamelCase : List[str] = logging.get_logger(__name__) lowerCamelCase : List[Any] = { "facebook/convnextv2-tiny-1k-224": "https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json", } class A__ ( A__ , A__ ): A__ = 'convnextv2' def __init__( self : Tuple , _a : Optional[int]=3 , _a : Any=4 , _a : int=4 , _a : Union[str, Any]=None , _a : List[str]=None , _a : Optional[Any]="gelu" , _a : Any=0.02 , _a : Any=1e-12 , _a : Tuple=0.0 , _a : int=224 , _a : Any=None , _a : Optional[int]=None , **_a : List[str] , ) -> Optional[Any]: '''simple docstring''' super().__init__(**_a ) _SCREAMING_SNAKE_CASE =num_channels _SCREAMING_SNAKE_CASE =patch_size _SCREAMING_SNAKE_CASE =num_stages _SCREAMING_SNAKE_CASE =[96, 192, 384, 768] if hidden_sizes is None else hidden_sizes _SCREAMING_SNAKE_CASE =[3, 3, 9, 3] if depths is None else depths _SCREAMING_SNAKE_CASE =hidden_act _SCREAMING_SNAKE_CASE =initializer_range _SCREAMING_SNAKE_CASE =layer_norm_eps _SCREAMING_SNAKE_CASE =drop_path_rate _SCREAMING_SNAKE_CASE =image_size _SCREAMING_SNAKE_CASE =['stem'] + [f"stage{idx}" for idx in range(1 , len(self.depths ) + 1 )] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =get_aligned_output_features_output_indices( out_features=_a , out_indices=_a , stage_names=self.stage_names )
47
'''simple docstring''' from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : List[Any] = logging.get_logger(__name__) lowerCamelCase : str = { "huggingface/time-series-transformer-tourism-monthly": ( "https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json" ), # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer } class A__ ( A__ ): A__ = 'time_series_transformer' A__ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self : Optional[int] , _a : Optional[int] = None , _a : Optional[int] = None , _a : str = "student_t" , _a : str = "nll" , _a : int = 1 , _a : List[int] = [1, 2, 3, 4, 5, 6, 7] , _a : Optional[Union[str, bool]] = "mean" , _a : int = 0 , _a : int = 0 , _a : int = 0 , _a : int = 0 , _a : Optional[List[int]] = None , _a : Optional[List[int]] = None , _a : int = 32 , _a : int = 32 , _a : int = 2 , _a : int = 2 , _a : int = 2 , _a : int = 2 , _a : bool = True , _a : str = "gelu" , _a : int = 64 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : int = 100 , _a : float = 0.02 , _a : Union[str, Any]=True , **_a : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =prediction_length _SCREAMING_SNAKE_CASE =context_length or prediction_length _SCREAMING_SNAKE_CASE =distribution_output _SCREAMING_SNAKE_CASE =loss _SCREAMING_SNAKE_CASE =input_size _SCREAMING_SNAKE_CASE =num_time_features _SCREAMING_SNAKE_CASE =lags_sequence _SCREAMING_SNAKE_CASE =scaling _SCREAMING_SNAKE_CASE =num_dynamic_real_features _SCREAMING_SNAKE_CASE =num_static_real_features _SCREAMING_SNAKE_CASE =num_static_categorical_features 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`' ) _SCREAMING_SNAKE_CASE =cardinality else: _SCREAMING_SNAKE_CASE =[0] 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`' ) _SCREAMING_SNAKE_CASE =embedding_dimension else: _SCREAMING_SNAKE_CASE =[min(50 , (cat + 1) // 2 ) for cat in self.cardinality] _SCREAMING_SNAKE_CASE =num_parallel_samples # Transformer architecture configuration _SCREAMING_SNAKE_CASE =input_size * len(_a ) + self._number_of_features _SCREAMING_SNAKE_CASE =d_model _SCREAMING_SNAKE_CASE =encoder_attention_heads _SCREAMING_SNAKE_CASE =decoder_attention_heads _SCREAMING_SNAKE_CASE =encoder_ffn_dim _SCREAMING_SNAKE_CASE =decoder_ffn_dim _SCREAMING_SNAKE_CASE =encoder_layers _SCREAMING_SNAKE_CASE =decoder_layers _SCREAMING_SNAKE_CASE =dropout _SCREAMING_SNAKE_CASE =attention_dropout _SCREAMING_SNAKE_CASE =activation_dropout _SCREAMING_SNAKE_CASE =encoder_layerdrop _SCREAMING_SNAKE_CASE =decoder_layerdrop _SCREAMING_SNAKE_CASE =activation_function _SCREAMING_SNAKE_CASE =init_std _SCREAMING_SNAKE_CASE =use_cache super().__init__(is_encoder_decoder=_a , **_a ) @property def A ( self : List[Any] ) -> int: '''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 )
47
1
'''simple docstring''' import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device lowerCamelCase : Optional[int] = False class A__ ( unittest.TestCase ): pass @slow @require_torch_gpu class A__ ( unittest.TestCase ): def A ( self : Tuple ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =VersatileDiffusionImageVariationPipeline.from_pretrained('shi-labs/versatile-diffusion' ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) _SCREAMING_SNAKE_CASE =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg' ) _SCREAMING_SNAKE_CASE =torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE =pipe( image=_a , generator=_a , guidance_scale=7.5 , num_inference_steps=50 , output_type='numpy' , ).images _SCREAMING_SNAKE_CASE =image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) _SCREAMING_SNAKE_CASE =np.array([0.04_41, 0.04_69, 0.05_07, 0.05_75, 0.06_32, 0.06_50, 0.08_65, 0.09_09, 0.09_45] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
47
'''simple docstring''' import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets lowerCamelCase : List[Any] = "\\n @inproceedings{kakwani2020indicnlpsuite,\n title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}},\n author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar},\n year={2020},\n booktitle={Findings of EMNLP},\n}\n" lowerCamelCase : Optional[Any] = "\\n IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide\n variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te.\n" lowerCamelCase : int = "\nCompute IndicGLUE evaluation metric associated to each IndicGLUE dataset.\nArgs:\n predictions: list of predictions to score (as int64),\n except for 'cvit-mkb-clsr' where each prediction is a vector (of float32).\n references: list of ground truth labels corresponding to the predictions (as int64),\n except for 'cvit-mkb-clsr' where each reference is a vector (of float32).\nReturns: depending on the IndicGLUE subset, one or several of:\n \"accuracy\": Accuracy\n \"f1\": F1 score\n \"precision\": Precision@10\nExamples:\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr')\n >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'precision@10': 1.0}\n\n" def _lowerCAmelCase ( _UpperCamelCase : List[str] , _UpperCamelCase : Tuple ) -> List[Any]: """simple docstring""" return float((preds == labels).mean() ) def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Any ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =simple_accuracy(_UpperCamelCase , _UpperCamelCase ) _SCREAMING_SNAKE_CASE =float(fa_score(y_true=_UpperCamelCase , y_pred=_UpperCamelCase ) ) return { "accuracy": acc, "f1": fa, } def _lowerCAmelCase ( _UpperCamelCase : Any , _UpperCamelCase : int ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =en_sentvecs.shape[0] # mean centering _SCREAMING_SNAKE_CASE =en_sentvecs - np.mean(_UpperCamelCase , axis=0 ) _SCREAMING_SNAKE_CASE =in_sentvecs - np.mean(_UpperCamelCase , axis=0 ) _SCREAMING_SNAKE_CASE =cdist(_UpperCamelCase , _UpperCamelCase , 'cosine' ) _SCREAMING_SNAKE_CASE =np.array(range(_UpperCamelCase ) ) _SCREAMING_SNAKE_CASE =sim.argsort(axis=1 )[:, :10] _SCREAMING_SNAKE_CASE =np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def A ( self : Any ) -> List[str]: '''simple docstring''' if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('int64' ) if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32' ) ), 'references': datasets.Value('int64' ) if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32' ) ), } ) , codebase_urls=[] , reference_urls=[] , format='numpy' if self.config_name != 'cvit-mkb-clsr' else None , ) def A ( self : List[str] , _a : Tuple , _a : Optional[int] ) -> int: '''simple docstring''' if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(_a , _a )} elif self.config_name in ["wiki-ner"]: return acc_and_fa(_a , _a ) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(_a , _a )} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]' )
47
1
'''simple docstring''' def _lowerCAmelCase ( _UpperCamelCase : list , _UpperCamelCase : int = 0 ) -> list: """simple docstring""" _SCREAMING_SNAKE_CASE =length or len(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =False for i in range(length - 1 ): if list_data[i] > list_data[i + 1]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =list_data[i + 1], list_data[i] _SCREAMING_SNAKE_CASE =True return list_data if not swapped else bubble_sort(_UpperCamelCase , length - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
47
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase : Dict = logging.get_logger(__name__) lowerCamelCase : List[Any] = { "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json", } class A__ ( A__ ): A__ = 'deta' A__ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Tuple , _a : Optional[int]=None , _a : int=900 , _a : Optional[Any]=2048 , _a : int=6 , _a : Tuple=2048 , _a : Optional[int]=8 , _a : Any=6 , _a : str=1024 , _a : int=8 , _a : int=0.0 , _a : Optional[Any]=True , _a : Tuple="relu" , _a : Union[str, Any]=256 , _a : Tuple=0.1 , _a : str=0.0 , _a : Dict=0.0 , _a : Tuple=0.02 , _a : Union[str, Any]=1.0 , _a : Any=True , _a : Tuple=False , _a : List[Any]="sine" , _a : str=5 , _a : List[Any]=4 , _a : str=4 , _a : Union[str, Any]=True , _a : Optional[int]=300 , _a : Dict=True , _a : List[Any]=True , _a : List[Any]=1 , _a : List[str]=5 , _a : int=2 , _a : Dict=1 , _a : str=1 , _a : Optional[Any]=5 , _a : Union[str, Any]=2 , _a : List[str]=0.1 , _a : List[Any]=0.25 , **_a : Union[str, Any] , ) -> List[str]: '''simple docstring''' if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) _SCREAMING_SNAKE_CASE =CONFIG_MAPPING['resnet'](out_features=['stage2', 'stage3', 'stage4'] ) else: if isinstance(_a , _a ): _SCREAMING_SNAKE_CASE =backbone_config.pop('model_type' ) _SCREAMING_SNAKE_CASE =CONFIG_MAPPING[backbone_model_type] _SCREAMING_SNAKE_CASE =config_class.from_dict(_a ) _SCREAMING_SNAKE_CASE =backbone_config _SCREAMING_SNAKE_CASE =num_queries _SCREAMING_SNAKE_CASE =max_position_embeddings _SCREAMING_SNAKE_CASE =d_model _SCREAMING_SNAKE_CASE =encoder_ffn_dim _SCREAMING_SNAKE_CASE =encoder_layers _SCREAMING_SNAKE_CASE =encoder_attention_heads _SCREAMING_SNAKE_CASE =decoder_ffn_dim _SCREAMING_SNAKE_CASE =decoder_layers _SCREAMING_SNAKE_CASE =decoder_attention_heads _SCREAMING_SNAKE_CASE =dropout _SCREAMING_SNAKE_CASE =attention_dropout _SCREAMING_SNAKE_CASE =activation_dropout _SCREAMING_SNAKE_CASE =activation_function _SCREAMING_SNAKE_CASE =init_std _SCREAMING_SNAKE_CASE =init_xavier_std _SCREAMING_SNAKE_CASE =encoder_layerdrop _SCREAMING_SNAKE_CASE =auxiliary_loss _SCREAMING_SNAKE_CASE =position_embedding_type # deformable attributes _SCREAMING_SNAKE_CASE =num_feature_levels _SCREAMING_SNAKE_CASE =encoder_n_points _SCREAMING_SNAKE_CASE =decoder_n_points _SCREAMING_SNAKE_CASE =two_stage _SCREAMING_SNAKE_CASE =two_stage_num_proposals _SCREAMING_SNAKE_CASE =with_box_refine _SCREAMING_SNAKE_CASE =assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError('If two_stage is True, with_box_refine must be True.' ) # Hungarian matcher _SCREAMING_SNAKE_CASE =class_cost _SCREAMING_SNAKE_CASE =bbox_cost _SCREAMING_SNAKE_CASE =giou_cost # Loss coefficients _SCREAMING_SNAKE_CASE =mask_loss_coefficient _SCREAMING_SNAKE_CASE =dice_loss_coefficient _SCREAMING_SNAKE_CASE =bbox_loss_coefficient _SCREAMING_SNAKE_CASE =giou_loss_coefficient _SCREAMING_SNAKE_CASE =eos_coefficient _SCREAMING_SNAKE_CASE =focal_alpha super().__init__(is_encoder_decoder=_a , **_a ) @property def A ( self : Dict ) -> int: '''simple docstring''' return self.encoder_attention_heads @property def A ( self : List[Any] ) -> int: '''simple docstring''' return self.d_model def A ( self : Optional[int] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =copy.deepcopy(self.__dict__ ) _SCREAMING_SNAKE_CASE =self.backbone_config.to_dict() _SCREAMING_SNAKE_CASE =self.__class__.model_type return output
47
1
'''simple docstring''' import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging lowerCamelCase : Dict = logging.get_logger(__name__) lowerCamelCase : Any = r"\n Args:\n input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):\n Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax\n or scores for each vocabulary token after SoftMax.\n kwargs (`Dict[str, Any]`, *optional*):\n Additional stopping criteria specific kwargs.\n\n Return:\n `bool`. `False` indicates we should continue, `True` indicates we should stop.\n\n" class A__ ( A__ ): @add_start_docstrings(_a ) def __call__( self : List[str] , _a : torch.LongTensor , _a : torch.FloatTensor , **_a : str ) -> bool: '''simple docstring''' raise NotImplementedError('StoppingCriteria needs to be subclassed' ) class A__ ( A__ ): def __init__( self : List[Any] , _a : int , _a : Optional[int] = None ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =max_length _SCREAMING_SNAKE_CASE =max_position_embeddings @add_start_docstrings(_a ) def __call__( self : List[str] , _a : torch.LongTensor , _a : torch.FloatTensor , **_a : Tuple ) -> bool: '''simple docstring''' _SCREAMING_SNAKE_CASE =input_ids.shape[-1] _SCREAMING_SNAKE_CASE =cur_len >= self.max_length if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings: logger.warning_once( 'This is a friendly reminder - the current text generation call will exceed the model\'s predefined ' f"maximum length ({self.max_position_embeddings}). Depending on the model, you may observe " 'exceptions, performance degradation, or nothing at all.' ) return is_done class A__ ( A__ ): def __init__( self : Optional[int] , _a : int , _a : int ) -> Optional[int]: '''simple docstring''' warnings.warn( 'The class `MaxNewTokensCriteria` is deprecated. ' f"Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` " 'with `max_length = start_length + max_new_tokens` instead.' , _a , ) _SCREAMING_SNAKE_CASE =start_length _SCREAMING_SNAKE_CASE =max_new_tokens _SCREAMING_SNAKE_CASE =start_length + max_new_tokens @add_start_docstrings(_a ) def __call__( self : List[Any] , _a : torch.LongTensor , _a : torch.FloatTensor , **_a : List[Any] ) -> bool: '''simple docstring''' return input_ids.shape[-1] >= self.max_length class A__ ( A__ ): def __init__( self : Optional[int] , _a : float , _a : Optional[float] = None ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =max_time _SCREAMING_SNAKE_CASE =time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(_a ) def __call__( self : Tuple , _a : torch.LongTensor , _a : torch.FloatTensor , **_a : List[Any] ) -> bool: '''simple docstring''' return time.time() - self.initial_timestamp > self.max_time class A__ ( A__ ): @add_start_docstrings(_a ) def __call__( self : List[Any] , _a : torch.LongTensor , _a : torch.FloatTensor , **_a : Optional[int] ) -> bool: '''simple docstring''' return any(criteria(_a , _a ) for criteria in self ) @property def A ( self : List[Any] ) -> Optional[int]: '''simple docstring''' for stopping_criterium in self: if isinstance(_a , _a ): return stopping_criterium.max_length elif isinstance(_a , _a ): return stopping_criterium.max_length return None def _lowerCAmelCase ( _UpperCamelCase : StoppingCriteriaList , _UpperCamelCase : int ) -> StoppingCriteriaList: """simple docstring""" _SCREAMING_SNAKE_CASE =stopping_criteria.max_length _SCREAMING_SNAKE_CASE =deepcopy(_UpperCamelCase ) if stopping_max_length is not None and stopping_max_length != max_length: warnings.warn('You set different `max_length` for stopping criteria and `max_length` parameter' , _UpperCamelCase ) elif stopping_max_length is None: new_stopping_criteria.append(MaxLengthCriteria(max_length=_UpperCamelCase ) ) return new_stopping_criteria
47
'''simple docstring''' import numpy as np from PIL import Image def _lowerCAmelCase ( _UpperCamelCase : np.ndarray , _UpperCamelCase : int , _UpperCamelCase : int ) -> np.ndarray: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 # compute the shape of the output matrix _SCREAMING_SNAKE_CASE =(arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape _SCREAMING_SNAKE_CASE =np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix _SCREAMING_SNAKE_CASE =np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 return updated_arr def _lowerCAmelCase ( _UpperCamelCase : np.ndarray , _UpperCamelCase : int , _UpperCamelCase : int ) -> np.ndarray: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 # compute the shape of the output matrix _SCREAMING_SNAKE_CASE =(arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape _SCREAMING_SNAKE_CASE =np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix _SCREAMING_SNAKE_CASE =int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name="avgpooling", verbose=True) # Loading the image lowerCamelCase : Optional[Any] = Image.open("path_to_image") # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
47
1
'''simple docstring''' from copy import deepcopy from typing import Optional, Union import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_tf_available, is_torch_available if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf class A__ ( A__ ): A__ = ['image_processor'] A__ = 'SamImageProcessor' def __init__( self : Optional[Any] , _a : Any ) -> Dict: '''simple docstring''' super().__init__(_a ) _SCREAMING_SNAKE_CASE =self.image_processor _SCREAMING_SNAKE_CASE =-10 _SCREAMING_SNAKE_CASE =self.image_processor.size['longest_edge'] def __call__( self : Any , _a : Optional[int]=None , _a : str=None , _a : str=None , _a : Any=None , _a : Optional[Union[str, TensorType]] = None , **_a : Optional[int] , ) -> BatchEncoding: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processor( _a , return_tensors=_a , **_a , ) # pop arguments that are not used in the foward but used nevertheless _SCREAMING_SNAKE_CASE =encoding_image_processor['original_sizes'] if hasattr(_a , 'numpy' ): # Checks if Torch or TF tensor _SCREAMING_SNAKE_CASE =original_sizes.numpy() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self._check_and_preprocess_points( input_points=_a , input_labels=_a , input_boxes=_a , ) _SCREAMING_SNAKE_CASE =self._normalize_and_convert( _a , _a , input_points=_a , input_labels=_a , input_boxes=_a , return_tensors=_a , ) return encoding_image_processor def A ( self : List[str] , _a : str , _a : Optional[Any] , _a : Optional[int]=None , _a : Union[str, Any]=None , _a : Optional[int]=None , _a : Union[str, Any]="pt" , ) -> Optional[int]: '''simple docstring''' if input_points is not None: if len(_a ) != len(_a ): _SCREAMING_SNAKE_CASE =[ self._normalize_coordinates(self.target_size , _a , original_sizes[0] ) for point in input_points ] else: _SCREAMING_SNAKE_CASE =[ self._normalize_coordinates(self.target_size , _a , _a ) for point, original_size in zip(_a , _a ) ] # check that all arrays have the same shape if not all(point.shape == input_points[0].shape for point in input_points ): if input_labels is not None: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self._pad_points_and_labels(_a , _a ) _SCREAMING_SNAKE_CASE =np.array(_a ) if input_labels is not None: _SCREAMING_SNAKE_CASE =np.array(_a ) if input_boxes is not None: if len(_a ) != len(_a ): _SCREAMING_SNAKE_CASE =[ self._normalize_coordinates(self.target_size , _a , original_sizes[0] , is_bounding_box=_a ) for box in input_boxes ] else: _SCREAMING_SNAKE_CASE =[ self._normalize_coordinates(self.target_size , _a , _a , is_bounding_box=_a ) for box, original_size in zip(_a , _a ) ] _SCREAMING_SNAKE_CASE =np.array(_a ) if input_boxes is not None: if return_tensors == "pt": _SCREAMING_SNAKE_CASE =torch.from_numpy(_a ) # boxes batch size of 1 by default _SCREAMING_SNAKE_CASE =input_boxes.unsqueeze(1 ) if len(input_boxes.shape ) != 3 else input_boxes elif return_tensors == "tf": _SCREAMING_SNAKE_CASE =tf.convert_to_tensor(_a ) # boxes batch size of 1 by default _SCREAMING_SNAKE_CASE =tf.expand_dims(_a , 1 ) if len(input_boxes.shape ) != 3 else input_boxes encoding_image_processor.update({'input_boxes': input_boxes} ) if input_points is not None: if return_tensors == "pt": _SCREAMING_SNAKE_CASE =torch.from_numpy(_a ) # point batch size of 1 by default _SCREAMING_SNAKE_CASE =input_points.unsqueeze(1 ) if len(input_points.shape ) != 4 else input_points elif return_tensors == "tf": _SCREAMING_SNAKE_CASE =tf.convert_to_tensor(_a ) # point batch size of 1 by default _SCREAMING_SNAKE_CASE =tf.expand_dims(_a , 1 ) if len(input_points.shape ) != 4 else input_points encoding_image_processor.update({'input_points': input_points} ) if input_labels is not None: if return_tensors == "pt": _SCREAMING_SNAKE_CASE =torch.from_numpy(_a ) # point batch size of 1 by default _SCREAMING_SNAKE_CASE =input_labels.unsqueeze(1 ) if len(input_labels.shape ) != 3 else input_labels elif return_tensors == "tf": _SCREAMING_SNAKE_CASE =tf.convert_to_tensor(_a ) # point batch size of 1 by default _SCREAMING_SNAKE_CASE =tf.expand_dims(_a , 1 ) if len(input_labels.shape ) != 3 else input_labels encoding_image_processor.update({'input_labels': input_labels} ) return encoding_image_processor def A ( self : Optional[int] , _a : Union[str, Any] , _a : int ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =max([point.shape[0] for point in input_points] ) _SCREAMING_SNAKE_CASE =[] for i, point in enumerate(_a ): if point.shape[0] != expected_nb_points: _SCREAMING_SNAKE_CASE =np.concatenate( [point, np.zeros((expected_nb_points - point.shape[0], 2) ) + self.point_pad_value] , axis=0 ) _SCREAMING_SNAKE_CASE =np.append(input_labels[i] , [self.point_pad_value] ) processed_input_points.append(_a ) _SCREAMING_SNAKE_CASE =processed_input_points return input_points, input_labels def A ( self : str , _a : int , _a : np.ndarray , _a : str , _a : List[str]=False ) -> np.ndarray: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =original_size _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self.image_processor._get_preprocess_shape(_a , longest_edge=_a ) _SCREAMING_SNAKE_CASE =deepcopy(_a ).astype(_a ) if is_bounding_box: _SCREAMING_SNAKE_CASE =coords.reshape(-1 , 2 , 2 ) _SCREAMING_SNAKE_CASE =coords[..., 0] * (new_w / old_w) _SCREAMING_SNAKE_CASE =coords[..., 1] * (new_h / old_h) if is_bounding_box: _SCREAMING_SNAKE_CASE =coords.reshape(-1 , 4 ) return coords def A ( self : List[str] , _a : Optional[int]=None , _a : Optional[int]=None , _a : Union[str, Any]=None , ) -> Dict: '''simple docstring''' if input_points is not None: if hasattr(_a , 'numpy' ): # Checks for TF or Torch tensor _SCREAMING_SNAKE_CASE =input_points.numpy().tolist() if not isinstance(_a , _a ) or not isinstance(input_points[0] , _a ): raise ValueError('Input points must be a list of list of floating points.' ) _SCREAMING_SNAKE_CASE =[np.array(_a ) for input_point in input_points] else: _SCREAMING_SNAKE_CASE =None if input_labels is not None: if hasattr(_a , 'numpy' ): _SCREAMING_SNAKE_CASE =input_labels.numpy().tolist() if not isinstance(_a , _a ) or not isinstance(input_labels[0] , _a ): raise ValueError('Input labels must be a list of list integers.' ) _SCREAMING_SNAKE_CASE =[np.array(_a ) for label in input_labels] else: _SCREAMING_SNAKE_CASE =None if input_boxes is not None: if hasattr(_a , 'numpy' ): _SCREAMING_SNAKE_CASE =input_boxes.numpy().tolist() if ( not isinstance(_a , _a ) or not isinstance(input_boxes[0] , _a ) or not isinstance(input_boxes[0][0] , _a ) ): raise ValueError('Input boxes must be a list of list of list of floating points.' ) _SCREAMING_SNAKE_CASE =[np.array(_a ).astype(np.floataa ) for box in input_boxes] else: _SCREAMING_SNAKE_CASE =None return input_points, input_labels, input_boxes @property def A ( self : List[Any] ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processor.model_input_names return list(dict.fromkeys(_a ) ) def A ( self : Optional[int] , *_a : str , **_a : List[Any] ) -> str: '''simple docstring''' return self.image_processor.post_process_masks(*_a , **_a )
47
'''simple docstring''' import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _lowerCAmelCase ( ) -> Any: """simple docstring""" _SCREAMING_SNAKE_CASE =ArgumentParser( description=( 'PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes' ) ) # Optional arguments for the launch helper parser.add_argument('--num_cores' , type=_UpperCamelCase , default=1 , help='Number of TPU cores to use (1 or 8).' ) # positional parser.add_argument( 'training_script' , type=_UpperCamelCase , help=( 'The full path to the single TPU training ' 'program/script to be launched in parallel, ' 'followed by all the arguments for the ' 'training script' ) , ) # rest from the training program parser.add_argument('training_script_args' , nargs=_UpperCamelCase ) return parser.parse_args() def _lowerCAmelCase ( ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =parse_args() # Import training_script as a module. _SCREAMING_SNAKE_CASE =Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) _SCREAMING_SNAKE_CASE =script_fpath.stem _SCREAMING_SNAKE_CASE =importlib.import_module(_UpperCamelCase ) # Patch sys.argv _SCREAMING_SNAKE_CASE =[args.training_script] + args.training_script_args + ['--tpu_num_cores', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
47
1
'''simple docstring''' from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def _lowerCAmelCase ( _UpperCamelCase : float , _UpperCamelCase : float , _UpperCamelCase : bool = False ) -> list[float]: """simple docstring""" if radian_mode: return [magnitude * cos(_UpperCamelCase ), magnitude * sin(_UpperCamelCase )] return [magnitude * cos(radians(_UpperCamelCase ) ), magnitude * sin(radians(_UpperCamelCase ) )] def _lowerCAmelCase ( _UpperCamelCase : NDArray[floataa] , _UpperCamelCase : NDArray[floataa] , _UpperCamelCase : float = 10**-1 ) -> bool: """simple docstring""" _SCREAMING_SNAKE_CASE =cross(_UpperCamelCase , _UpperCamelCase ) _SCREAMING_SNAKE_CASE =sum(_UpperCamelCase ) return abs(_UpperCamelCase ) < eps if __name__ == "__main__": # Test to check if it works lowerCamelCase : Optional[Any] = array( [ polar_force(7_1_8.4, 1_8_0 - 3_0), polar_force(8_7_9.5_4, 4_5), polar_force(1_0_0, -9_0), ] ) lowerCamelCase : NDArray[floataa] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg lowerCamelCase : str = array( [ polar_force(3_0 * 9.8_1, 1_5), polar_force(2_1_5, 1_8_0 - 4_5), polar_force(2_6_4, 9_0 - 3_0), ] ) lowerCamelCase : str = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg lowerCamelCase : Optional[int] = array([[0, -2_0_0_0], [0, -1_2_0_0], [0, 1_5_6_0_0], [0, -1_2_4_0_0]]) lowerCamelCase : int = array([[0, 0], [6, 0], [1_0, 0], [1_2, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
47
'''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. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class A__ ( A__ ): A__ = ( 'This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.' 'It takes two arguments named `image` which should be the original image, and `label` which should be a text ' 'describing the elements what should be identified in the segmentation mask. The tool returns the mask.' ) A__ = 'CIDAS/clipseg-rd64-refined' A__ = 'image_segmenter' A__ = CLIPSegForImageSegmentation A__ = ['image', 'text'] A__ = ['image'] def __init__( self : Any , *_a : Dict , **_a : str ) -> Any: '''simple docstring''' requires_backends(self , ['vision'] ) super().__init__(*_a , **_a ) def A ( self : int , _a : "Image" , _a : str ) -> Optional[Any]: '''simple docstring''' return self.pre_processor(text=[label] , images=[image] , padding=_a , return_tensors='pt' ) def A ( self : Dict , _a : Dict ) -> str: '''simple docstring''' with torch.no_grad(): _SCREAMING_SNAKE_CASE =self.model(**_a ).logits return logits def A ( self : Any , _a : str ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =outputs.cpu().detach().numpy() _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =1 return Image.fromarray((array * 255).astype(np.uinta ) )
47
1
'''simple docstring''' from ..utils import DummyObject, requires_backends class A__ ( metaclass=A__ ): A__ = ['torch', 'scipy'] def __init__( self : Optional[Any] , *_a : Any , **_a : Tuple ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ['torch', 'scipy'] ) @classmethod def A ( cls : Any , *_a : Optional[int] , **_a : Tuple ) -> Optional[Any]: '''simple docstring''' requires_backends(cls , ['torch', 'scipy'] ) @classmethod def A ( cls : Any , *_a : Tuple , **_a : List[Any] ) -> Tuple: '''simple docstring''' requires_backends(cls , ['torch', 'scipy'] )
47
'''simple docstring''' from __future__ import annotations import math def _lowerCAmelCase ( _UpperCamelCase : int ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_UpperCamelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowerCAmelCase ( _UpperCamelCase : int ) -> list[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =str(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =[n] for i in range(1 , len(_UpperCamelCase ) ): list_nums.append(int(str_num[i:] ) ) list_nums.append(int(str_num[:-i] ) ) return list_nums def _lowerCAmelCase ( _UpperCamelCase : int ) -> bool: """simple docstring""" if len(str(_UpperCamelCase ) ) > 3: if not is_prime(int(str(_UpperCamelCase )[-3:] ) ) or not is_prime(int(str(_UpperCamelCase )[:3] ) ): return False return True def _lowerCAmelCase ( _UpperCamelCase : int = 11 ) -> list[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =13 while len(_UpperCamelCase ) != count: if validate(_UpperCamelCase ): _SCREAMING_SNAKE_CASE =list_truncated_nums(_UpperCamelCase ) if all(is_prime(_UpperCamelCase ) for i in list_nums ): list_truncated_primes.append(_UpperCamelCase ) num += 2 return list_truncated_primes def _lowerCAmelCase ( ) -> int: """simple docstring""" return sum(compute_truncated_primes(11 ) ) if __name__ == "__main__": print(f'''{sum(compute_truncated_primes(1_1)) = }''')
47
1
'''simple docstring''' from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class A__ ( nn.Module ): def __init__( self : List[Any] , _a : int , _a : int , _a : int , _a : int=0.0 , _a : Optional[int] = None , _a : str = "geglu" , _a : Optional[int] = None , _a : bool = False , _a : bool = False , _a : bool = False , _a : bool = False , _a : bool = True , _a : str = "layer_norm" , _a : bool = False , ) -> List[str]: '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =only_cross_attention _SCREAMING_SNAKE_CASE =(num_embeds_ada_norm is not None) and norm_type == 'ada_norm_zero' _SCREAMING_SNAKE_CASE =(num_embeds_ada_norm is not None) and norm_type == 'ada_norm' if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to" f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}." ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: _SCREAMING_SNAKE_CASE =AdaLayerNorm(_a , _a ) elif self.use_ada_layer_norm_zero: _SCREAMING_SNAKE_CASE =AdaLayerNormZero(_a , _a ) else: _SCREAMING_SNAKE_CASE =nn.LayerNorm(_a , elementwise_affine=_a ) _SCREAMING_SNAKE_CASE =Attention( query_dim=_a , heads=_a , dim_head=_a , dropout=_a , bias=_a , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=_a , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. _SCREAMING_SNAKE_CASE =( AdaLayerNorm(_a , _a ) if self.use_ada_layer_norm else nn.LayerNorm(_a , elementwise_affine=_a ) ) _SCREAMING_SNAKE_CASE =Attention( query_dim=_a , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=_a , dim_head=_a , dropout=_a , bias=_a , upcast_attention=_a , ) # is self-attn if encoder_hidden_states is none else: _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =None # 3. Feed-forward _SCREAMING_SNAKE_CASE =nn.LayerNorm(_a , elementwise_affine=_a ) _SCREAMING_SNAKE_CASE =FeedForward(_a , dropout=_a , activation_fn=_a , final_dropout=_a ) # let chunk size default to None _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =0 def A ( self : Tuple , _a : Optional[int] , _a : int ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =chunk_size _SCREAMING_SNAKE_CASE =dim def A ( self : List[Any] , _a : torch.FloatTensor , _a : Optional[torch.FloatTensor] = None , _a : Optional[torch.FloatTensor] = None , _a : Optional[torch.FloatTensor] = None , _a : Optional[torch.LongTensor] = None , _a : Dict[str, Any] = None , _a : Optional[torch.LongTensor] = None , ) -> Tuple: '''simple docstring''' if self.use_ada_layer_norm: _SCREAMING_SNAKE_CASE =self.norma(_a , _a ) elif self.use_ada_layer_norm_zero: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self.norma( _a , _a , _a , hidden_dtype=hidden_states.dtype ) else: _SCREAMING_SNAKE_CASE =self.norma(_a ) _SCREAMING_SNAKE_CASE =cross_attention_kwargs if cross_attention_kwargs is not None else {} _SCREAMING_SNAKE_CASE =self.attna( _a , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=_a , **_a , ) if self.use_ada_layer_norm_zero: _SCREAMING_SNAKE_CASE =gate_msa.unsqueeze(1 ) * attn_output _SCREAMING_SNAKE_CASE =attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: _SCREAMING_SNAKE_CASE =( self.norma(_a , _a ) if self.use_ada_layer_norm else self.norma(_a ) ) _SCREAMING_SNAKE_CASE =self.attna( _a , encoder_hidden_states=_a , attention_mask=_a , **_a , ) _SCREAMING_SNAKE_CASE =attn_output + hidden_states # 3. Feed-forward _SCREAMING_SNAKE_CASE =self.norma(_a ) if self.use_ada_layer_norm_zero: _SCREAMING_SNAKE_CASE =norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( f"`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`." ) _SCREAMING_SNAKE_CASE =norm_hidden_states.shape[self._chunk_dim] // self._chunk_size _SCREAMING_SNAKE_CASE =torch.cat( [self.ff(_a ) for hid_slice in norm_hidden_states.chunk(_a , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: _SCREAMING_SNAKE_CASE =self.ff(_a ) if self.use_ada_layer_norm_zero: _SCREAMING_SNAKE_CASE =gate_mlp.unsqueeze(1 ) * ff_output _SCREAMING_SNAKE_CASE =ff_output + hidden_states return hidden_states class A__ ( nn.Module ): def __init__( self : List[str] , _a : int , _a : Optional[int] = None , _a : int = 4 , _a : float = 0.0 , _a : str = "geglu" , _a : bool = False , ) -> List[str]: '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =int(dim * mult ) _SCREAMING_SNAKE_CASE =dim_out if dim_out is not None else dim if activation_fn == "gelu": _SCREAMING_SNAKE_CASE =GELU(_a , _a ) if activation_fn == "gelu-approximate": _SCREAMING_SNAKE_CASE =GELU(_a , _a , approximate='tanh' ) elif activation_fn == "geglu": _SCREAMING_SNAKE_CASE =GEGLU(_a , _a ) elif activation_fn == "geglu-approximate": _SCREAMING_SNAKE_CASE =ApproximateGELU(_a , _a ) _SCREAMING_SNAKE_CASE =nn.ModuleList([] ) # project in self.net.append(_a ) # project dropout self.net.append(nn.Dropout(_a ) ) # project out self.net.append(nn.Linear(_a , _a ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(_a ) ) def A ( self : List[Any] , _a : List[str] ) -> Dict: '''simple docstring''' for module in self.net: _SCREAMING_SNAKE_CASE =module(_a ) return hidden_states class A__ ( nn.Module ): def __init__( self : Any , _a : int , _a : int , _a : str = "none" ) -> List[str]: '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =nn.Linear(_a , _a ) _SCREAMING_SNAKE_CASE =approximate def A ( self : List[str] , _a : int ) -> Tuple: '''simple docstring''' if gate.device.type != "mps": return F.gelu(_a , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def A ( self : int , _a : List[str] ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.proj(_a ) _SCREAMING_SNAKE_CASE =self.gelu(_a ) return hidden_states class A__ ( nn.Module ): def __init__( self : Tuple , _a : int , _a : int ) -> int: '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =nn.Linear(_a , dim_out * 2 ) def A ( self : Dict , _a : Tuple ) -> Union[str, Any]: '''simple docstring''' if gate.device.type != "mps": return F.gelu(_a ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def A ( self : str , _a : Dict ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self.proj(_a ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(_a ) class A__ ( nn.Module ): def __init__( self : Any , _a : int , _a : int ) -> List[Any]: '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =nn.Linear(_a , _a ) def A ( self : str , _a : List[str] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.proj(_a ) return x * torch.sigmoid(1.7_02 * x ) class A__ ( nn.Module ): def __init__( self : Dict , _a : int , _a : Tuple ) -> List[Any]: '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =nn.Embedding(_a , _a ) _SCREAMING_SNAKE_CASE =nn.SiLU() _SCREAMING_SNAKE_CASE =nn.Linear(_a , embedding_dim * 2 ) _SCREAMING_SNAKE_CASE =nn.LayerNorm(_a , elementwise_affine=_a ) def A ( self : int , _a : Any , _a : Any ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.linear(self.silu(self.emb(_a ) ) ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =torch.chunk(_a , 2 ) _SCREAMING_SNAKE_CASE =self.norm(_a ) * (1 + scale) + shift return x class A__ ( nn.Module ): def __init__( self : Tuple , _a : Tuple , _a : Dict ) -> Optional[int]: '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =CombinedTimestepLabelEmbeddings(_a , _a ) _SCREAMING_SNAKE_CASE =nn.SiLU() _SCREAMING_SNAKE_CASE =nn.Linear(_a , 6 * embedding_dim , bias=_a ) _SCREAMING_SNAKE_CASE =nn.LayerNorm(_a , elementwise_affine=_a , eps=1e-6 ) def A ( self : Tuple , _a : List[str] , _a : Union[str, Any] , _a : str , _a : Optional[int]=None ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.linear(self.silu(self.emb(_a , _a , hidden_dtype=_a ) ) ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =emb.chunk(6 , dim=1 ) _SCREAMING_SNAKE_CASE =self.norm(_a ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class A__ ( nn.Module ): def __init__( self : Any , _a : int , _a : int , _a : int , _a : Optional[str] = None , _a : float = 1e-5 ) -> List[Any]: '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =num_groups _SCREAMING_SNAKE_CASE =eps if act_fn is None: _SCREAMING_SNAKE_CASE =None else: _SCREAMING_SNAKE_CASE =get_activation(_a ) _SCREAMING_SNAKE_CASE =nn.Linear(_a , out_dim * 2 ) def A ( self : Union[str, Any] , _a : List[Any] , _a : str ) -> Dict: '''simple docstring''' if self.act: _SCREAMING_SNAKE_CASE =self.act(_a ) _SCREAMING_SNAKE_CASE =self.linear(_a ) _SCREAMING_SNAKE_CASE =emb[:, :, None, None] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =emb.chunk(2 , dim=1 ) _SCREAMING_SNAKE_CASE =F.group_norm(_a , self.num_groups , eps=self.eps ) _SCREAMING_SNAKE_CASE =x * (1 + scale) + shift return x
47
'''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: lowerCamelCase : int = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class A__ ( unittest.TestCase ): def __init__( self : List[str] , _a : List[Any] , _a : List[str]=7 , _a : List[str]=3 , _a : Tuple=18 , _a : Tuple=30 , _a : str=400 , _a : Tuple=None , _a : Union[str, Any]=True , _a : List[str]=True , _a : Optional[int]=None , ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =size if size is not None else {'height': 20, 'width': 20} _SCREAMING_SNAKE_CASE =parent _SCREAMING_SNAKE_CASE =batch_size _SCREAMING_SNAKE_CASE =num_channels _SCREAMING_SNAKE_CASE =image_size _SCREAMING_SNAKE_CASE =min_resolution _SCREAMING_SNAKE_CASE =max_resolution _SCREAMING_SNAKE_CASE =size _SCREAMING_SNAKE_CASE =do_normalize _SCREAMING_SNAKE_CASE =do_convert_rgb _SCREAMING_SNAKE_CASE =[512, 1024, 2048, 4096] _SCREAMING_SNAKE_CASE =patch_size if patch_size is not None else {'height': 16, 'width': 16} def A ( self : Any ) -> List[str]: '''simple docstring''' return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def A ( self : int ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE ='https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg' _SCREAMING_SNAKE_CASE =Image.open(requests.get(_a , stream=_a ).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 A__ ( A__ , unittest.TestCase ): A__ = PixaStructImageProcessor if is_vision_available() else None def A ( self : Dict ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =PixaStructImageProcessingTester(self ) @property def A ( self : Optional[Any] ) -> int: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def A ( self : Any ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_a , 'do_normalize' ) ) self.assertTrue(hasattr(_a , 'do_convert_rgb' ) ) def A ( self : Any ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processor_tester.prepare_dummy_image() _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) _SCREAMING_SNAKE_CASE =2048 _SCREAMING_SNAKE_CASE =image_processor(_a , return_tensors='pt' , max_patches=_a ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.06_06 ) , atol=1e-3 , rtol=1e-3 ) ) def A ( self : Any ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PIL images _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input _SCREAMING_SNAKE_CASE =( (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 _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def A ( self : List[str] ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PIL images _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input _SCREAMING_SNAKE_CASE =( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 _SCREAMING_SNAKE_CASE =True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(_a ): _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches _SCREAMING_SNAKE_CASE ='Hello' _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a , header_text=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a , header_text=_a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def A ( self : List[Any] ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , numpify=_a ) for image in image_inputs: self.assertIsInstance(_a , np.ndarray ) _SCREAMING_SNAKE_CASE =( (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 _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def A ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , torchify=_a ) for image in image_inputs: self.assertIsInstance(_a , torch.Tensor ) # Test not batched input _SCREAMING_SNAKE_CASE =( (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 _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a ).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 A__ ( A__ , unittest.TestCase ): A__ = PixaStructImageProcessor if is_vision_available() else None def A ( self : str ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =PixaStructImageProcessingTester(self , num_channels=4 ) _SCREAMING_SNAKE_CASE =3 @property def A ( self : List[str] ) -> Optional[Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def A ( self : List[str] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_a , 'do_normalize' ) ) self.assertTrue(hasattr(_a , 'do_convert_rgb' ) ) def A ( self : Dict ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PIL images _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input _SCREAMING_SNAKE_CASE =( (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 _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
47
1
'''simple docstring''' import inspect import unittest from transformers import RegNetConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import RegNetForImageClassification, RegNetModel from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class A__ : def __init__( self : int , _a : Optional[int] , _a : Any=3 , _a : Optional[Any]=32 , _a : Union[str, Any]=3 , _a : Dict=10 , _a : Optional[Any]=[10, 20, 30, 40] , _a : List[Any]=[1, 1, 2, 1] , _a : Union[str, Any]=True , _a : Dict=True , _a : Any="relu" , _a : int=3 , _a : Optional[int]=None , ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =parent _SCREAMING_SNAKE_CASE =batch_size _SCREAMING_SNAKE_CASE =image_size _SCREAMING_SNAKE_CASE =num_channels _SCREAMING_SNAKE_CASE =embeddings_size _SCREAMING_SNAKE_CASE =hidden_sizes _SCREAMING_SNAKE_CASE =depths _SCREAMING_SNAKE_CASE =is_training _SCREAMING_SNAKE_CASE =use_labels _SCREAMING_SNAKE_CASE =hidden_act _SCREAMING_SNAKE_CASE =num_labels _SCREAMING_SNAKE_CASE =scope _SCREAMING_SNAKE_CASE =len(_a ) def A ( self : Any ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _SCREAMING_SNAKE_CASE =None if self.use_labels: _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] , self.num_labels ) _SCREAMING_SNAKE_CASE =self.get_config() return config, pixel_values, labels def A ( self : List[str] ) -> Optional[int]: '''simple docstring''' return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def A ( self : Optional[Any] , _a : str , _a : List[str] , _a : List[str] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =RegNetModel(config=_a ) model.to(_a ) model.eval() _SCREAMING_SNAKE_CASE =model(_a ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def A ( self : int , _a : List[Any] , _a : Any , _a : Optional[Any] ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.num_labels _SCREAMING_SNAKE_CASE =RegNetForImageClassification(_a ) model.to(_a ) model.eval() _SCREAMING_SNAKE_CASE =model(_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def A ( self : Optional[Any] ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =config_and_inputs _SCREAMING_SNAKE_CASE ={'pixel_values': pixel_values} return config, inputs_dict @require_torch class A__ ( A__ , A__ , unittest.TestCase ): A__ = (RegNetModel, RegNetForImageClassification) if is_torch_available() else () A__ = ( {'feature-extraction': RegNetModel, 'image-classification': RegNetForImageClassification} if is_torch_available() else {} ) A__ = False A__ = False A__ = False A__ = False def A ( self : Dict ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =RegNetModelTester(self ) _SCREAMING_SNAKE_CASE =ConfigTester(self , config_class=_a , has_text_modality=_a ) def A ( self : int ) -> Optional[int]: '''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 A ( self : Tuple ) -> Tuple: '''simple docstring''' return @unittest.skip(reason='RegNet does not use inputs_embeds' ) def A ( self : Tuple ) -> List[str]: '''simple docstring''' pass @unittest.skip(reason='RegNet does not support input and output embeddings' ) def A ( self : List[Any] ) -> List[str]: '''simple docstring''' pass def A ( self : Tuple ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE =model_class(_a ) _SCREAMING_SNAKE_CASE =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _SCREAMING_SNAKE_CASE =[*signature.parameters.keys()] _SCREAMING_SNAKE_CASE =['pixel_values'] self.assertListEqual(arg_names[:1] , _a ) def A ( self : str ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def A ( self : Union[str, Any] ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE =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 A ( self : int ) -> List[Any]: '''simple docstring''' def check_hidden_states_output(_a : Optional[int] , _a : int , _a : Dict ): _SCREAMING_SNAKE_CASE =model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): _SCREAMING_SNAKE_CASE =model(**self._prepare_for_class(_a , _a ) ) _SCREAMING_SNAKE_CASE =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _SCREAMING_SNAKE_CASE =self.model_tester.num_stages self.assertEqual(len(_a ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE =['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: _SCREAMING_SNAKE_CASE =layer_type _SCREAMING_SNAKE_CASE =True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _SCREAMING_SNAKE_CASE =True check_hidden_states_output(_a , _a , _a ) def A ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) @slow def A ( self : List[str] ) -> Dict: '''simple docstring''' for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _SCREAMING_SNAKE_CASE =RegNetModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def _lowerCAmelCase ( ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class A__ ( unittest.TestCase ): @cached_property def A ( self : Optional[Any] ) -> int: '''simple docstring''' return ( AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def A ( self : Any ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(_a ) _SCREAMING_SNAKE_CASE =self.default_image_processor _SCREAMING_SNAKE_CASE =prepare_img() _SCREAMING_SNAKE_CASE =image_processor(images=_a , return_tensors='pt' ).to(_a ) # forward pass with torch.no_grad(): _SCREAMING_SNAKE_CASE =model(**_a ) # verify the logits _SCREAMING_SNAKE_CASE =torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _a ) _SCREAMING_SNAKE_CASE =torch.tensor([-0.41_80, -1.50_51, -3.48_36] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1e-4 ) )
47
'''simple docstring''' import copy import re class A__ : A__ = 'hp' A__ = {} A__ = None @classmethod def A ( cls : Optional[Any] , _a : Optional[Any] , _a : Any ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =prefix _SCREAMING_SNAKE_CASE =defaults cls.build_naming_info() @staticmethod def A ( _a : Optional[Any] , _a : List[Any] ) -> Any: '''simple docstring''' if len(_a ) == 0: return "" _SCREAMING_SNAKE_CASE =None if any(char.isdigit() for char in word ): raise Exception(f"Parameters should not contain numbers: '{word}' contains a number" ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(_a ) + 1 ): _SCREAMING_SNAKE_CASE =word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: _SCREAMING_SNAKE_CASE =prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(_a : str ): _SCREAMING_SNAKE_CASE ='' while integer != 0: _SCREAMING_SNAKE_CASE =chr(ord('A' ) + integer % 10 ) + s integer //= 10 return s _SCREAMING_SNAKE_CASE =0 while True: _SCREAMING_SNAKE_CASE =word + '#' + int_to_alphabetic(_a ) if sword in info["reverse_short_word"]: continue else: _SCREAMING_SNAKE_CASE =sword break _SCREAMING_SNAKE_CASE =short_word _SCREAMING_SNAKE_CASE =word return short_word @staticmethod def A ( _a : Optional[Any] , _a : int ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =param_name.split('_' ) _SCREAMING_SNAKE_CASE =[TrialShortNamer.shortname_for_word(_a , _a ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name _SCREAMING_SNAKE_CASE =['', '_'] for separator in separators: _SCREAMING_SNAKE_CASE =separator.join(_a ) if shortname not in info["reverse_short_param"]: _SCREAMING_SNAKE_CASE =shortname _SCREAMING_SNAKE_CASE =param_name return shortname return param_name @staticmethod def A ( _a : Dict , _a : int ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =TrialShortNamer.shortname_for_key(_a , _a ) _SCREAMING_SNAKE_CASE =short_name _SCREAMING_SNAKE_CASE =param_name @classmethod def A ( cls : Optional[int] ) -> Tuple: '''simple docstring''' if cls.NAMING_INFO is not None: return _SCREAMING_SNAKE_CASE ={ 'short_word': {}, 'reverse_short_word': {}, 'short_param': {}, 'reverse_short_param': {}, } _SCREAMING_SNAKE_CASE =list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(_a , _a ) _SCREAMING_SNAKE_CASE =info @classmethod def A ( cls : List[Any] , _a : int ) -> int: '''simple docstring''' cls.build_naming_info() assert cls.PREFIX is not None _SCREAMING_SNAKE_CASE =[copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(f"You should provide a default value for the param name {k} with value {v}" ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue _SCREAMING_SNAKE_CASE =cls.NAMING_INFO['short_param'][k] if isinstance(_a , _a ): _SCREAMING_SNAKE_CASE =1 if v else 0 _SCREAMING_SNAKE_CASE ='' if isinstance(_a , (int, float) ) else '-' _SCREAMING_SNAKE_CASE =f"{key}{sep}{v}" name.append(_a ) return "_".join(_a ) @classmethod def A ( cls : Optional[Any] , _a : List[Any] ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =repr[len(cls.PREFIX ) + 1 :] if repr == "": _SCREAMING_SNAKE_CASE =[] else: _SCREAMING_SNAKE_CASE =repr.split('_' ) _SCREAMING_SNAKE_CASE ={} for value in values: if "-" in value: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =value.split('-' ) else: _SCREAMING_SNAKE_CASE =re.sub('[0-9.]' , '' , _a ) _SCREAMING_SNAKE_CASE =float(re.sub('[^0-9.]' , '' , _a ) ) _SCREAMING_SNAKE_CASE =cls.NAMING_INFO['reverse_short_param'][p_k] _SCREAMING_SNAKE_CASE =p_v for k in cls.DEFAULTS: if k not in parameters: _SCREAMING_SNAKE_CASE =cls.DEFAULTS[k] return parameters
47
1
'''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_video_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import VivitImageProcessor class A__ ( unittest.TestCase ): def __init__( self : List[str] , _a : List[Any] , _a : List[str]=7 , _a : Optional[int]=3 , _a : Tuple=10 , _a : Optional[Any]=18 , _a : int=30 , _a : Optional[int]=400 , _a : Dict=True , _a : Union[str, Any]=None , _a : List[Any]=True , _a : str=[0.5, 0.5, 0.5] , _a : List[Any]=[0.5, 0.5, 0.5] , _a : str=None , ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =size if size is not None else {'shortest_edge': 18} _SCREAMING_SNAKE_CASE =crop_size if crop_size is not None else {'height': 18, 'width': 18} _SCREAMING_SNAKE_CASE =parent _SCREAMING_SNAKE_CASE =batch_size _SCREAMING_SNAKE_CASE =num_channels _SCREAMING_SNAKE_CASE =num_frames _SCREAMING_SNAKE_CASE =image_size _SCREAMING_SNAKE_CASE =min_resolution _SCREAMING_SNAKE_CASE =max_resolution _SCREAMING_SNAKE_CASE =do_resize _SCREAMING_SNAKE_CASE =size _SCREAMING_SNAKE_CASE =do_normalize _SCREAMING_SNAKE_CASE =image_mean _SCREAMING_SNAKE_CASE =image_std _SCREAMING_SNAKE_CASE =crop_size def A ( self : int ) -> Dict: '''simple docstring''' return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "crop_size": self.crop_size, } @require_torch @require_vision class A__ ( A__ , unittest.TestCase ): A__ = VivitImageProcessor if is_vision_available() else None def A ( self : int ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =VivitImageProcessingTester(self ) @property def A ( self : List[Any] ) -> List[Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def A ( self : List[Any] ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_a , 'image_mean' ) ) self.assertTrue(hasattr(_a , 'image_std' ) ) self.assertTrue(hasattr(_a , 'do_normalize' ) ) self.assertTrue(hasattr(_a , 'do_resize' ) ) self.assertTrue(hasattr(_a , 'do_center_crop' ) ) self.assertTrue(hasattr(_a , 'size' ) ) def A ( self : str ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =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} ) _SCREAMING_SNAKE_CASE =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 A ( self : Any ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PIL videos _SCREAMING_SNAKE_CASE =prepare_video_inputs(self.image_processor_tester , equal_resolution=_a ) for video in video_inputs: self.assertIsInstance(_a , _a ) self.assertIsInstance(video[0] , Image.Image ) # Test not batched input _SCREAMING_SNAKE_CASE =image_processing(video_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processing(_a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def A ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _SCREAMING_SNAKE_CASE =prepare_video_inputs(self.image_processor_tester , equal_resolution=_a , numpify=_a ) for video in video_inputs: self.assertIsInstance(_a , _a ) self.assertIsInstance(video[0] , np.ndarray ) # Test not batched input _SCREAMING_SNAKE_CASE =image_processing(video_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processing(_a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def A ( self : Optional[int] ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _SCREAMING_SNAKE_CASE =prepare_video_inputs(self.image_processor_tester , equal_resolution=_a , torchify=_a ) for video in video_inputs: self.assertIsInstance(_a , _a ) self.assertIsInstance(video[0] , torch.Tensor ) # Test not batched input _SCREAMING_SNAKE_CASE =image_processing(video_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processing(_a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
47
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version lowerCamelCase : Optional[int] = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt") @dataclass class A__ : A__ = field( default='cifar10' , metadata={'help': 'Name of a dataset from the datasets package'} ) A__ = field( default=A__ , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) A__ = field( default=A__ , metadata={'help': 'The column name of the images in the files.'} ) A__ = field(default=A__ , metadata={'help': 'A folder containing the training data.'} ) A__ = field(default=A__ , metadata={'help': 'A folder containing the validation data.'} ) A__ = field( default=0.15 , metadata={'help': 'Percent to split off of train for validation.'} ) A__ = field( default=A__ , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) A__ = field( default=A__ , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of evaluation examples to this ' 'value if set.' ) } , ) def A ( self : Union[str, Any] ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE ={} if self.train_dir is not None: _SCREAMING_SNAKE_CASE =self.train_dir if self.validation_dir is not None: _SCREAMING_SNAKE_CASE =self.validation_dir _SCREAMING_SNAKE_CASE =data_files if data_files else None @dataclass class A__ : A__ = field( default=A__ , metadata={ 'help': ( 'The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.' ) } , ) A__ = field( default=A__ , metadata={'help': 'Pretrained config name or path if not the same as model_name_or_path'} ) A__ = field( default=A__ , metadata={ 'help': ( 'Override some existing default config settings when a model is trained from scratch. Example: ' 'n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index' ) } , ) A__ = field( default=A__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from s3'} ) A__ = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) A__ = field(default=A__ , metadata={'help': 'Name or path of preprocessor config.'} ) A__ = field( default=A__ , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) A__ = field( default=0.75 , metadata={'help': 'The ratio of the number of masked tokens in the input sequence.'} ) A__ = field( default=A__ , metadata={'help': 'Whether or not to train with normalized pixel values as target.'} ) @dataclass class A__ ( A__ ): A__ = field( default=1E-3 , metadata={'help': 'Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'} ) def _lowerCAmelCase ( _UpperCamelCase : int ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE =torch.stack([example['pixel_values'] for example in examples] ) return {"pixel_values": pixel_values} def _lowerCAmelCase ( ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE =HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) 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. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('run_mae' , _UpperCamelCase , _UpperCamelCase ) # 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 )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _SCREAMING_SNAKE_CASE =training_args.get_process_log_level() logger.setLevel(_UpperCamelCase ) transformers.utils.logging.set_verbosity(_UpperCamelCase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # 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}" ) logger.info(f"Training/evaluation parameters {training_args}" ) # Detecting last checkpoint. _SCREAMING_SNAKE_CASE =None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _SCREAMING_SNAKE_CASE =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 and training_args.resume_from_checkpoint is 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.' ) # Initialize our dataset. _SCREAMING_SNAKE_CASE =load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. _SCREAMING_SNAKE_CASE =None if 'validation' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , _UpperCamelCase ) and data_args.train_val_split > 0.0: _SCREAMING_SNAKE_CASE =ds['train'].train_test_split(data_args.train_val_split ) _SCREAMING_SNAKE_CASE =split['train'] _SCREAMING_SNAKE_CASE =split['test'] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _SCREAMING_SNAKE_CASE ={ 'cache_dir': model_args.cache_dir, 'revision': model_args.model_revision, 'use_auth_token': True if model_args.use_auth_token else None, } if model_args.config_name: _SCREAMING_SNAKE_CASE =ViTMAEConfig.from_pretrained(model_args.config_name , **_UpperCamelCase ) elif model_args.model_name_or_path: _SCREAMING_SNAKE_CASE =ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **_UpperCamelCase ) else: _SCREAMING_SNAKE_CASE =ViTMAEConfig() logger.warning('You are instantiating a new config instance from scratch.' ) if model_args.config_overrides is not None: logger.info(f"Overriding config: {model_args.config_overrides}" ) config.update_from_string(model_args.config_overrides ) logger.info(f"New config: {config}" ) # adapt config config.update( { 'mask_ratio': model_args.mask_ratio, 'norm_pix_loss': model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: _SCREAMING_SNAKE_CASE =ViTImageProcessor.from_pretrained(model_args.image_processor_name , **_UpperCamelCase ) elif model_args.model_name_or_path: _SCREAMING_SNAKE_CASE =ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **_UpperCamelCase ) else: _SCREAMING_SNAKE_CASE =ViTImageProcessor() # create model if model_args.model_name_or_path: _SCREAMING_SNAKE_CASE =ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=_UpperCamelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('Training new model from scratch' ) _SCREAMING_SNAKE_CASE =ViTMAEForPreTraining(_UpperCamelCase ) if training_args.do_train: _SCREAMING_SNAKE_CASE =ds['train'].column_names else: _SCREAMING_SNAKE_CASE =ds['validation'].column_names if data_args.image_column_name is not None: _SCREAMING_SNAKE_CASE =data_args.image_column_name elif "image" in column_names: _SCREAMING_SNAKE_CASE ='image' elif "img" in column_names: _SCREAMING_SNAKE_CASE ='img' else: _SCREAMING_SNAKE_CASE =column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: _SCREAMING_SNAKE_CASE =image_processor.size['shortest_edge'] else: _SCREAMING_SNAKE_CASE =(image_processor.size['height'], image_processor.size['width']) _SCREAMING_SNAKE_CASE =Compose( [ Lambda(lambda _UpperCamelCase : img.convert('RGB' ) if img.mode != "RGB" else img ), RandomResizedCrop(_UpperCamelCase , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(_UpperCamelCase : Dict ): _SCREAMING_SNAKE_CASE =[transforms(_UpperCamelCase ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError('--do_train requires a train dataset' ) if data_args.max_train_samples is not None: _SCREAMING_SNAKE_CASE =ds['train'].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(_UpperCamelCase ) if training_args.do_eval: if "validation" not in ds: raise ValueError('--do_eval requires a validation dataset' ) if data_args.max_eval_samples is not None: _SCREAMING_SNAKE_CASE =( ds['validation'].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(_UpperCamelCase ) # Compute absolute learning rate _SCREAMING_SNAKE_CASE =( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: _SCREAMING_SNAKE_CASE =training_args.base_learning_rate * total_train_batch_size / 2_56 # Initialize our trainer _SCREAMING_SNAKE_CASE =Trainer( model=_UpperCamelCase , args=_UpperCamelCase , train_dataset=ds['train'] if training_args.do_train else None , eval_dataset=ds['validation'] if training_args.do_eval else None , tokenizer=_UpperCamelCase , data_collator=_UpperCamelCase , ) # Training if training_args.do_train: _SCREAMING_SNAKE_CASE =None if training_args.resume_from_checkpoint is not None: _SCREAMING_SNAKE_CASE =training_args.resume_from_checkpoint elif last_checkpoint is not None: _SCREAMING_SNAKE_CASE =last_checkpoint _SCREAMING_SNAKE_CASE =trainer.train(resume_from_checkpoint=_UpperCamelCase ) trainer.save_model() trainer.log_metrics('train' , train_result.metrics ) trainer.save_metrics('train' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _SCREAMING_SNAKE_CASE =trainer.evaluate() trainer.log_metrics('eval' , _UpperCamelCase ) trainer.save_metrics('eval' , _UpperCamelCase ) # Write model card and (optionally) push to hub _SCREAMING_SNAKE_CASE ={ 'tasks': 'masked-auto-encoding', 'dataset': data_args.dataset_name, 'tags': ['masked-auto-encoding'], } if training_args.push_to_hub: trainer.push_to_hub(**_UpperCamelCase ) else: trainer.create_model_card(**_UpperCamelCase ) def _lowerCAmelCase ( _UpperCamelCase : List[str] ) -> Optional[int]: """simple docstring""" main() if __name__ == "__main__": main()
47
1
'''simple docstring''' from pathlib import Path import fire from tqdm import tqdm def _lowerCAmelCase ( _UpperCamelCase : Optional[int]="ro" , _UpperCamelCase : Optional[Any]="en" , _UpperCamelCase : List[str]="wmt16" , _UpperCamelCase : Union[str, Any]=None ) -> None: """simple docstring""" try: import datasets except (ModuleNotFoundError, ImportError): raise ImportError('run pip install datasets' ) _SCREAMING_SNAKE_CASE =f"{src_lang}-{tgt_lang}" print(f"Converting {dataset}-{pair}" ) _SCREAMING_SNAKE_CASE =datasets.load_dataset(_UpperCamelCase , _UpperCamelCase ) if save_dir is None: _SCREAMING_SNAKE_CASE =f"{dataset}-{pair}" _SCREAMING_SNAKE_CASE =Path(_UpperCamelCase ) save_dir.mkdir(exist_ok=_UpperCamelCase ) for split in ds.keys(): print(f"Splitting {split} with {ds[split].num_rows} records" ) # to save to val.source, val.target like summary datasets _SCREAMING_SNAKE_CASE ='val' if split == 'validation' else split _SCREAMING_SNAKE_CASE =save_dir.joinpath(f"{fn}.source" ) _SCREAMING_SNAKE_CASE =save_dir.joinpath(f"{fn}.target" ) _SCREAMING_SNAKE_CASE =src_path.open('w+' ) _SCREAMING_SNAKE_CASE =tgt_path.open('w+' ) # reader is the bottleneck so writing one record at a time doesn't slow things down for x in tqdm(ds[split] ): _SCREAMING_SNAKE_CASE =x['translation'] src_fp.write(ex[src_lang] + '\n' ) tgt_fp.write(ex[tgt_lang] + '\n' ) print(f"Saved {dataset} dataset to {save_dir}" ) if __name__ == "__main__": fire.Fire(download_wmt_dataset)
47
'''simple docstring''' from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class A__ ( A__ , A__ ): @register_to_config def __init__( self : Dict , _a : int = 768 , ) -> Union[str, Any]: '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =nn.Parameter(torch.zeros(1 , _a ) ) _SCREAMING_SNAKE_CASE =nn.Parameter(torch.ones(1 , _a ) ) def A ( self : Tuple , _a : Optional[Union[str, torch.device]] = None , _a : Optional[torch.dtype] = None , ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =nn.Parameter(self.mean.to(_a ).to(_a ) ) _SCREAMING_SNAKE_CASE =nn.Parameter(self.std.to(_a ).to(_a ) ) return self def A ( self : Tuple , _a : str ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =(embeds - self.mean) * 1.0 / self.std return embeds def A ( self : List[str] , _a : Optional[Any] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =(embeds * self.std) + self.mean return embeds
47
1
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : Any = logging.get_logger(__name__) lowerCamelCase : Optional[Any] = { "google/pix2struct-textcaps-base": ( "https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json" ), } class A__ ( A__ ): A__ = 'pix2struct_text_model' A__ = ['past_key_values'] A__ = { 'hidden_size': 'hidden_size', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self : Union[str, Any] , _a : Optional[int]=5_0244 , _a : Tuple=768 , _a : Tuple=64 , _a : List[Any]=2048 , _a : Tuple=12 , _a : int=12 , _a : List[str]=32 , _a : List[str]=128 , _a : List[str]=0.1 , _a : Dict=1e-6 , _a : int=1.0 , _a : Optional[int]="gelu_new" , _a : Dict=0 , _a : List[str]=False , _a : List[Any]=0 , _a : Optional[Any]=1 , _a : int=False , _a : Optional[int]=True , **_a : int , ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =vocab_size _SCREAMING_SNAKE_CASE =hidden_size _SCREAMING_SNAKE_CASE =d_kv _SCREAMING_SNAKE_CASE =d_ff _SCREAMING_SNAKE_CASE =num_layers _SCREAMING_SNAKE_CASE =num_heads _SCREAMING_SNAKE_CASE =relative_attention_num_buckets _SCREAMING_SNAKE_CASE =relative_attention_max_distance _SCREAMING_SNAKE_CASE =dropout_rate _SCREAMING_SNAKE_CASE =layer_norm_epsilon _SCREAMING_SNAKE_CASE =initializer_factor _SCREAMING_SNAKE_CASE =use_cache _SCREAMING_SNAKE_CASE =eos_token_id _SCREAMING_SNAKE_CASE =decoder_start_token_id # for backwards compatibility _SCREAMING_SNAKE_CASE =dense_act_fn super().__init__( pad_token_id=_a , eos_token_id=_a , decoder_start_token_id=_a , tie_word_embeddings=_a , is_decoder=_a , **_a , ) @classmethod def A ( cls : List[str] , _a : Union[str, os.PathLike] , **_a : Tuple ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(_a ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =cls.get_config_dict(_a , **_a ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('model_type' ) == "pix2struct": _SCREAMING_SNAKE_CASE =config_dict['text_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " f"{cls.model_type}. This is not supported for all configurations of models and can yield errors." ) return cls.from_dict(_a , **_a ) class A__ ( A__ ): A__ = 'pix2struct_vision_model' def __init__( self : Dict , _a : List[str]=768 , _a : List[str]=768 , _a : Tuple=2048 , _a : Any=64 , _a : List[str]=12 , _a : List[str]=12 , _a : str="gelu_new" , _a : List[str]=1e-6 , _a : int=0.0 , _a : Union[str, Any]=0.0 , _a : Optional[int]=1e-10 , _a : str=1.0 , _a : Optional[int]=4096 , _a : str=32 , _a : Tuple=128 , **_a : Optional[int] , ) -> Union[str, Any]: '''simple docstring''' super().__init__(**_a ) _SCREAMING_SNAKE_CASE =hidden_size _SCREAMING_SNAKE_CASE =patch_embed_hidden_size _SCREAMING_SNAKE_CASE =d_ff _SCREAMING_SNAKE_CASE =dropout_rate _SCREAMING_SNAKE_CASE =num_hidden_layers _SCREAMING_SNAKE_CASE =num_attention_heads _SCREAMING_SNAKE_CASE =initializer_range _SCREAMING_SNAKE_CASE =initializer_factor _SCREAMING_SNAKE_CASE =attention_dropout _SCREAMING_SNAKE_CASE =layer_norm_eps _SCREAMING_SNAKE_CASE =dense_act_fn _SCREAMING_SNAKE_CASE =seq_len _SCREAMING_SNAKE_CASE =relative_attention_num_buckets _SCREAMING_SNAKE_CASE =relative_attention_max_distance _SCREAMING_SNAKE_CASE =d_kv @classmethod def A ( cls : List[Any] , _a : Union[str, os.PathLike] , **_a : Dict ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(_a ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =cls.get_config_dict(_a , **_a ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('model_type' ) == "pix2struct": _SCREAMING_SNAKE_CASE =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(_a , **_a ) class A__ ( A__ ): A__ = 'pix2struct' A__ = True def __init__( self : Optional[int] , _a : Any=None , _a : Union[str, Any]=None , _a : Optional[int]=1.0 , _a : Optional[int]=0.02 , _a : int=False , _a : Dict=False , _a : List[Any]=True , **_a : str , ) -> Optional[int]: '''simple docstring''' super().__init__(tie_word_embeddings=_a , is_encoder_decoder=_a , **_a ) if text_config is None: _SCREAMING_SNAKE_CASE ={} logger.info('text_config is None. Initializing the Pix2StructTextConfig with default values.' ) if vision_config is None: _SCREAMING_SNAKE_CASE ={} logger.info('vision_config is None. Initializing the Pix2StructVisionConfig with default values.' ) _SCREAMING_SNAKE_CASE =PixaStructTextConfig(**_a ) _SCREAMING_SNAKE_CASE =PixaStructVisionConfig(**_a ) _SCREAMING_SNAKE_CASE =self.text_config.decoder_start_token_id _SCREAMING_SNAKE_CASE =self.text_config.pad_token_id _SCREAMING_SNAKE_CASE =self.text_config.eos_token_id _SCREAMING_SNAKE_CASE =initializer_factor _SCREAMING_SNAKE_CASE =initializer_range _SCREAMING_SNAKE_CASE =self.initializer_range _SCREAMING_SNAKE_CASE =self.initializer_range _SCREAMING_SNAKE_CASE =is_vqa @classmethod def A ( cls : Union[str, Any] , _a : PixaStructTextConfig , _a : PixaStructVisionConfig , **_a : Optional[Any] ) -> List[str]: '''simple docstring''' return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **_a ) def A ( self : List[str] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =copy.deepcopy(self.__dict__ ) _SCREAMING_SNAKE_CASE =self.text_config.to_dict() _SCREAMING_SNAKE_CASE =self.vision_config.to_dict() _SCREAMING_SNAKE_CASE =self.__class__.model_type return output
47
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def _lowerCAmelCase ( _UpperCamelCase : Optional[int] ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =botoa.client('iam' ) _SCREAMING_SNAKE_CASE ={ 'Version': '2012-10-17', 'Statement': [ {'Effect': 'Allow', 'Principal': {'Service': 'sagemaker.amazonaws.com'}, 'Action': 'sts:AssumeRole'} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=_UpperCamelCase , AssumeRolePolicyDocument=json.dumps(_UpperCamelCase , indent=2 ) ) _SCREAMING_SNAKE_CASE ={ 'Version': '2012-10-17', 'Statement': [ { 'Effect': 'Allow', 'Action': [ 'sagemaker:*', 'ecr:GetDownloadUrlForLayer', 'ecr:BatchGetImage', 'ecr:BatchCheckLayerAvailability', 'ecr:GetAuthorizationToken', 'cloudwatch:PutMetricData', 'cloudwatch:GetMetricData', 'cloudwatch:GetMetricStatistics', 'cloudwatch:ListMetrics', 'logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:DescribeLogStreams', 'logs:PutLogEvents', 'logs:GetLogEvents', 's3:CreateBucket', 's3:ListBucket', 's3:GetBucketLocation', 's3:GetObject', 's3:PutObject', ], 'Resource': '*', } ], } # attach policy to role iam_client.put_role_policy( RoleName=_UpperCamelCase , PolicyName=f"{role_name}_policy_permission" , PolicyDocument=json.dumps(_UpperCamelCase , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(f"role {role_name} already exists. Using existing one" ) def _lowerCAmelCase ( _UpperCamelCase : List[str] ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =botoa.client('iam' ) return iam_client.get_role(RoleName=_UpperCamelCase )["Role"]["Arn"] def _lowerCAmelCase ( ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =_ask_options( 'How do you want to authorize?' , ['AWS Profile', 'Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) '] , _UpperCamelCase , ) _SCREAMING_SNAKE_CASE =None if credentials_configuration == 0: _SCREAMING_SNAKE_CASE =_ask_field('Enter your AWS Profile name: [default] ' , default='default' ) _SCREAMING_SNAKE_CASE =aws_profile else: print( 'Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,' '`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`' ) _SCREAMING_SNAKE_CASE =_ask_field('AWS Access Key ID: ' ) _SCREAMING_SNAKE_CASE =aws_access_key_id _SCREAMING_SNAKE_CASE =_ask_field('AWS Secret Access Key: ' ) _SCREAMING_SNAKE_CASE =aws_secret_access_key _SCREAMING_SNAKE_CASE =_ask_field('Enter your AWS Region: [us-east-1]' , default='us-east-1' ) _SCREAMING_SNAKE_CASE =aws_region _SCREAMING_SNAKE_CASE =_ask_options( 'Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?' , ['Provide IAM Role name', 'Create new IAM role using credentials'] , _UpperCamelCase , ) if role_management == 0: _SCREAMING_SNAKE_CASE =_ask_field('Enter your IAM role name: ' ) else: _SCREAMING_SNAKE_CASE ='accelerate_sagemaker_execution_role' print(f"Accelerate will create an iam role \"{iam_role_name}\" using the provided credentials" ) _create_iam_role_for_sagemaker(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to use custom Docker image? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE =None if is_custom_docker_image: _SCREAMING_SNAKE_CASE =_ask_field('Enter your Docker image: ' , lambda _UpperCamelCase : str(_UpperCamelCase ).lower() ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to provide SageMaker input channels with data locations? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE =None if is_sagemaker_inputs_enabled: _SCREAMING_SNAKE_CASE =_ask_field( 'Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): ' , lambda _UpperCamelCase : str(_UpperCamelCase ).lower() , ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to enable SageMaker metrics? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE =None if is_sagemaker_metrics_enabled: _SCREAMING_SNAKE_CASE =_ask_field( 'Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): ' , lambda _UpperCamelCase : str(_UpperCamelCase ).lower() , ) _SCREAMING_SNAKE_CASE =_ask_options( 'What is the distributed mode?' , ['No distributed training', 'Data parallelism'] , _convert_sagemaker_distributed_mode , ) _SCREAMING_SNAKE_CASE ={} _SCREAMING_SNAKE_CASE =_ask_field( 'Do you wish to optimize your script with torch dynamo?[yes/NO]:' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) if use_dynamo: _SCREAMING_SNAKE_CASE ='dynamo_' _SCREAMING_SNAKE_CASE =_ask_options( 'Which dynamo backend would you like to use?' , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to customize the defaults sent to torch.compile? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) if use_custom_options: _SCREAMING_SNAKE_CASE =_ask_options( 'Which mode do you want to use?' , _UpperCamelCase , lambda _UpperCamelCase : TORCH_DYNAMO_MODES[int(_UpperCamelCase )] , default='default' , ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to enable dynamic shape tracing? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE ='Which EC2 instance type you want to use for your training?' if distributed_type != SageMakerDistributedType.NO: _SCREAMING_SNAKE_CASE =_ask_options( _UpperCamelCase , _UpperCamelCase , lambda _UpperCamelCase : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(_UpperCamelCase )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" _SCREAMING_SNAKE_CASE =_ask_field(_UpperCamelCase , lambda _UpperCamelCase : str(_UpperCamelCase ).lower() , default='ml.p3.2xlarge' ) _SCREAMING_SNAKE_CASE =1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): _SCREAMING_SNAKE_CASE =_ask_field( 'How many machines do you want use? [1]: ' , _UpperCamelCase , default=1 , ) _SCREAMING_SNAKE_CASE =_ask_options( 'Do you wish to use FP16 or BF16 (mixed precision)?' , ['no', 'fp16', 'bf16', 'fp8'] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( 'Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.' ) return SageMakerConfig( image_uri=_UpperCamelCase , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=_UpperCamelCase , use_cpu=_UpperCamelCase , dynamo_config=_UpperCamelCase , eca_instance_type=_UpperCamelCase , profile=_UpperCamelCase , region=_UpperCamelCase , iam_role_name=_UpperCamelCase , mixed_precision=_UpperCamelCase , num_machines=_UpperCamelCase , sagemaker_inputs_file=_UpperCamelCase , sagemaker_metrics_file=_UpperCamelCase , )
47
1
'''simple docstring''' import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCamelCase : str = logging.get_logger(__name__) lowerCamelCase : List[Any] = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} # See all BART models at https://huggingface.co/models?filter=bart lowerCamelCase : Union[str, Any] = { "vocab_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json", }, "merges_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt", }, } lowerCamelCase : List[Any] = { "facebook/bart-base": 1_0_2_4, "facebook/bart-large": 1_0_2_4, "facebook/bart-large-mnli": 1_0_2_4, "facebook/bart-large-cnn": 1_0_2_4, "facebook/bart-large-xsum": 1_0_2_4, "yjernite/bart_eli5": 1_0_2_4, } @lru_cache() def _lowerCAmelCase ( ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =( list(range(ord('!' ) , ord('~' ) + 1 ) ) + list(range(ord('¡' ) , ord('¬' ) + 1 ) ) + list(range(ord('®' ) , ord('ÿ' ) + 1 ) ) ) _SCREAMING_SNAKE_CASE =bs[:] _SCREAMING_SNAKE_CASE =0 for b in range(2**8 ): if b not in bs: bs.append(_UpperCamelCase ) cs.append(2**8 + n ) n += 1 _SCREAMING_SNAKE_CASE =[chr(_UpperCamelCase ) for n in cs] return dict(zip(_UpperCamelCase , _UpperCamelCase ) ) def _lowerCAmelCase ( _UpperCamelCase : Optional[int] ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =set() _SCREAMING_SNAKE_CASE =word[0] for char in word[1:]: pairs.add((prev_char, char) ) _SCREAMING_SNAKE_CASE =char return pairs class A__ ( A__ ): A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = ['input_ids', 'attention_mask'] def __init__( self : str , _a : Optional[int] , _a : Optional[int] , _a : List[str]="replace" , _a : List[str]="<s>" , _a : int="</s>" , _a : List[Any]="</s>" , _a : Optional[Any]="<s>" , _a : Any="<unk>" , _a : Optional[int]="<pad>" , _a : int="<mask>" , _a : List[str]=False , **_a : Tuple , ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else bos_token _SCREAMING_SNAKE_CASE =AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else eos_token _SCREAMING_SNAKE_CASE =AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else sep_token _SCREAMING_SNAKE_CASE =AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else cls_token _SCREAMING_SNAKE_CASE =AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else unk_token _SCREAMING_SNAKE_CASE =AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else pad_token # Mask token behave like a normal word, i.e. include the space before it _SCREAMING_SNAKE_CASE =AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( errors=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , cls_token=_a , pad_token=_a , mask_token=_a , add_prefix_space=_a , **_a , ) with open(_a , encoding='utf-8' ) as vocab_handle: _SCREAMING_SNAKE_CASE =json.load(_a ) _SCREAMING_SNAKE_CASE ={v: k for k, v in self.encoder.items()} _SCREAMING_SNAKE_CASE =errors # how to handle errors in decoding _SCREAMING_SNAKE_CASE =bytes_to_unicode() _SCREAMING_SNAKE_CASE ={v: k for k, v in self.byte_encoder.items()} with open(_a , encoding='utf-8' ) as merges_handle: _SCREAMING_SNAKE_CASE =merges_handle.read().split('\n' )[1:-1] _SCREAMING_SNAKE_CASE =[tuple(merge.split() ) for merge in bpe_merges] _SCREAMING_SNAKE_CASE =dict(zip(_a , range(len(_a ) ) ) ) _SCREAMING_SNAKE_CASE ={} _SCREAMING_SNAKE_CASE =add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions _SCREAMING_SNAKE_CASE =re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' ) @property def A ( self : Any ) -> str: '''simple docstring''' return len(self.encoder ) def A ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def A ( self : Union[str, Any] , _a : Tuple ) -> str: '''simple docstring''' if token in self.cache: return self.cache[token] _SCREAMING_SNAKE_CASE =tuple(_a ) _SCREAMING_SNAKE_CASE =get_pairs(_a ) if not pairs: return token while True: _SCREAMING_SNAKE_CASE =min(_a , key=lambda _a : self.bpe_ranks.get(_a , float('inf' ) ) ) if bigram not in self.bpe_ranks: break _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =bigram _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =0 while i < len(_a ): try: _SCREAMING_SNAKE_CASE =word.index(_a , _a ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) _SCREAMING_SNAKE_CASE =j if word[i] == first and i < len(_a ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _SCREAMING_SNAKE_CASE =tuple(_a ) _SCREAMING_SNAKE_CASE =new_word if len(_a ) == 1: break else: _SCREAMING_SNAKE_CASE =get_pairs(_a ) _SCREAMING_SNAKE_CASE =' '.join(_a ) _SCREAMING_SNAKE_CASE =word return word def A ( self : Optional[Any] , _a : int ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =[] for token in re.findall(self.pat , _a ): _SCREAMING_SNAKE_CASE =''.join( self.byte_encoder[b] for b in token.encode('utf-8' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_a ).split(' ' ) ) return bpe_tokens def A ( self : Dict , _a : List[str] ) -> int: '''simple docstring''' return self.encoder.get(_a , self.encoder.get(self.unk_token ) ) def A ( self : Dict , _a : List[str] ) -> Tuple: '''simple docstring''' return self.decoder.get(_a ) def A ( self : int , _a : Any ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =''.join(_a ) _SCREAMING_SNAKE_CASE =bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8' , errors=self.errors ) return text def A ( self : List[Any] , _a : str , _a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(_a ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return _SCREAMING_SNAKE_CASE =os.path.join( _a , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) _SCREAMING_SNAKE_CASE =os.path.join( _a , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(_a , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_a , ensure_ascii=_a ) + '\n' ) _SCREAMING_SNAKE_CASE =0 with open(_a , '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 _a : 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!' ) _SCREAMING_SNAKE_CASE =token_index writer.write(' '.join(_a ) + '\n' ) index += 1 return vocab_file, merge_file def A ( self : Tuple , _a : List[int] , _a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _SCREAMING_SNAKE_CASE =[self.cls_token_id] _SCREAMING_SNAKE_CASE =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def A ( self : Optional[int] , _a : List[int] , _a : Optional[List[int]] = None , _a : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def A ( self : Any , _a : List[int] , _a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =[self.sep_token_id] _SCREAMING_SNAKE_CASE =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def A ( self : List[Any] , _a : Tuple , _a : List[Any]=False , **_a : Optional[int] ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =kwargs.pop('add_prefix_space' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(_a ) > 0 and not text[0].isspace()): _SCREAMING_SNAKE_CASE =' ' + text return (text, kwargs)
47
'''simple docstring''' class A__ : def __init__( self : Union[str, Any] , _a : int ) -> None: '''simple docstring''' _SCREAMING_SNAKE_CASE =size _SCREAMING_SNAKE_CASE =[0] * size _SCREAMING_SNAKE_CASE =[0] * size @staticmethod def A ( _a : int ) -> int: '''simple docstring''' return index | (index + 1) @staticmethod def A ( _a : int ) -> int: '''simple docstring''' return (index & (index + 1)) - 1 def A ( self : Tuple , _a : int , _a : int ) -> None: '''simple docstring''' _SCREAMING_SNAKE_CASE =value while index < self.size: _SCREAMING_SNAKE_CASE =self.get_prev(_a ) + 1 if current_left_border == index: _SCREAMING_SNAKE_CASE =value else: _SCREAMING_SNAKE_CASE =max(_a , _a , _a ) _SCREAMING_SNAKE_CASE =self.get_next(_a ) def A ( self : int , _a : int , _a : int ) -> int: '''simple docstring''' right -= 1 # Because of right is exclusive _SCREAMING_SNAKE_CASE =0 while left <= right: _SCREAMING_SNAKE_CASE =self.get_prev(_a ) if left <= current_left: _SCREAMING_SNAKE_CASE =max(_a , self.tree[right] ) _SCREAMING_SNAKE_CASE =current_left else: _SCREAMING_SNAKE_CASE =max(_a , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
47
1
'''simple docstring''' import numpy as np from PIL import Image def _lowerCAmelCase ( _UpperCamelCase : np.ndarray , _UpperCamelCase : int , _UpperCamelCase : int ) -> np.ndarray: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 # compute the shape of the output matrix _SCREAMING_SNAKE_CASE =(arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape _SCREAMING_SNAKE_CASE =np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix _SCREAMING_SNAKE_CASE =np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 return updated_arr def _lowerCAmelCase ( _UpperCamelCase : np.ndarray , _UpperCamelCase : int , _UpperCamelCase : int ) -> np.ndarray: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 # compute the shape of the output matrix _SCREAMING_SNAKE_CASE =(arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape _SCREAMING_SNAKE_CASE =np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix _SCREAMING_SNAKE_CASE =int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name="avgpooling", verbose=True) # Loading the image lowerCamelCase : Optional[Any] = Image.open("path_to_image") # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
47
'''simple docstring''' from __future__ import annotations from random import random from typing import Generic, TypeVar lowerCamelCase : Union[str, Any] = TypeVar("KT") lowerCamelCase : Dict = TypeVar("VT") class A__ ( Generic[KT, VT] ): def __init__( self : str , _a : KT | str = "root" , _a : VT | None = None ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =key _SCREAMING_SNAKE_CASE =value _SCREAMING_SNAKE_CASE =[] def __repr__( self : Union[str, Any] ) -> str: '''simple docstring''' return f"Node({self.key}: {self.value})" @property def A ( self : int ) -> int: '''simple docstring''' return len(self.forward ) class A__ ( Generic[KT, VT] ): def __init__( self : Optional[Any] , _a : float = 0.5 , _a : int = 16 ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =Node[KT, VT]() _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =p _SCREAMING_SNAKE_CASE =max_level def __str__( self : Tuple ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =list(self ) if len(_a ) == 0: return f"SkipList(level={self.level})" _SCREAMING_SNAKE_CASE =max((len(str(_a ) ) for item in items) , default=4 ) _SCREAMING_SNAKE_CASE =max(_a , 4 ) + 4 _SCREAMING_SNAKE_CASE =self.head _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =node.forward.copy() lines.append(f"[{node.key}]".ljust(_a , '-' ) + '* ' * len(_a ) ) lines.append(' ' * label_size + '| ' * len(_a ) ) while len(node.forward ) != 0: _SCREAMING_SNAKE_CASE =node.forward[0] lines.append( f"[{node.key}]".ljust(_a , '-' ) + ' '.join(str(n.key ) if n.key == node.key else '|' for n in forwards ) ) lines.append(' ' * label_size + '| ' * len(_a ) ) _SCREAMING_SNAKE_CASE =node.forward lines.append('None'.ljust(_a ) + '* ' * len(_a ) ) return f"SkipList(level={self.level})\n" + "\n".join(_a ) def __iter__( self : Dict ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.head while len(node.forward ) != 0: yield node.forward[0].key _SCREAMING_SNAKE_CASE =node.forward[0] def A ( self : List[Any] ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =1 while random() < self.p and level < self.max_level: level += 1 return level def A ( self : Any , _a : Any ) -> tuple[Node[KT, VT] | None, list[Node[KT, VT]]]: '''simple docstring''' _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =self.head for i in reversed(range(self.level ) ): # i < node.level - When node level is lesser than `i` decrement `i`. # node.forward[i].key < key - Jumping to node with key value higher # or equal to searched key would result # in skipping searched key. while i < node.level and node.forward[i].key < key: _SCREAMING_SNAKE_CASE =node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(_a ) update_vector.reverse() # Note that we were inserting values in reverse order. # len(node.forward) != 0 - If current node doesn't contain any further # references then searched key is not present. # node.forward[0].key == key - Next node key should be equal to search key # if key is present. if len(node.forward ) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def A ( self : Union[str, Any] , _a : KT ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self._locate_node(_a ) if node is not None: for i, update_node in enumerate(_a ): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: _SCREAMING_SNAKE_CASE =node.forward[i] else: _SCREAMING_SNAKE_CASE =update_node.forward[:i] def A ( self : Optional[Any] , _a : KT , _a : VT ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self._locate_node(_a ) if node is not None: _SCREAMING_SNAKE_CASE =value else: _SCREAMING_SNAKE_CASE =self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for _ in range(self.level - 1 , _a ): update_vector.append(self.head ) _SCREAMING_SNAKE_CASE =level _SCREAMING_SNAKE_CASE =Node(_a , _a ) for i, update_node in enumerate(update_vector[:level] ): # Change references to pass through new node. if update_node.level > i: new_node.forward.append(update_node.forward[i] ) if update_node.level < i + 1: update_node.forward.append(_a ) else: _SCREAMING_SNAKE_CASE =new_node def A ( self : List[str] , _a : VT ) -> VT | None: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self._locate_node(_a ) if node is not None: return node.value return None def _lowerCAmelCase ( ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key1' , 3 ) skip_list.insert('Key2' , 12 ) skip_list.insert('Key3' , 41 ) skip_list.insert('Key4' , -19 ) _SCREAMING_SNAKE_CASE =skip_list.head _SCREAMING_SNAKE_CASE ={} while node.level != 0: _SCREAMING_SNAKE_CASE =node.forward[0] _SCREAMING_SNAKE_CASE =node.value assert len(_UpperCamelCase ) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def _lowerCAmelCase ( ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key1' , 10 ) skip_list.insert('Key1' , 12 ) skip_list.insert('Key5' , 7 ) skip_list.insert('Key7' , 10 ) skip_list.insert('Key10' , 5 ) skip_list.insert('Key7' , 7 ) skip_list.insert('Key5' , 5 ) skip_list.insert('Key10' , 10 ) _SCREAMING_SNAKE_CASE =skip_list.head _SCREAMING_SNAKE_CASE ={} while node.level != 0: _SCREAMING_SNAKE_CASE =node.forward[0] _SCREAMING_SNAKE_CASE =node.value if len(_UpperCamelCase ) != 4: print() assert len(_UpperCamelCase ) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def _lowerCAmelCase ( ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() assert skip_list.find('Some key' ) is None def _lowerCAmelCase ( ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key2' , 20 ) assert skip_list.find('Key2' ) == 20 skip_list.insert('Some Key' , 10 ) skip_list.insert('Key2' , 8 ) skip_list.insert('V' , 13 ) assert skip_list.find('Y' ) is None assert skip_list.find('Key2' ) == 8 assert skip_list.find('Some Key' ) == 10 assert skip_list.find('V' ) == 13 def _lowerCAmelCase ( ) -> List[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.delete('Some key' ) assert len(skip_list.head.forward ) == 0 def _lowerCAmelCase ( ) -> Optional[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key1' , 12 ) skip_list.insert('V' , 13 ) skip_list.insert('X' , 14 ) skip_list.insert('Key2' , 15 ) skip_list.delete('V' ) skip_list.delete('Key2' ) assert skip_list.find('V' ) is None assert skip_list.find('Key2' ) is None def _lowerCAmelCase ( ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key1' , 12 ) skip_list.insert('V' , 13 ) skip_list.insert('X' , 14 ) skip_list.insert('Key2' , 15 ) skip_list.delete('V' ) assert skip_list.find('V' ) is None assert skip_list.find('X' ) == 14 assert skip_list.find('Key1' ) == 12 assert skip_list.find('Key2' ) == 15 skip_list.delete('X' ) assert skip_list.find('V' ) is None assert skip_list.find('X' ) is None assert skip_list.find('Key1' ) == 12 assert skip_list.find('Key2' ) == 15 skip_list.delete('Key1' ) assert skip_list.find('V' ) is None assert skip_list.find('X' ) is None assert skip_list.find('Key1' ) is None assert skip_list.find('Key2' ) == 15 skip_list.delete('Key2' ) assert skip_list.find('V' ) is None assert skip_list.find('X' ) is None assert skip_list.find('Key1' ) is None assert skip_list.find('Key2' ) is None def _lowerCAmelCase ( ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key1' , 12 ) skip_list.insert('V' , 13 ) skip_list.insert('X' , 1_42 ) skip_list.insert('Key2' , 15 ) skip_list.delete('X' ) def traverse_keys(_UpperCamelCase : Dict ): yield node.key for forward_node in node.forward: yield from traverse_keys(_UpperCamelCase ) assert len(set(traverse_keys(skip_list.head ) ) ) == 4 def _lowerCAmelCase ( ) -> Union[str, Any]: """simple docstring""" def is_sorted(_UpperCamelCase : str ): return all(next_item >= item for item, next_item in zip(_UpperCamelCase , lst[1:] ) ) _SCREAMING_SNAKE_CASE =SkipList() for i in range(10 ): skip_list.insert(_UpperCamelCase , _UpperCamelCase ) assert is_sorted(list(_UpperCamelCase ) ) skip_list.delete(5 ) skip_list.delete(8 ) skip_list.delete(2 ) assert is_sorted(list(_UpperCamelCase ) ) skip_list.insert(-12 , -12 ) skip_list.insert(77 , 77 ) assert is_sorted(list(_UpperCamelCase ) ) def _lowerCAmelCase ( ) -> List[str]: """simple docstring""" for _ in range(1_00 ): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def _lowerCAmelCase ( ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert(2 , '2' ) skip_list.insert(4 , '4' ) skip_list.insert(6 , '4' ) skip_list.insert(4 , '5' ) skip_list.insert(8 , '4' ) skip_list.insert(9 , '4' ) skip_list.delete(4 ) print(_UpperCamelCase ) if __name__ == "__main__": import doctest doctest.testmod() main()
47
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : List[Any] = logging.get_logger(__name__) lowerCamelCase : List[str] = { "studio-ousia/luke-base": "https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json", "studio-ousia/luke-large": "https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json", } class A__ ( A__ ): A__ = 'luke' def __init__( self : str , _a : Optional[int]=5_0267 , _a : Optional[int]=50_0000 , _a : int=768 , _a : str=256 , _a : int=12 , _a : Optional[int]=12 , _a : List[Any]=3072 , _a : Union[str, Any]="gelu" , _a : Optional[Any]=0.1 , _a : int=0.1 , _a : List[str]=512 , _a : Tuple=2 , _a : Union[str, Any]=0.02 , _a : Optional[int]=1e-12 , _a : Optional[Any]=True , _a : Any=None , _a : List[Any]=1 , _a : List[Any]=0 , _a : int=2 , **_a : str , ) -> Optional[int]: '''simple docstring''' super().__init__(pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , **_a ) _SCREAMING_SNAKE_CASE =vocab_size _SCREAMING_SNAKE_CASE =entity_vocab_size _SCREAMING_SNAKE_CASE =hidden_size _SCREAMING_SNAKE_CASE =entity_emb_size _SCREAMING_SNAKE_CASE =num_hidden_layers _SCREAMING_SNAKE_CASE =num_attention_heads _SCREAMING_SNAKE_CASE =hidden_act _SCREAMING_SNAKE_CASE =intermediate_size _SCREAMING_SNAKE_CASE =hidden_dropout_prob _SCREAMING_SNAKE_CASE =attention_probs_dropout_prob _SCREAMING_SNAKE_CASE =max_position_embeddings _SCREAMING_SNAKE_CASE =type_vocab_size _SCREAMING_SNAKE_CASE =initializer_range _SCREAMING_SNAKE_CASE =layer_norm_eps _SCREAMING_SNAKE_CASE =use_entity_aware_attention _SCREAMING_SNAKE_CASE =classifier_dropout
47
'''simple docstring''' import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version lowerCamelCase : List[Any] = version.parse(importlib_metadata.version("nltk")) if NLTK_VERSION >= version.Version("3.6.4"): from nltk import word_tokenize lowerCamelCase : Any = "\\n@inproceedings{banarjee2005,\n title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n author = {Banerjee, Satanjeev and Lavie, Alon},\n booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n month = jun,\n year = {2005},\n address = {Ann Arbor, Michigan},\n publisher = {Association for Computational Linguistics},\n url = {https://www.aclweb.org/anthology/W05-0909},\n pages = {65--72},\n}\n" lowerCamelCase : Optional[Any] = "\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n" lowerCamelCase : Optional[Any] = "\nComputes METEOR score of translated segments against one or more references.\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n 'meteor': meteor score.\nExamples:\n\n >>> meteor = datasets.load_metric('meteor')\n >>> predictions = [\"It is a guide to action which ensures that the military always obeys the commands of the party\"]\n >>> references = [\"It is a guide to action that ensures that the military will forever heed Party commands\"]\n >>> results = meteor.compute(predictions=predictions, references=references)\n >>> print(round(results[\"meteor\"], 4))\n 0.6944\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def A ( self : Tuple ) -> str: '''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/nltk/nltk/blob/develop/nltk/translate/meteor_score.py'] , reference_urls=[ 'https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score', 'https://en.wikipedia.org/wiki/METEOR', ] , ) def A ( self : Union[str, Any] , _a : Union[str, Any] ) -> Optional[int]: '''simple docstring''' import nltk nltk.download('wordnet' ) if NLTK_VERSION >= version.Version('3.6.5' ): nltk.download('punkt' ) if NLTK_VERSION >= version.Version('3.6.6' ): nltk.download('omw-1.4' ) def A ( self : int , _a : Tuple , _a : List[str] , _a : List[str]=0.9 , _a : Dict=3 , _a : Optional[int]=0.5 ) -> Optional[int]: '''simple docstring''' if NLTK_VERSION >= version.Version('3.6.5' ): _SCREAMING_SNAKE_CASE =[ meteor_score.single_meteor_score( word_tokenize(_a ) , word_tokenize(_a ) , alpha=_a , beta=_a , gamma=_a ) for ref, pred in zip(_a , _a ) ] else: _SCREAMING_SNAKE_CASE =[ meteor_score.single_meteor_score(_a , _a , alpha=_a , beta=_a , gamma=_a ) for ref, pred in zip(_a , _a ) ] return {"meteor": np.mean(_a )}
47
1
'''simple docstring''' from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class A__ ( A__ ): def A ( self : Optional[Any] ) -> str: '''simple docstring''' return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def A ( self : Any ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE ={'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']} return Dataset.from_dict(_a ) def A ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self._create_example_records() _SCREAMING_SNAKE_CASE =Dataset.from_list(_a ) self.assertListEqual(dset.column_names , ['col_1', 'col_2'] ) for i, r in enumerate(_a ): self.assertDictEqual(_a , example_records[i] ) def A ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self._create_example_records() _SCREAMING_SNAKE_CASE =Dataset.from_list(_a ) _SCREAMING_SNAKE_CASE =Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]} ) self.assertEqual(dset.info , dset_from_dict.info ) def A ( self : Any ) -> List[Any]: # checks what happens with missing columns '''simple docstring''' _SCREAMING_SNAKE_CASE =[{'col_1': 1}, {'col_2': 'x'}] _SCREAMING_SNAKE_CASE =Dataset.from_list(_a ) self.assertDictEqual(dset[0] , {'col_1': 1} ) self.assertDictEqual(dset[1] , {'col_1': None} ) # NB: first record is used for columns def A ( self : str ) -> int: # checks if the type can be inferred from the second record '''simple docstring''' _SCREAMING_SNAKE_CASE =[{'col_1': []}, {'col_1': [1, 2]}] _SCREAMING_SNAKE_CASE =Dataset.from_list(_a ) self.assertEqual(dset.info.features['col_1'] , Sequence(Value('int64' ) ) ) def A ( self : Optional[Any] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =Dataset.from_list([] ) self.assertEqual(len(_a ) , 0 ) self.assertListEqual(dset.column_names , [] )
47
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowerCamelCase : List[str] = logging.get_logger(__name__) lowerCamelCase : List[Any] = { "facebook/convnextv2-tiny-1k-224": "https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json", } class A__ ( A__ , A__ ): A__ = 'convnextv2' def __init__( self : Tuple , _a : Optional[int]=3 , _a : Any=4 , _a : int=4 , _a : Union[str, Any]=None , _a : List[str]=None , _a : Optional[Any]="gelu" , _a : Any=0.02 , _a : Any=1e-12 , _a : Tuple=0.0 , _a : int=224 , _a : Any=None , _a : Optional[int]=None , **_a : List[str] , ) -> Optional[Any]: '''simple docstring''' super().__init__(**_a ) _SCREAMING_SNAKE_CASE =num_channels _SCREAMING_SNAKE_CASE =patch_size _SCREAMING_SNAKE_CASE =num_stages _SCREAMING_SNAKE_CASE =[96, 192, 384, 768] if hidden_sizes is None else hidden_sizes _SCREAMING_SNAKE_CASE =[3, 3, 9, 3] if depths is None else depths _SCREAMING_SNAKE_CASE =hidden_act _SCREAMING_SNAKE_CASE =initializer_range _SCREAMING_SNAKE_CASE =layer_norm_eps _SCREAMING_SNAKE_CASE =drop_path_rate _SCREAMING_SNAKE_CASE =image_size _SCREAMING_SNAKE_CASE =['stem'] + [f"stage{idx}" for idx in range(1 , len(self.depths ) + 1 )] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =get_aligned_output_features_output_indices( out_features=_a , out_indices=_a , stage_names=self.stage_names )
47
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer lowerCamelCase : Optional[Any] = logging.get_logger(__name__) lowerCamelCase : Optional[int] = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} # See all BART models at https://huggingface.co/models?filter=bart lowerCamelCase : Any = { "vocab_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json", }, "merges_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt", }, "tokenizer_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json", }, } lowerCamelCase : Any = { "facebook/bart-base": 1_0_2_4, "facebook/bart-large": 1_0_2_4, "facebook/bart-large-mnli": 1_0_2_4, "facebook/bart-large-cnn": 1_0_2_4, "facebook/bart-large-xsum": 1_0_2_4, "yjernite/bart_eli5": 1_0_2_4, } class A__ ( A__ ): A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = ['input_ids', 'attention_mask'] A__ = BartTokenizer def __init__( self : List[Any] , _a : Any=None , _a : str=None , _a : Any=None , _a : Dict="replace" , _a : List[Any]="<s>" , _a : List[Any]="</s>" , _a : Optional[Any]="</s>" , _a : str="<s>" , _a : Optional[Any]="<unk>" , _a : Any="<pad>" , _a : List[str]="<mask>" , _a : Union[str, Any]=False , _a : List[Any]=True , **_a : Tuple , ) -> List[str]: '''simple docstring''' super().__init__( _a , _a , tokenizer_file=_a , errors=_a , bos_token=_a , eos_token=_a , sep_token=_a , cls_token=_a , unk_token=_a , pad_token=_a , mask_token=_a , add_prefix_space=_a , trim_offsets=_a , **_a , ) _SCREAMING_SNAKE_CASE =json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space' , _a ) != add_prefix_space: _SCREAMING_SNAKE_CASE =getattr(_a , pre_tok_state.pop('type' ) ) _SCREAMING_SNAKE_CASE =add_prefix_space _SCREAMING_SNAKE_CASE =pre_tok_class(**_a ) _SCREAMING_SNAKE_CASE =add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` _SCREAMING_SNAKE_CASE ='post_processor' _SCREAMING_SNAKE_CASE =getattr(self.backend_tokenizer , _a , _a ) if tokenizer_component_instance: _SCREAMING_SNAKE_CASE =json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: _SCREAMING_SNAKE_CASE =tuple(state['sep'] ) if "cls" in state: _SCREAMING_SNAKE_CASE =tuple(state['cls'] ) _SCREAMING_SNAKE_CASE =False if state.get('add_prefix_space' , _a ) != add_prefix_space: _SCREAMING_SNAKE_CASE =add_prefix_space _SCREAMING_SNAKE_CASE =True if state.get('trim_offsets' , _a ) != trim_offsets: _SCREAMING_SNAKE_CASE =trim_offsets _SCREAMING_SNAKE_CASE =True if changes_to_apply: _SCREAMING_SNAKE_CASE =getattr(_a , state.pop('type' ) ) _SCREAMING_SNAKE_CASE =component_class(**_a ) setattr(self.backend_tokenizer , _a , _a ) @property def A ( self : Tuple ) -> str: '''simple docstring''' if self._mask_token is None: if self.verbose: logger.error('Using mask_token, but it is not set yet.' ) return None return str(self._mask_token ) @mask_token.setter def A ( self : List[str] , _a : Union[str, Any] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else value _SCREAMING_SNAKE_CASE =value def A ( self : Dict , *_a : int , **_a : str ) -> BatchEncoding: '''simple docstring''' _SCREAMING_SNAKE_CASE =kwargs.get('is_split_into_words' , _a ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " 'to use it with pretokenized inputs.' ) return super()._batch_encode_plus(*_a , **_a ) def A ( self : Optional[int] , *_a : Any , **_a : str ) -> BatchEncoding: '''simple docstring''' _SCREAMING_SNAKE_CASE =kwargs.get('is_split_into_words' , _a ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " 'to use it with pretokenized inputs.' ) return super()._encode_plus(*_a , **_a ) def A ( self : List[str] , _a : str , _a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self._tokenizer.model.save(_a , name=_a ) return tuple(_a ) def A ( self : Tuple , _a : str , _a : int=None ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =[self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def A ( self : Dict , _a : List[int] , _a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =[self.sep_token_id] _SCREAMING_SNAKE_CASE =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
47
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase : int = {"configuration_glpn": ["GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP", "GLPNConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : int = ["GLPNFeatureExtractor"] lowerCamelCase : Optional[int] = ["GLPNImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Union[str, Any] = [ "GLPN_PRETRAINED_MODEL_ARCHIVE_LIST", "GLPNForDepthEstimation", "GLPNLayer", "GLPNModel", "GLPNPreTrainedModel", ] if TYPE_CHECKING: from .configuration_glpn import GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP, GLPNConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_glpn import GLPNFeatureExtractor from .image_processing_glpn import GLPNImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_glpn import ( GLPN_PRETRAINED_MODEL_ARCHIVE_LIST, GLPNForDepthEstimation, GLPNLayer, GLPNModel, GLPNPreTrainedModel, ) else: import sys lowerCamelCase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
47
1
'''simple docstring''' from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : List[Any] = logging.get_logger(__name__) lowerCamelCase : str = { "huggingface/time-series-transformer-tourism-monthly": ( "https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json" ), # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer } class A__ ( A__ ): A__ = 'time_series_transformer' A__ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self : Optional[int] , _a : Optional[int] = None , _a : Optional[int] = None , _a : str = "student_t" , _a : str = "nll" , _a : int = 1 , _a : List[int] = [1, 2, 3, 4, 5, 6, 7] , _a : Optional[Union[str, bool]] = "mean" , _a : int = 0 , _a : int = 0 , _a : int = 0 , _a : int = 0 , _a : Optional[List[int]] = None , _a : Optional[List[int]] = None , _a : int = 32 , _a : int = 32 , _a : int = 2 , _a : int = 2 , _a : int = 2 , _a : int = 2 , _a : bool = True , _a : str = "gelu" , _a : int = 64 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : int = 100 , _a : float = 0.02 , _a : Union[str, Any]=True , **_a : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =prediction_length _SCREAMING_SNAKE_CASE =context_length or prediction_length _SCREAMING_SNAKE_CASE =distribution_output _SCREAMING_SNAKE_CASE =loss _SCREAMING_SNAKE_CASE =input_size _SCREAMING_SNAKE_CASE =num_time_features _SCREAMING_SNAKE_CASE =lags_sequence _SCREAMING_SNAKE_CASE =scaling _SCREAMING_SNAKE_CASE =num_dynamic_real_features _SCREAMING_SNAKE_CASE =num_static_real_features _SCREAMING_SNAKE_CASE =num_static_categorical_features 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`' ) _SCREAMING_SNAKE_CASE =cardinality else: _SCREAMING_SNAKE_CASE =[0] 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`' ) _SCREAMING_SNAKE_CASE =embedding_dimension else: _SCREAMING_SNAKE_CASE =[min(50 , (cat + 1) // 2 ) for cat in self.cardinality] _SCREAMING_SNAKE_CASE =num_parallel_samples # Transformer architecture configuration _SCREAMING_SNAKE_CASE =input_size * len(_a ) + self._number_of_features _SCREAMING_SNAKE_CASE =d_model _SCREAMING_SNAKE_CASE =encoder_attention_heads _SCREAMING_SNAKE_CASE =decoder_attention_heads _SCREAMING_SNAKE_CASE =encoder_ffn_dim _SCREAMING_SNAKE_CASE =decoder_ffn_dim _SCREAMING_SNAKE_CASE =encoder_layers _SCREAMING_SNAKE_CASE =decoder_layers _SCREAMING_SNAKE_CASE =dropout _SCREAMING_SNAKE_CASE =attention_dropout _SCREAMING_SNAKE_CASE =activation_dropout _SCREAMING_SNAKE_CASE =encoder_layerdrop _SCREAMING_SNAKE_CASE =decoder_layerdrop _SCREAMING_SNAKE_CASE =activation_function _SCREAMING_SNAKE_CASE =init_std _SCREAMING_SNAKE_CASE =use_cache super().__init__(is_encoder_decoder=_a , **_a ) @property def A ( self : List[Any] ) -> int: '''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 )
47
'''simple docstring''' lowerCamelCase : Any = "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" lowerCamelCase : int = [{"type": "code", "content": INSTALL_CONTENT}] lowerCamelCase : str = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
47
1
'''simple docstring''' import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _lowerCAmelCase ( ) -> Any: """simple docstring""" _SCREAMING_SNAKE_CASE =ArgumentParser( description=( 'PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes' ) ) # Optional arguments for the launch helper parser.add_argument('--num_cores' , type=_UpperCamelCase , default=1 , help='Number of TPU cores to use (1 or 8).' ) # positional parser.add_argument( 'training_script' , type=_UpperCamelCase , help=( 'The full path to the single TPU training ' 'program/script to be launched in parallel, ' 'followed by all the arguments for the ' 'training script' ) , ) # rest from the training program parser.add_argument('training_script_args' , nargs=_UpperCamelCase ) return parser.parse_args() def _lowerCAmelCase ( ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =parse_args() # Import training_script as a module. _SCREAMING_SNAKE_CASE =Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) _SCREAMING_SNAKE_CASE =script_fpath.stem _SCREAMING_SNAKE_CASE =importlib.import_module(_UpperCamelCase ) # Patch sys.argv _SCREAMING_SNAKE_CASE =[args.training_script] + args.training_script_args + ['--tpu_num_cores', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
47
'''simple docstring''' import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device lowerCamelCase : Optional[int] = False class A__ ( unittest.TestCase ): pass @slow @require_torch_gpu class A__ ( unittest.TestCase ): def A ( self : Tuple ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =VersatileDiffusionImageVariationPipeline.from_pretrained('shi-labs/versatile-diffusion' ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) _SCREAMING_SNAKE_CASE =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg' ) _SCREAMING_SNAKE_CASE =torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE =pipe( image=_a , generator=_a , guidance_scale=7.5 , num_inference_steps=50 , output_type='numpy' , ).images _SCREAMING_SNAKE_CASE =image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) _SCREAMING_SNAKE_CASE =np.array([0.04_41, 0.04_69, 0.05_07, 0.05_75, 0.06_32, 0.06_50, 0.08_65, 0.09_09, 0.09_45] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
47
1
'''simple docstring''' from statistics import mean import numpy as np def _lowerCAmelCase ( _UpperCamelCase : list , _UpperCamelCase : list , _UpperCamelCase : list , _UpperCamelCase : int ) -> list: """simple docstring""" _SCREAMING_SNAKE_CASE =0 # Number of processes finished _SCREAMING_SNAKE_CASE =0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. _SCREAMING_SNAKE_CASE =[0] * no_of_process # List to include calculation results _SCREAMING_SNAKE_CASE =[0] * no_of_process # Sort by arrival time. _SCREAMING_SNAKE_CASE =[burst_time[i] for i in np.argsort(_UpperCamelCase )] _SCREAMING_SNAKE_CASE =[process_name[i] for i in np.argsort(_UpperCamelCase )] arrival_time.sort() while no_of_process > finished_process_count: _SCREAMING_SNAKE_CASE =0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: _SCREAMING_SNAKE_CASE =arrival_time[i] _SCREAMING_SNAKE_CASE =0 # Index showing the location of the process being performed _SCREAMING_SNAKE_CASE =0 # Saves the current response ratio. _SCREAMING_SNAKE_CASE =0 for i in range(0 , _UpperCamelCase ): if finished_process[i] == 0 and arrival_time[i] <= current_time: _SCREAMING_SNAKE_CASE =(burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: _SCREAMING_SNAKE_CASE =temp _SCREAMING_SNAKE_CASE =i # Calculate the turn around time _SCREAMING_SNAKE_CASE =current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. _SCREAMING_SNAKE_CASE =1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def _lowerCAmelCase ( _UpperCamelCase : list , _UpperCamelCase : list , _UpperCamelCase : list , _UpperCamelCase : int ) -> list: """simple docstring""" _SCREAMING_SNAKE_CASE =[0] * no_of_process for i in range(0 , _UpperCamelCase ): _SCREAMING_SNAKE_CASE =turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": lowerCamelCase : Dict = 5 lowerCamelCase : Optional[int] = ["A", "B", "C", "D", "E"] lowerCamelCase : Tuple = [1, 2, 3, 4, 5] lowerCamelCase : str = [1, 2, 3, 4, 5] lowerCamelCase : Tuple = calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) lowerCamelCase : Optional[Any] = calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print("Process name \tArrival time \tBurst time \tTurn around time \tWaiting time") for i in range(0, no_of_process): print( f'''{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t''' f'''{turn_around_time[i]}\t\t\t{waiting_time[i]}''' ) print(f'''average waiting time : {mean(waiting_time):.5f}''') print(f'''average turn around time : {mean(turn_around_time):.5f}''')
47
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase : Any = { "configuration_funnel": ["FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP", "FunnelConfig"], "convert_funnel_original_tf_checkpoint_to_pytorch": [], "tokenization_funnel": ["FunnelTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[Any] = ["FunnelTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[str] = [ "FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST", "FunnelBaseModel", "FunnelForMaskedLM", "FunnelForMultipleChoice", "FunnelForPreTraining", "FunnelForQuestionAnswering", "FunnelForSequenceClassification", "FunnelForTokenClassification", "FunnelModel", "FunnelPreTrainedModel", "load_tf_weights_in_funnel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Union[str, Any] = [ "TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST", "TFFunnelBaseModel", "TFFunnelForMaskedLM", "TFFunnelForMultipleChoice", "TFFunnelForPreTraining", "TFFunnelForQuestionAnswering", "TFFunnelForSequenceClassification", "TFFunnelForTokenClassification", "TFFunnelModel", "TFFunnelPreTrainedModel", ] if TYPE_CHECKING: from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig from .tokenization_funnel import FunnelTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_funnel_fast import FunnelTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_funnel import ( FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, FunnelBaseModel, FunnelForMaskedLM, FunnelForMultipleChoice, FunnelForPreTraining, FunnelForQuestionAnswering, FunnelForSequenceClassification, FunnelForTokenClassification, FunnelModel, FunnelPreTrainedModel, load_tf_weights_in_funnel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_funnel import ( TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, TFFunnelPreTrainedModel, ) else: import sys lowerCamelCase : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
47
1
'''simple docstring''' import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): lowerCamelCase : Tuple = "pt" elif is_tf_available(): lowerCamelCase : Optional[int] = "tf" else: lowerCamelCase : Tuple = "jax" class A__ ( A__ , unittest.TestCase ): A__ = ByTaTokenizer A__ = False def A ( self : str ) -> Any: '''simple docstring''' super().setUp() _SCREAMING_SNAKE_CASE =ByTaTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def A ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' return ByTaTokenizer.from_pretrained('google/byt5-small' ) def A ( self : Dict , **_a : Union[str, Any] ) -> ByTaTokenizer: '''simple docstring''' return self.tokenizer_class.from_pretrained(self.tmpdirname , **_a ) def A ( self : List[str] , _a : Dict , _a : str=False , _a : Optional[int]=20 , _a : int=5 ) -> Tuple[str, list]: '''simple docstring''' _SCREAMING_SNAKE_CASE =[] for i in range(len(_a ) ): try: _SCREAMING_SNAKE_CASE =tokenizer.decode([i] , clean_up_tokenization_spaces=_a ) except UnicodeDecodeError: pass toks.append((i, tok) ) _SCREAMING_SNAKE_CASE =list(filter(lambda _a : re.match(r'^[ a-zA-Z]+$' , t[1] ) , _a ) ) _SCREAMING_SNAKE_CASE =list(filter(lambda _a : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=_a ) , _a ) ) if max_length is not None and len(_a ) > max_length: _SCREAMING_SNAKE_CASE =toks[:max_length] if min_length is not None and len(_a ) < min_length and len(_a ) > 0: while len(_a ) < min_length: _SCREAMING_SNAKE_CASE =toks + toks # toks_str = [t[1] for t in toks] _SCREAMING_SNAKE_CASE =[t[0] for t in toks] # Ensure consistency _SCREAMING_SNAKE_CASE =tokenizer.decode(_a , clean_up_tokenization_spaces=_a ) if " " not in output_txt and len(_a ) > 1: _SCREAMING_SNAKE_CASE =( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=_a ) + ' ' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=_a ) ) if with_prefix_space: _SCREAMING_SNAKE_CASE =' ' + output_txt _SCREAMING_SNAKE_CASE =tokenizer.encode(_a , add_special_tokens=_a ) return output_txt, output_ids def A ( self : Any ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.ta_base_tokenizer _SCREAMING_SNAKE_CASE =tokenizer(['hi</s>', 'I went to the gym</s>', '</s>'] ) _SCREAMING_SNAKE_CASE =tokenizer(['hi', 'I went to the gym', ''] ) self.assertListEqual(batch_with_eos_added['input_ids'] , batch_without_eos_added['input_ids'] ) def A ( self : Optional[int] ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.ta_base_tokenizer _SCREAMING_SNAKE_CASE ='Unicode €.' _SCREAMING_SNAKE_CASE =tokenizer(_a ) _SCREAMING_SNAKE_CASE =[88, 113, 108, 102, 114, 103, 104, 35, 229, 133, 175, 49, 1] self.assertEqual(encoded['input_ids'] , _a ) # decoding _SCREAMING_SNAKE_CASE =tokenizer.decode(_a ) self.assertEqual(_a , 'Unicode €.</s>' ) _SCREAMING_SNAKE_CASE =tokenizer('e è é ê ë' ) _SCREAMING_SNAKE_CASE =[104, 35, 198, 171, 35, 198, 172, 35, 198, 173, 35, 198, 174, 1] self.assertEqual(encoded['input_ids'] , _a ) # decoding _SCREAMING_SNAKE_CASE =tokenizer.decode(_a ) self.assertEqual(_a , 'e è é ê ë</s>' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('e è é ê ë' ) ) , 'e è é ê ë</s>' ) def A ( self : Union[str, Any] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.ta_base_tokenizer _SCREAMING_SNAKE_CASE =['A long paragraph for summarization.', 'Another paragraph for summarization.'] # fmt: off _SCREAMING_SNAKE_CASE =[68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 1, 0] # fmt: on _SCREAMING_SNAKE_CASE =tokenizer(_a , padding=_a , return_tensors=_a ) self.assertIsInstance(_a , _a ) if FRAMEWORK != "jax": _SCREAMING_SNAKE_CASE =list(batch.input_ids.numpy()[0] ) else: _SCREAMING_SNAKE_CASE =list(batch.input_ids.tolist()[0] ) self.assertListEqual(_a , _a ) self.assertEqual((2, 37) , batch.input_ids.shape ) self.assertEqual((2, 37) , batch.attention_mask.shape ) def A ( self : Dict ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.ta_base_tokenizer _SCREAMING_SNAKE_CASE =['A long paragraph for summarization.', 'Another paragraph for summarization.'] _SCREAMING_SNAKE_CASE =tokenizer(_a , padding=_a , return_tensors=_a ) # check if input_ids are returned and no decoder_input_ids self.assertIn('input_ids' , _a ) self.assertIn('attention_mask' , _a ) self.assertNotIn('decoder_input_ids' , _a ) self.assertNotIn('decoder_attention_mask' , _a ) def A ( self : List[str] ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.ta_base_tokenizer _SCREAMING_SNAKE_CASE =[ 'Summary of the text.', 'Another summary.', ] _SCREAMING_SNAKE_CASE =tokenizer( text_target=_a , max_length=32 , padding='max_length' , truncation=_a , return_tensors=_a ) self.assertEqual(32 , targets['input_ids'].shape[1] ) def A ( self : Union[str, Any] ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.ta_base_tokenizer _SCREAMING_SNAKE_CASE =['A long paragraph for summarization. </s>'] _SCREAMING_SNAKE_CASE =['Summary of the text. </s>'] # fmt: off _SCREAMING_SNAKE_CASE =[68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 35, 1] _SCREAMING_SNAKE_CASE =[86, 120, 112, 112, 100, 117, 124, 35, 114, 105, 35, 119, 107, 104, 35, 119, 104, 123, 119, 49, 35, 1] # fmt: on _SCREAMING_SNAKE_CASE =tokenizer(_a , text_target=_a ) self.assertEqual(_a , batch['input_ids'][0] ) self.assertEqual(_a , batch['labels'][0] ) def A ( self : Tuple ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test _SCREAMING_SNAKE_CASE =self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): # Isolate this from the other tests because we save additional tokens/etc _SCREAMING_SNAKE_CASE =tempfile.mkdtemp() _SCREAMING_SNAKE_CASE =' He is very happy, UNwant\u00E9d,running' _SCREAMING_SNAKE_CASE =tokenizer.encode(_a , add_special_tokens=_a ) tokenizer.save_pretrained(_a ) _SCREAMING_SNAKE_CASE =tokenizer.__class__.from_pretrained(_a ) _SCREAMING_SNAKE_CASE =after_tokenizer.encode(_a , add_special_tokens=_a ) self.assertListEqual(_a , _a ) shutil.rmtree(_a ) _SCREAMING_SNAKE_CASE =self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): # Isolate this from the other tests because we save additional tokens/etc _SCREAMING_SNAKE_CASE =tempfile.mkdtemp() _SCREAMING_SNAKE_CASE =' He is very happy, UNwant\u00E9d,running' tokenizer.add_tokens(['bim', 'bambam'] ) _SCREAMING_SNAKE_CASE =tokenizer.additional_special_tokens additional_special_tokens.append('new_additional_special_token' ) tokenizer.add_special_tokens({'additional_special_tokens': additional_special_tokens} ) _SCREAMING_SNAKE_CASE =tokenizer.encode(_a , add_special_tokens=_a ) tokenizer.save_pretrained(_a ) _SCREAMING_SNAKE_CASE =tokenizer.__class__.from_pretrained(_a ) _SCREAMING_SNAKE_CASE =after_tokenizer.encode(_a , add_special_tokens=_a ) self.assertListEqual(_a , _a ) self.assertIn('new_additional_special_token' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) _SCREAMING_SNAKE_CASE =tokenizer.__class__.from_pretrained(_a , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(_a ) def A ( self : int ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =[] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(_a ) with open(os.path.join(_a , 'special_tokens_map.json' ) , encoding='utf-8' ) as json_file: _SCREAMING_SNAKE_CASE =json.load(_a ) with open(os.path.join(_a , 'tokenizer_config.json' ) , encoding='utf-8' ) as json_file: _SCREAMING_SNAKE_CASE =json.load(_a ) _SCREAMING_SNAKE_CASE =[f"<extra_id_{i}>" for i in range(125 )] _SCREAMING_SNAKE_CASE =added_tokens_extra_ids + [ 'an_additional_special_token' ] _SCREAMING_SNAKE_CASE =added_tokens_extra_ids + [ 'an_additional_special_token' ] with open(os.path.join(_a , 'special_tokens_map.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(_a , _a ) with open(os.path.join(_a , 'tokenizer_config.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(_a , _a ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files _SCREAMING_SNAKE_CASE =tokenizer_class.from_pretrained( _a , ) self.assertIn( 'an_additional_special_token' , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( ['an_additional_special_token'] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['an_additional_special_token'] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained _SCREAMING_SNAKE_CASE =added_tokens_extra_ids + [AddedToken('a_new_additional_special_token' , lstrip=_a )] _SCREAMING_SNAKE_CASE =tokenizer_class.from_pretrained( _a , additional_special_tokens=_a , ) self.assertIn('a_new_additional_special_token' , tokenizer.additional_special_tokens ) self.assertEqual( ['a_new_additional_special_token'] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['a_new_additional_special_token'] ) ) , ) def A ( self : Union[str, Any] ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =[] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(_a ) _SCREAMING_SNAKE_CASE =tokenizer_class.from_pretrained(_a ) self.assertTrue(tokenizer.decode([255] ) == '' ) def A ( self : int ) -> List[Any]: '''simple docstring''' pass def A ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' pass def A ( self : List[Any] ) -> Tuple: '''simple docstring''' pass def A ( self : Tuple ) -> Optional[Any]: '''simple docstring''' pass def A ( self : Optional[int] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.get_tokenizers(fast=_a , do_lower_case=_a ) for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): _SCREAMING_SNAKE_CASE =['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 'x', 't', '</s>'] _SCREAMING_SNAKE_CASE =tokenizer.convert_tokens_to_string(_a ) self.assertIsInstance(_a , _a ) def A ( self : List[str] ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): _SCREAMING_SNAKE_CASE =[ 'bos_token', 'eos_token', 'unk_token', 'sep_token', 'pad_token', 'cls_token', 'mask_token', ] _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =tokenizer.convert_ids_to_tokens( _a , skip_special_tokens=_a ) for attr in attributes_list: setattr(_a , attr + '_id' , _a ) self.assertEqual(getattr(_a , _a ) , _a ) self.assertEqual(getattr(_a , attr + '_id' ) , _a ) setattr(_a , attr + '_id' , _a ) self.assertEqual(getattr(_a , _a ) , _a ) self.assertEqual(getattr(_a , attr + '_id' ) , _a ) setattr(_a , 'additional_special_tokens_ids' , [] ) self.assertListEqual(getattr(_a , 'additional_special_tokens' ) , [] ) self.assertListEqual(getattr(_a , 'additional_special_tokens_ids' ) , [] ) setattr(_a , 'additional_special_tokens_ids' , [token_id_to_test_setters] ) self.assertListEqual(getattr(_a , 'additional_special_tokens' ) , [token_to_test_setters] ) self.assertListEqual(getattr(_a , 'additional_special_tokens_ids' ) , [token_id_to_test_setters] )
47
'''simple docstring''' import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def _lowerCAmelCase ( _UpperCamelCase : Dict , _UpperCamelCase : Any=False ) -> Optional[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =OmegaConf.load(_UpperCamelCase ) if display: print(yaml.dump(OmegaConf.to_container(_UpperCamelCase ) ) ) return config def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : Optional[Any]=None , _UpperCamelCase : Union[str, Any]=None ) -> Optional[Any]: """simple docstring""" if conf_path is None: _SCREAMING_SNAKE_CASE ='./model_checkpoints/vqgan_only.yaml' _SCREAMING_SNAKE_CASE =load_config(_UpperCamelCase , display=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =VQModel(**config.model.params ) if ckpt_path is None: _SCREAMING_SNAKE_CASE ='./model_checkpoints/vqgan_only.pt' _SCREAMING_SNAKE_CASE =torch.load(_UpperCamelCase , map_location=_UpperCamelCase ) if ".ckpt" in ckpt_path: _SCREAMING_SNAKE_CASE =sd['state_dict'] model.load_state_dict(_UpperCamelCase , strict=_UpperCamelCase ) model.to(_UpperCamelCase ) del sd return model def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : int ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =model.encode(_UpperCamelCase ) print(f"VQGAN --- {model.__class__.__name__}: latent shape: {z.shape[2:]}" ) _SCREAMING_SNAKE_CASE =model.decode(_UpperCamelCase ) return xrec def _lowerCAmelCase ( _UpperCamelCase : Dict , _UpperCamelCase : List[str]=False ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =string.rsplit('.' , 1 ) if reload: _SCREAMING_SNAKE_CASE =importlib.import_module(_UpperCamelCase ) importlib.reload(_UpperCamelCase ) return getattr(importlib.import_module(_UpperCamelCase , package=_UpperCamelCase ) , cls ) def _lowerCAmelCase ( _UpperCamelCase : str ) -> List[str]: """simple docstring""" if "target" not in config: raise KeyError('Expected key `target` to instantiate.' ) return get_obj_from_str(config['target'] )(**config.get('params' , {} ) ) def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : List[Any] , _UpperCamelCase : List[str]=True , _UpperCamelCase : int=True ) -> Union[str, Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =instantiate_from_config(_UpperCamelCase ) if sd is not None: model.load_state_dict(_UpperCamelCase ) if gpu: model.cuda() if eval_mode: model.eval() return {"model": model} def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Optional[Any] , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Optional[int] ) -> List[Any]: """simple docstring""" if ckpt: _SCREAMING_SNAKE_CASE =torch.load(_UpperCamelCase , map_location='cpu' ) _SCREAMING_SNAKE_CASE =pl_sd['global_step'] print(f"loaded model from global step {global_step}." ) else: _SCREAMING_SNAKE_CASE ={'state_dict': None} _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =load_model_from_config(config.model , pl_sd['state_dict'] , gpu=_UpperCamelCase , eval_mode=_UpperCamelCase )['model'] return model, global_step
47
1
'''simple docstring''' def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =[], [] while len(_UpperCamelCase ) > 1: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =min(_UpperCamelCase ), max(_UpperCamelCase ) start.append(_UpperCamelCase ) end.append(_UpperCamelCase ) collection.remove(_UpperCamelCase ) collection.remove(_UpperCamelCase ) end.reverse() return start + collection + end if __name__ == "__main__": lowerCamelCase : List[Any] = input("Enter numbers separated by a comma:\n").strip() lowerCamelCase : Any = [int(item) for item in user_input.split(",")] print(*merge_sort(unsorted), sep=",")
47
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase : int = {"configuration_mbart": ["MBART_PRETRAINED_CONFIG_ARCHIVE_MAP", "MBartConfig", "MBartOnnxConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[Any] = ["MBartTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Dict = ["MBartTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : int = [ "MBART_PRETRAINED_MODEL_ARCHIVE_LIST", "MBartForCausalLM", "MBartForConditionalGeneration", "MBartForQuestionAnswering", "MBartForSequenceClassification", "MBartModel", "MBartPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Union[str, Any] = [ "TFMBartForConditionalGeneration", "TFMBartModel", "TFMBartPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[Any] = [ "FlaxMBartForConditionalGeneration", "FlaxMBartForQuestionAnswering", "FlaxMBartForSequenceClassification", "FlaxMBartModel", "FlaxMBartPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys lowerCamelCase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
47
1
'''simple docstring''' import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A__ ( A__ , unittest.TestCase ): A__ = LayoutLMTokenizer A__ = LayoutLMTokenizerFast A__ = True A__ = True def A ( self : Any ) -> int: '''simple docstring''' super().setUp() _SCREAMING_SNAKE_CASE =[ '[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] _SCREAMING_SNAKE_CASE =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def A ( self : List[Any] , **_a : List[str] ) -> Tuple: '''simple docstring''' return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_a ) def A ( self : Dict , _a : str ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE ='UNwant\u00E9d,running' _SCREAMING_SNAKE_CASE ='unwanted, running' return input_text, output_text def A ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.tokenizer_class(self.vocab_file ) _SCREAMING_SNAKE_CASE =tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(_a , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [7, 4, 5, 10, 8, 9] ) def A ( self : Optional[Any] ) -> Tuple: '''simple docstring''' pass
47
'''simple docstring''' from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : List[Any] = logging.get_logger(__name__) lowerCamelCase : str = { "huggingface/time-series-transformer-tourism-monthly": ( "https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json" ), # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer } class A__ ( A__ ): A__ = 'time_series_transformer' A__ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self : Optional[int] , _a : Optional[int] = None , _a : Optional[int] = None , _a : str = "student_t" , _a : str = "nll" , _a : int = 1 , _a : List[int] = [1, 2, 3, 4, 5, 6, 7] , _a : Optional[Union[str, bool]] = "mean" , _a : int = 0 , _a : int = 0 , _a : int = 0 , _a : int = 0 , _a : Optional[List[int]] = None , _a : Optional[List[int]] = None , _a : int = 32 , _a : int = 32 , _a : int = 2 , _a : int = 2 , _a : int = 2 , _a : int = 2 , _a : bool = True , _a : str = "gelu" , _a : int = 64 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : int = 100 , _a : float = 0.02 , _a : Union[str, Any]=True , **_a : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =prediction_length _SCREAMING_SNAKE_CASE =context_length or prediction_length _SCREAMING_SNAKE_CASE =distribution_output _SCREAMING_SNAKE_CASE =loss _SCREAMING_SNAKE_CASE =input_size _SCREAMING_SNAKE_CASE =num_time_features _SCREAMING_SNAKE_CASE =lags_sequence _SCREAMING_SNAKE_CASE =scaling _SCREAMING_SNAKE_CASE =num_dynamic_real_features _SCREAMING_SNAKE_CASE =num_static_real_features _SCREAMING_SNAKE_CASE =num_static_categorical_features 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`' ) _SCREAMING_SNAKE_CASE =cardinality else: _SCREAMING_SNAKE_CASE =[0] 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`' ) _SCREAMING_SNAKE_CASE =embedding_dimension else: _SCREAMING_SNAKE_CASE =[min(50 , (cat + 1) // 2 ) for cat in self.cardinality] _SCREAMING_SNAKE_CASE =num_parallel_samples # Transformer architecture configuration _SCREAMING_SNAKE_CASE =input_size * len(_a ) + self._number_of_features _SCREAMING_SNAKE_CASE =d_model _SCREAMING_SNAKE_CASE =encoder_attention_heads _SCREAMING_SNAKE_CASE =decoder_attention_heads _SCREAMING_SNAKE_CASE =encoder_ffn_dim _SCREAMING_SNAKE_CASE =decoder_ffn_dim _SCREAMING_SNAKE_CASE =encoder_layers _SCREAMING_SNAKE_CASE =decoder_layers _SCREAMING_SNAKE_CASE =dropout _SCREAMING_SNAKE_CASE =attention_dropout _SCREAMING_SNAKE_CASE =activation_dropout _SCREAMING_SNAKE_CASE =encoder_layerdrop _SCREAMING_SNAKE_CASE =decoder_layerdrop _SCREAMING_SNAKE_CASE =activation_function _SCREAMING_SNAKE_CASE =init_std _SCREAMING_SNAKE_CASE =use_cache super().__init__(is_encoder_decoder=_a , **_a ) @property def A ( self : List[Any] ) -> int: '''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 )
47
1
'''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 A__ : def __init__( self : str , _a : Any , _a : List[str]=13 , _a : Union[str, Any]=7 , _a : List[Any]=True , _a : Optional[int]=True , _a : Tuple=True , _a : Optional[Any]=True , _a : Optional[int]=99 , _a : str=24 , _a : str=2 , _a : Union[str, Any]=6 , _a : Union[str, Any]=37 , _a : Any="gelu" , _a : Any=0.1 , _a : List[Any]=0.1 , _a : List[str]=512 , _a : Tuple=16 , _a : List[str]=2 , _a : int=0.02 , _a : Optional[int]=3 , _a : Any=None , _a : int=1000 , ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =parent _SCREAMING_SNAKE_CASE =batch_size _SCREAMING_SNAKE_CASE =seq_length _SCREAMING_SNAKE_CASE =is_training _SCREAMING_SNAKE_CASE =use_input_mask _SCREAMING_SNAKE_CASE =use_token_type_ids _SCREAMING_SNAKE_CASE =use_labels _SCREAMING_SNAKE_CASE =vocab_size _SCREAMING_SNAKE_CASE =hidden_size _SCREAMING_SNAKE_CASE =num_hidden_layers _SCREAMING_SNAKE_CASE =num_attention_heads _SCREAMING_SNAKE_CASE =intermediate_size _SCREAMING_SNAKE_CASE =hidden_act _SCREAMING_SNAKE_CASE =hidden_dropout_prob _SCREAMING_SNAKE_CASE =attention_probs_dropout_prob _SCREAMING_SNAKE_CASE =max_position_embeddings _SCREAMING_SNAKE_CASE =type_vocab_size _SCREAMING_SNAKE_CASE =type_sequence_label_size _SCREAMING_SNAKE_CASE =initializer_range _SCREAMING_SNAKE_CASE =num_labels _SCREAMING_SNAKE_CASE =scope _SCREAMING_SNAKE_CASE =range_bbox def A ( self : int ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE =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]: _SCREAMING_SNAKE_CASE =bbox[i, j, 3] _SCREAMING_SNAKE_CASE =bbox[i, j, 1] _SCREAMING_SNAKE_CASE =t if bbox[i, j, 2] < bbox[i, j, 0]: _SCREAMING_SNAKE_CASE =bbox[i, j, 2] _SCREAMING_SNAKE_CASE =bbox[i, j, 0] _SCREAMING_SNAKE_CASE =t _SCREAMING_SNAKE_CASE =None if self.use_input_mask: _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) _SCREAMING_SNAKE_CASE =None if self.use_token_type_ids: _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =None if self.use_labels: _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _SCREAMING_SNAKE_CASE =self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def A ( self : Optional[int] ) -> 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 A ( self : int , _a : Any , _a : str , _a : Union[str, Any] , _a : Any , _a : Tuple , _a : List[Any] , _a : Dict , ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =LiltModel(config=_a ) model.to(_a ) model.eval() _SCREAMING_SNAKE_CASE =model(_a , bbox=_a , attention_mask=_a , token_type_ids=_a ) _SCREAMING_SNAKE_CASE =model(_a , bbox=_a , token_type_ids=_a ) _SCREAMING_SNAKE_CASE =model(_a , bbox=_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def A ( self : Optional[int] , _a : Tuple , _a : List[str] , _a : Optional[Any] , _a : Any , _a : Tuple , _a : Any , _a : Optional[int] , ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.num_labels _SCREAMING_SNAKE_CASE =LiltForTokenClassification(config=_a ) model.to(_a ) model.eval() _SCREAMING_SNAKE_CASE =model( _a , bbox=_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def A ( self : Tuple , _a : str , _a : List[str] , _a : Optional[Any] , _a : Union[str, Any] , _a : Dict , _a : List[Any] , _a : str , ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =LiltForQuestionAnswering(config=_a ) model.to(_a ) model.eval() _SCREAMING_SNAKE_CASE =model( _a , bbox=_a , attention_mask=_a , token_type_ids=_a , start_positions=_a , end_positions=_a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def A ( self : Dict ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() ( ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ) =config_and_inputs _SCREAMING_SNAKE_CASE ={ 'input_ids': input_ids, 'bbox': bbox, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_torch class A__ ( A__ , A__ , A__ , unittest.TestCase ): A__ = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) A__ = ( { 'feature-extraction': LiltModel, 'question-answering': LiltForQuestionAnswering, 'text-classification': LiltForSequenceClassification, 'token-classification': LiltForTokenClassification, 'zero-shot': LiltForSequenceClassification, } if is_torch_available() else {} ) A__ = False A__ = False def A ( self : Tuple , _a : Union[str, Any] , _a : int , _a : List[Any] , _a : Optional[int] , _a : int ) -> Optional[Any]: '''simple docstring''' return True def A ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =LiltModelTester(self ) _SCREAMING_SNAKE_CASE =ConfigTester(self , config_class=_a , hidden_size=37 ) def A ( self : Dict ) -> Optional[int]: '''simple docstring''' self.config_tester.run_common_tests() def A ( self : Union[str, Any] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def A ( self : Optional[int] ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _SCREAMING_SNAKE_CASE =type self.model_tester.create_and_check_model(*_a ) def A ( self : int ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_a ) def A ( self : List[Any] ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_a ) @slow def A ( self : Optional[int] ) -> Dict: '''simple docstring''' for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _SCREAMING_SNAKE_CASE =LiltModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @require_torch @slow class A__ ( unittest.TestCase ): def A ( self : Dict ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =LiltModel.from_pretrained('SCUT-DLVCLab/lilt-roberta-en-base' ).to(_a ) _SCREAMING_SNAKE_CASE =torch.tensor([[1, 2]] , device=_a ) _SCREAMING_SNAKE_CASE =torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=_a ) # forward pass with torch.no_grad(): _SCREAMING_SNAKE_CASE =model(input_ids=_a , bbox=_a ) _SCREAMING_SNAKE_CASE =torch.Size([1, 2, 768] ) _SCREAMING_SNAKE_CASE =torch.tensor( [[-0.06_53, 0.09_50, -0.00_61], [-0.05_45, 0.09_26, -0.03_24]] , device=_a , ) self.assertTrue(outputs.last_hidden_state.shape , _a ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , _a , atol=1e-3 ) )
47
'''simple docstring''' import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets lowerCamelCase : List[Any] = "\\n @inproceedings{kakwani2020indicnlpsuite,\n title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}},\n author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar},\n year={2020},\n booktitle={Findings of EMNLP},\n}\n" lowerCamelCase : Optional[Any] = "\\n IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide\n variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te.\n" lowerCamelCase : int = "\nCompute IndicGLUE evaluation metric associated to each IndicGLUE dataset.\nArgs:\n predictions: list of predictions to score (as int64),\n except for 'cvit-mkb-clsr' where each prediction is a vector (of float32).\n references: list of ground truth labels corresponding to the predictions (as int64),\n except for 'cvit-mkb-clsr' where each reference is a vector (of float32).\nReturns: depending on the IndicGLUE subset, one or several of:\n \"accuracy\": Accuracy\n \"f1\": F1 score\n \"precision\": Precision@10\nExamples:\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr')\n >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'precision@10': 1.0}\n\n" def _lowerCAmelCase ( _UpperCamelCase : List[str] , _UpperCamelCase : Tuple ) -> List[Any]: """simple docstring""" return float((preds == labels).mean() ) def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Any ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =simple_accuracy(_UpperCamelCase , _UpperCamelCase ) _SCREAMING_SNAKE_CASE =float(fa_score(y_true=_UpperCamelCase , y_pred=_UpperCamelCase ) ) return { "accuracy": acc, "f1": fa, } def _lowerCAmelCase ( _UpperCamelCase : Any , _UpperCamelCase : int ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =en_sentvecs.shape[0] # mean centering _SCREAMING_SNAKE_CASE =en_sentvecs - np.mean(_UpperCamelCase , axis=0 ) _SCREAMING_SNAKE_CASE =in_sentvecs - np.mean(_UpperCamelCase , axis=0 ) _SCREAMING_SNAKE_CASE =cdist(_UpperCamelCase , _UpperCamelCase , 'cosine' ) _SCREAMING_SNAKE_CASE =np.array(range(_UpperCamelCase ) ) _SCREAMING_SNAKE_CASE =sim.argsort(axis=1 )[:, :10] _SCREAMING_SNAKE_CASE =np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def A ( self : Any ) -> List[str]: '''simple docstring''' if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('int64' ) if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32' ) ), 'references': datasets.Value('int64' ) if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32' ) ), } ) , codebase_urls=[] , reference_urls=[] , format='numpy' if self.config_name != 'cvit-mkb-clsr' else None , ) def A ( self : List[str] , _a : Tuple , _a : Optional[int] ) -> int: '''simple docstring''' if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(_a , _a )} elif self.config_name in ["wiki-ner"]: return acc_and_fa(_a , _a ) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(_a , _a )} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]' )
47
1
'''simple docstring''' import os import sys import unittest lowerCamelCase : Optional[Any] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model_to_tester_mapping, get_test_to_tester_mapping, ) lowerCamelCase : str = os.path.join("tests", "models", "bert", "test_modeling_bert.py") lowerCamelCase : Any = os.path.join("tests", "models", "blip", "test_modeling_blip.py") class A__ ( unittest.TestCase ): def A ( self : Any ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =get_test_to_tester_mapping(_a ) _SCREAMING_SNAKE_CASE =get_test_to_tester_mapping(_a ) _SCREAMING_SNAKE_CASE ={'BertModelTest': 'BertModelTester'} _SCREAMING_SNAKE_CASE ={ 'BlipModelTest': 'BlipModelTester', 'BlipTextImageModelTest': 'BlipTextImageModelsModelTester', 'BlipTextModelTest': 'BlipTextModelTester', 'BlipTextRetrievalModelTest': 'BlipTextRetrievalModelTester', 'BlipVQAModelTest': 'BlipVQAModelTester', 'BlipVisionModelTest': 'BlipVisionModelTester', } self.assertEqual(get_test_info.to_json(_a ) , _a ) self.assertEqual(get_test_info.to_json(_a ) , _a ) def A ( self : List[str] ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =get_model_to_test_mapping(_a ) _SCREAMING_SNAKE_CASE =get_model_to_test_mapping(_a ) _SCREAMING_SNAKE_CASE ={ 'BertForMaskedLM': ['BertModelTest'], 'BertForMultipleChoice': ['BertModelTest'], 'BertForNextSentencePrediction': ['BertModelTest'], 'BertForPreTraining': ['BertModelTest'], 'BertForQuestionAnswering': ['BertModelTest'], 'BertForSequenceClassification': ['BertModelTest'], 'BertForTokenClassification': ['BertModelTest'], 'BertLMHeadModel': ['BertModelTest'], 'BertModel': ['BertModelTest'], } _SCREAMING_SNAKE_CASE ={ 'BlipForConditionalGeneration': ['BlipTextImageModelTest'], 'BlipForImageTextRetrieval': ['BlipTextRetrievalModelTest'], 'BlipForQuestionAnswering': ['BlipVQAModelTest'], 'BlipModel': ['BlipModelTest'], 'BlipTextModel': ['BlipTextModelTest'], 'BlipVisionModel': ['BlipVisionModelTest'], } self.assertEqual(get_test_info.to_json(_a ) , _a ) self.assertEqual(get_test_info.to_json(_a ) , _a ) def A ( self : Dict ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =get_model_to_tester_mapping(_a ) _SCREAMING_SNAKE_CASE =get_model_to_tester_mapping(_a ) _SCREAMING_SNAKE_CASE ={ 'BertForMaskedLM': ['BertModelTester'], 'BertForMultipleChoice': ['BertModelTester'], 'BertForNextSentencePrediction': ['BertModelTester'], 'BertForPreTraining': ['BertModelTester'], 'BertForQuestionAnswering': ['BertModelTester'], 'BertForSequenceClassification': ['BertModelTester'], 'BertForTokenClassification': ['BertModelTester'], 'BertLMHeadModel': ['BertModelTester'], 'BertModel': ['BertModelTester'], } _SCREAMING_SNAKE_CASE ={ 'BlipForConditionalGeneration': ['BlipTextImageModelsModelTester'], 'BlipForImageTextRetrieval': ['BlipTextRetrievalModelTester'], 'BlipForQuestionAnswering': ['BlipVQAModelTester'], 'BlipModel': ['BlipModelTester'], 'BlipTextModel': ['BlipTextModelTester'], 'BlipVisionModel': ['BlipVisionModelTester'], } self.assertEqual(get_test_info.to_json(_a ) , _a ) self.assertEqual(get_test_info.to_json(_a ) , _a )
47
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase : Dict = logging.get_logger(__name__) lowerCamelCase : List[Any] = { "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json", } class A__ ( A__ ): A__ = 'deta' A__ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Tuple , _a : Optional[int]=None , _a : int=900 , _a : Optional[Any]=2048 , _a : int=6 , _a : Tuple=2048 , _a : Optional[int]=8 , _a : Any=6 , _a : str=1024 , _a : int=8 , _a : int=0.0 , _a : Optional[Any]=True , _a : Tuple="relu" , _a : Union[str, Any]=256 , _a : Tuple=0.1 , _a : str=0.0 , _a : Dict=0.0 , _a : Tuple=0.02 , _a : Union[str, Any]=1.0 , _a : Any=True , _a : Tuple=False , _a : List[Any]="sine" , _a : str=5 , _a : List[Any]=4 , _a : str=4 , _a : Union[str, Any]=True , _a : Optional[int]=300 , _a : Dict=True , _a : List[Any]=True , _a : List[Any]=1 , _a : List[str]=5 , _a : int=2 , _a : Dict=1 , _a : str=1 , _a : Optional[Any]=5 , _a : Union[str, Any]=2 , _a : List[str]=0.1 , _a : List[Any]=0.25 , **_a : Union[str, Any] , ) -> List[str]: '''simple docstring''' if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) _SCREAMING_SNAKE_CASE =CONFIG_MAPPING['resnet'](out_features=['stage2', 'stage3', 'stage4'] ) else: if isinstance(_a , _a ): _SCREAMING_SNAKE_CASE =backbone_config.pop('model_type' ) _SCREAMING_SNAKE_CASE =CONFIG_MAPPING[backbone_model_type] _SCREAMING_SNAKE_CASE =config_class.from_dict(_a ) _SCREAMING_SNAKE_CASE =backbone_config _SCREAMING_SNAKE_CASE =num_queries _SCREAMING_SNAKE_CASE =max_position_embeddings _SCREAMING_SNAKE_CASE =d_model _SCREAMING_SNAKE_CASE =encoder_ffn_dim _SCREAMING_SNAKE_CASE =encoder_layers _SCREAMING_SNAKE_CASE =encoder_attention_heads _SCREAMING_SNAKE_CASE =decoder_ffn_dim _SCREAMING_SNAKE_CASE =decoder_layers _SCREAMING_SNAKE_CASE =decoder_attention_heads _SCREAMING_SNAKE_CASE =dropout _SCREAMING_SNAKE_CASE =attention_dropout _SCREAMING_SNAKE_CASE =activation_dropout _SCREAMING_SNAKE_CASE =activation_function _SCREAMING_SNAKE_CASE =init_std _SCREAMING_SNAKE_CASE =init_xavier_std _SCREAMING_SNAKE_CASE =encoder_layerdrop _SCREAMING_SNAKE_CASE =auxiliary_loss _SCREAMING_SNAKE_CASE =position_embedding_type # deformable attributes _SCREAMING_SNAKE_CASE =num_feature_levels _SCREAMING_SNAKE_CASE =encoder_n_points _SCREAMING_SNAKE_CASE =decoder_n_points _SCREAMING_SNAKE_CASE =two_stage _SCREAMING_SNAKE_CASE =two_stage_num_proposals _SCREAMING_SNAKE_CASE =with_box_refine _SCREAMING_SNAKE_CASE =assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError('If two_stage is True, with_box_refine must be True.' ) # Hungarian matcher _SCREAMING_SNAKE_CASE =class_cost _SCREAMING_SNAKE_CASE =bbox_cost _SCREAMING_SNAKE_CASE =giou_cost # Loss coefficients _SCREAMING_SNAKE_CASE =mask_loss_coefficient _SCREAMING_SNAKE_CASE =dice_loss_coefficient _SCREAMING_SNAKE_CASE =bbox_loss_coefficient _SCREAMING_SNAKE_CASE =giou_loss_coefficient _SCREAMING_SNAKE_CASE =eos_coefficient _SCREAMING_SNAKE_CASE =focal_alpha super().__init__(is_encoder_decoder=_a , **_a ) @property def A ( self : Dict ) -> int: '''simple docstring''' return self.encoder_attention_heads @property def A ( self : List[Any] ) -> int: '''simple docstring''' return self.d_model def A ( self : Optional[int] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =copy.deepcopy(self.__dict__ ) _SCREAMING_SNAKE_CASE =self.backbone_config.to_dict() _SCREAMING_SNAKE_CASE =self.__class__.model_type return output
47
1
'''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 A__ : def __init__( self : Optional[int] , _a : List[str] , _a : List[Any]=13 , _a : str=7 , _a : str=True , _a : Any=True , _a : Tuple=True , _a : Dict=True , _a : str=99 , _a : int=32 , _a : Dict=2 , _a : Optional[int]=4 , _a : Any=37 , _a : List[Any]="gelu" , _a : Optional[int]=0.1 , _a : List[Any]=0.1 , _a : Optional[Any]=512 , _a : List[str]=16 , _a : Optional[Any]=2 , _a : List[str]=0.02 , _a : int=3 , _a : List[str]=4 , _a : Union[str, Any]=None , ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =parent _SCREAMING_SNAKE_CASE =13 _SCREAMING_SNAKE_CASE =7 _SCREAMING_SNAKE_CASE =True _SCREAMING_SNAKE_CASE =True _SCREAMING_SNAKE_CASE =True _SCREAMING_SNAKE_CASE =True _SCREAMING_SNAKE_CASE =99 _SCREAMING_SNAKE_CASE =32 _SCREAMING_SNAKE_CASE =2 _SCREAMING_SNAKE_CASE =4 _SCREAMING_SNAKE_CASE =37 _SCREAMING_SNAKE_CASE ='gelu' _SCREAMING_SNAKE_CASE =0.1 _SCREAMING_SNAKE_CASE =0.1 _SCREAMING_SNAKE_CASE =512 _SCREAMING_SNAKE_CASE =16 _SCREAMING_SNAKE_CASE =2 _SCREAMING_SNAKE_CASE =0.02 _SCREAMING_SNAKE_CASE =3 _SCREAMING_SNAKE_CASE =4 _SCREAMING_SNAKE_CASE =None def A ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE =None if self.use_input_mask: _SCREAMING_SNAKE_CASE =random_attention_mask([self.batch_size, self.seq_length] ) _SCREAMING_SNAKE_CASE =None if self.use_token_type_ids: _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =None if self.use_labels: _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] , self.num_choices ) _SCREAMING_SNAKE_CASE =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=_a , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def A ( self : str , _a : Optional[Any] , _a : Optional[Any] , _a : int , _a : str , _a : List[Any] , _a : Optional[int] , _a : Any ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =TFRoFormerModel(config=_a ) _SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} _SCREAMING_SNAKE_CASE =[input_ids, input_mask] _SCREAMING_SNAKE_CASE =model(_a ) _SCREAMING_SNAKE_CASE =model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def A ( self : List[Any] , _a : str , _a : Dict , _a : List[str] , _a : List[Any] , _a : Optional[Any] , _a : int , _a : List[Any] ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =True _SCREAMING_SNAKE_CASE =TFRoFormerForCausalLM(config=_a ) _SCREAMING_SNAKE_CASE ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } _SCREAMING_SNAKE_CASE =model(_a )['logits'] self.parent.assertListEqual( list(prediction_scores.numpy().shape ) , [self.batch_size, self.seq_length, self.vocab_size] ) def A ( self : Tuple , _a : Any , _a : Dict , _a : Optional[Any] , _a : str , _a : List[str] , _a : List[str] , _a : Tuple ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =TFRoFormerForMaskedLM(config=_a ) _SCREAMING_SNAKE_CASE ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } _SCREAMING_SNAKE_CASE =model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def A ( self : Optional[int] , _a : Optional[int] , _a : Union[str, Any] , _a : str , _a : Tuple , _a : Tuple , _a : Tuple , _a : Union[str, Any] ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.num_labels _SCREAMING_SNAKE_CASE =TFRoFormerForSequenceClassification(config=_a ) _SCREAMING_SNAKE_CASE ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } _SCREAMING_SNAKE_CASE =model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def A ( self : Any , _a : List[Any] , _a : Dict , _a : List[str] , _a : Any , _a : Tuple , _a : str , _a : List[Any] ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.num_choices _SCREAMING_SNAKE_CASE =TFRoFormerForMultipleChoice(config=_a ) _SCREAMING_SNAKE_CASE =tf.tile(tf.expand_dims(_a , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE =tf.tile(tf.expand_dims(_a , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE =tf.tile(tf.expand_dims(_a , 1 ) , (1, self.num_choices, 1) ) _SCREAMING_SNAKE_CASE ={ 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } _SCREAMING_SNAKE_CASE =model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def A ( self : Tuple , _a : str , _a : Union[str, Any] , _a : Union[str, Any] , _a : Any , _a : List[Any] , _a : Dict , _a : List[str] ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.num_labels _SCREAMING_SNAKE_CASE =TFRoFormerForTokenClassification(config=_a ) _SCREAMING_SNAKE_CASE ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } _SCREAMING_SNAKE_CASE =model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def A ( self : str , _a : Any , _a : str , _a : Optional[Any] , _a : Optional[int] , _a : str , _a : Any , _a : Optional[int] ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =TFRoFormerForQuestionAnswering(config=_a ) _SCREAMING_SNAKE_CASE ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } _SCREAMING_SNAKE_CASE =model(_a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def A ( self : Tuple ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() ( ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ) =config_and_inputs _SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class A__ ( A__ , A__ , unittest.TestCase ): A__ = ( ( TFRoFormerModel, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerForMultipleChoice, ) if is_tf_available() else () ) A__ = ( { '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 {} ) A__ = False A__ = False def A ( self : Union[str, Any] , _a : List[str] , _a : int , _a : Optional[int] , _a : List[Any] , _a : Dict ) -> Tuple: '''simple docstring''' if pipeline_test_casse_name == "TextGenerationPipelineTests": return True return False def A ( self : Any ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =TFRoFormerModelTester(self ) _SCREAMING_SNAKE_CASE =ConfigTester(self , config_class=_a , hidden_size=37 ) def A ( self : List[str] ) -> Optional[Any]: '''simple docstring''' self.config_tester.run_common_tests() def A ( self : Optional[int] ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def A ( self : int ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_a ) def A ( self : Tuple ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head(*_a ) def A ( self : List[str] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_a ) def A ( self : Optional[int] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_a ) def A ( self : int ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_a ) def A ( self : Any ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_a ) @slow def A ( self : Dict ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =TFRoFormerModel.from_pretrained('junnyu/roformer_chinese_base' ) self.assertIsNotNone(_a ) @require_tf class A__ ( unittest.TestCase ): @slow def A ( self : int ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =TFRoFormerForMaskedLM.from_pretrained('junnyu/roformer_chinese_base' ) _SCREAMING_SNAKE_CASE =tf.constant([[0, 1, 2, 3, 4, 5]] ) _SCREAMING_SNAKE_CASE =model(_a )[0] # TODO Replace vocab size _SCREAMING_SNAKE_CASE =5_0000 _SCREAMING_SNAKE_CASE =[1, 6, vocab_size] self.assertEqual(output.shape , _a ) print(output[:, :3, :3] ) # TODO Replace values below with what was printed above. _SCREAMING_SNAKE_CASE =tf.constant( [ [ [-0.12_05_33_41, -1.0_26_49_01, 0.29_22_19_46], [-1.5_13_37_83, 0.19_74_33, 0.15_19_06_07], [-5.0_13_54_03, -3.90_02_56, -0.84_03_87_64], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , _a , atol=1e-4 ) @require_tf class A__ ( unittest.TestCase ): A__ = 1E-4 def A ( self : Dict ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =tf.constant([[4, 10]] ) _SCREAMING_SNAKE_CASE =TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 , embedding_dim=6 ) _SCREAMING_SNAKE_CASE =emba(input_ids.shape ) _SCREAMING_SNAKE_CASE =tf.constant( [[0.00_00, 0.00_00, 0.00_00, 1.00_00, 1.00_00, 1.00_00], [0.84_15, 0.04_64, 0.00_22, 0.54_03, 0.99_89, 1.00_00]] ) tf.debugging.assert_near(_a , _a , atol=self.tolerance ) def A ( self : Optional[Any] ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =tf.constant( [ [0.00_00, 0.00_00, 0.00_00, 0.00_00, 0.00_00], [0.84_15, 0.82_19, 0.80_20, 0.78_19, 0.76_17], [0.90_93, 0.93_64, 0.95_81, 0.97_49, 0.98_70], ] ) _SCREAMING_SNAKE_CASE =TFRoFormerSinusoidalPositionalEmbedding(num_positions=512 , embedding_dim=512 ) emba([2, 16, 512] ) _SCREAMING_SNAKE_CASE =emba.weight[:3, :5] tf.debugging.assert_near(_a , _a , atol=self.tolerance ) @require_tf class A__ ( unittest.TestCase ): A__ = 1E-4 def A ( self : Tuple ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa ) , shape=(2, 12, 16, 64) ) / 100 _SCREAMING_SNAKE_CASE =-tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa ) , shape=(2, 12, 16, 64) ) / 100 _SCREAMING_SNAKE_CASE =TFRoFormerSinusoidalPositionalEmbedding(num_positions=32 , embedding_dim=64 ) _SCREAMING_SNAKE_CASE =embed_positions([2, 16, 768] )[None, None, :, :] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =TFRoFormerSelfAttention.apply_rotary_position_embeddings( _a , _a , _a ) _SCREAMING_SNAKE_CASE =tf.constant( [ [0.00_00, 0.01_00, 0.02_00, 0.03_00, 0.04_00, 0.05_00, 0.06_00, 0.07_00], [-0.20_12, 0.88_97, 0.02_63, 0.94_01, 0.20_74, 0.94_63, 0.34_81, 0.93_43], [-1.70_57, 0.62_71, -1.21_45, 1.38_97, -0.63_03, 1.76_47, -0.11_73, 1.89_85], [-2.17_31, -1.63_97, -2.73_58, 0.28_54, -2.18_40, 1.71_83, -1.30_18, 2.48_71], [0.27_17, -3.61_73, -2.92_06, -2.19_88, -3.66_38, 0.38_58, -2.91_55, 2.29_80], [3.98_59, -2.15_80, -0.79_84, -4.49_04, -4.11_81, -2.02_52, -4.47_82, 1.12_53], ] ) _SCREAMING_SNAKE_CASE =tf.constant( [ [0.00_00, -0.01_00, -0.02_00, -0.03_00, -0.04_00, -0.05_00, -0.06_00, -0.07_00], [0.20_12, -0.88_97, -0.02_63, -0.94_01, -0.20_74, -0.94_63, -0.34_81, -0.93_43], [1.70_57, -0.62_71, 1.21_45, -1.38_97, 0.63_03, -1.76_47, 0.11_73, -1.89_85], [2.17_31, 1.63_97, 2.73_58, -0.28_54, 2.18_40, -1.71_83, 1.30_18, -2.48_71], [-0.27_17, 3.61_73, 2.92_06, 2.19_88, 3.66_38, -0.38_58, 2.91_55, -2.29_80], [-3.98_59, 2.15_80, 0.79_84, 4.49_04, 4.11_81, 2.02_52, 4.47_82, -1.12_53], ] ) tf.debugging.assert_near(query_layer[0, 0, :6, :8] , _a , atol=self.tolerance ) tf.debugging.assert_near(key_layer[0, 0, :6, :8] , _a , atol=self.tolerance )
47
'''simple docstring''' import numpy as np from PIL import Image def _lowerCAmelCase ( _UpperCamelCase : np.ndarray , _UpperCamelCase : int , _UpperCamelCase : int ) -> np.ndarray: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 # compute the shape of the output matrix _SCREAMING_SNAKE_CASE =(arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape _SCREAMING_SNAKE_CASE =np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix _SCREAMING_SNAKE_CASE =np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 return updated_arr def _lowerCAmelCase ( _UpperCamelCase : np.ndarray , _UpperCamelCase : int , _UpperCamelCase : int ) -> np.ndarray: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 # compute the shape of the output matrix _SCREAMING_SNAKE_CASE =(arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape _SCREAMING_SNAKE_CASE =np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix _SCREAMING_SNAKE_CASE =int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name="avgpooling", verbose=True) # Loading the image lowerCamelCase : Optional[Any] = Image.open("path_to_image") # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
47
1
'''simple docstring''' import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json lowerCamelCase : List[Any] = "sshleifer/mar_enro_6_3_student" class A__ ( A__ ): def A ( self : Tuple ) -> Tuple: '''simple docstring''' super().setUp() _SCREAMING_SNAKE_CASE =cached_path( 'https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz' , extract_compressed_file=_a , ) _SCREAMING_SNAKE_CASE =f"{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k" @slow @require_torch_gpu def A ( self : List[Any] ) -> str: '''simple docstring''' MarianMTModel.from_pretrained(_a ) @slow @require_torch_gpu def A ( self : int ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE ={ '$MAX_LEN': 64, '$BS': 64, '$GAS': 1, '$ENRO_DIR': self.data_dir, 'facebook/mbart-large-cc25': MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", '--learning_rate=3e-5': '--learning_rate 3e-4', '--num_train_epochs 6': '--num_train_epochs 1', } # Clean up bash script _SCREAMING_SNAKE_CASE =(self.test_file_dir / 'train_mbart_cc25_enro.sh').open().read().split('finetune.py' )[1].strip() _SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' , '' ).strip().replace('"$@"' , '' ) for k, v in env_vars_to_replace.items(): _SCREAMING_SNAKE_CASE =bash_script.replace(_a , str(_a ) ) _SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") _SCREAMING_SNAKE_CASE =f"\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n ".split() # XXX: args.gpus > 1 : handle multi_gpu in the future _SCREAMING_SNAKE_CASE =['finetune.py'] + bash_script.split() + args with patch.object(_a , 'argv' , _a ): _SCREAMING_SNAKE_CASE =argparse.ArgumentParser() _SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(_a ) _SCREAMING_SNAKE_CASE =SummarizationModule.add_model_specific_args(_a , os.getcwd() ) _SCREAMING_SNAKE_CASE =parser.parse_args() _SCREAMING_SNAKE_CASE =main(_a ) # Check metrics _SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) _SCREAMING_SNAKE_CASE =metrics['val'][0] _SCREAMING_SNAKE_CASE =metrics['val'][-1] self.assertEqual(len(metrics['val'] ) , (args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f"val_avg_{model.val_metric}"] , _a ) self.assertGreater(last_step_stats['val_avg_gen_time'] , 0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats['val_avg_gen_time'] , 1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats['val_avg_bleu'] - first_step_stats['val_avg_bleu'] , 2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats['val_avg_bleu'] , 17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics['val'][-1]['val_avg_bleu'] - metrics['test'][-1]['test_avg_bleu'] ) , 1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict _SCREAMING_SNAKE_CASE =os.listdir(_a ) _SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] _SCREAMING_SNAKE_CASE =os.path.join(args.output_dir , _a ) _SCREAMING_SNAKE_CASE =torch.load(_a , map_location='cpu' ) _SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: _SCREAMING_SNAKE_CASE ={os.path.basename(_a ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1 class A__ ( A__ ): @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def A ( self : List[str] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =f"{self.test_file_dir_str}/test_data/wmt_en_ro" _SCREAMING_SNAKE_CASE ={ '--fp16_opt_level=O1': '', '$MAX_LEN': 128, '$BS': 16, '$GAS': 1, '$ENRO_DIR': data_dir, '$m': 'sshleifer/student_marian_en_ro_6_1', 'val_check_interval=0.25': 'val_check_interval=1.0', } # Clean up bash script _SCREAMING_SNAKE_CASE =( (self.test_file_dir / 'distil_marian_no_teacher.sh').open().read().split('distillation.py' )[1].strip() ) _SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' , '' ).strip().replace('"$@"' , '' ) _SCREAMING_SNAKE_CASE =bash_script.replace('--fp16 ' , ' ' ) for k, v in env_vars_to_replace.items(): _SCREAMING_SNAKE_CASE =bash_script.replace(_a , str(_a ) ) _SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() _SCREAMING_SNAKE_CASE =bash_script.replace('--fp16' , '' ) _SCREAMING_SNAKE_CASE =6 _SCREAMING_SNAKE_CASE =( ['distillation.py'] + bash_script.split() + [ f"--output_dir={output_dir}", '--gpus=1', '--learning_rate=1e-3', f"--num_train_epochs={epochs}", '--warmup_steps=10', '--val_check_interval=1.0', '--do_predict', ] ) with patch.object(_a , 'argv' , _a ): _SCREAMING_SNAKE_CASE =argparse.ArgumentParser() _SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(_a ) _SCREAMING_SNAKE_CASE =SummarizationDistiller.add_model_specific_args(_a , os.getcwd() ) _SCREAMING_SNAKE_CASE =parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu _SCREAMING_SNAKE_CASE =distill_main(_a ) # Check metrics _SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) _SCREAMING_SNAKE_CASE =metrics['val'][0] _SCREAMING_SNAKE_CASE =metrics['val'][-1] assert len(metrics['val'] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f"val_avg_{model.val_metric}"] , _a ) # check lightning ckpt can be loaded and has a reasonable statedict _SCREAMING_SNAKE_CASE =os.listdir(_a ) _SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] _SCREAMING_SNAKE_CASE =os.path.join(args.output_dir , _a ) _SCREAMING_SNAKE_CASE =torch.load(_a , map_location='cpu' ) _SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: _SCREAMING_SNAKE_CASE ={os.path.basename(_a ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1
47
'''simple docstring''' import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _lowerCAmelCase ( ) -> Any: """simple docstring""" _SCREAMING_SNAKE_CASE =ArgumentParser( description=( 'PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes' ) ) # Optional arguments for the launch helper parser.add_argument('--num_cores' , type=_UpperCamelCase , default=1 , help='Number of TPU cores to use (1 or 8).' ) # positional parser.add_argument( 'training_script' , type=_UpperCamelCase , help=( 'The full path to the single TPU training ' 'program/script to be launched in parallel, ' 'followed by all the arguments for the ' 'training script' ) , ) # rest from the training program parser.add_argument('training_script_args' , nargs=_UpperCamelCase ) return parser.parse_args() def _lowerCAmelCase ( ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =parse_args() # Import training_script as a module. _SCREAMING_SNAKE_CASE =Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) _SCREAMING_SNAKE_CASE =script_fpath.stem _SCREAMING_SNAKE_CASE =importlib.import_module(_UpperCamelCase ) # Patch sys.argv _SCREAMING_SNAKE_CASE =[args.training_script] + args.training_script_args + ['--tpu_num_cores', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
47
1
'''simple docstring''' def _lowerCAmelCase ( _UpperCamelCase : Dict ) -> List[Any]: """simple docstring""" return [ { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], }, { 0: [6], 1: [9], 2: [4, 5], 3: [4], 4: [2, 3], 5: [2], 6: [0, 7], 7: [6], 8: [], 9: [1], }, { 0: [4], 1: [6], 2: [], 3: [5, 6, 7], 4: [0, 6], 5: [3, 8, 9], 6: [1, 3, 4, 7], 7: [3, 6, 8, 9], 8: [5, 7], 9: [5, 7], }, { 0: [1, 3], 1: [0, 2, 4], 2: [1, 3, 4], 3: [0, 2, 4], 4: [1, 2, 3], }, ][index] def _lowerCAmelCase ( _UpperCamelCase : dict[int, list[int]] ) -> list[tuple[int, int]]: """simple docstring""" _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =len(_UpperCamelCase ) # No of vertices in graph _SCREAMING_SNAKE_CASE =[0] * n _SCREAMING_SNAKE_CASE =[False] * n def dfs(_UpperCamelCase : int , _UpperCamelCase : Optional[int] , _UpperCamelCase : Optional[int] , _UpperCamelCase : Dict ): _SCREAMING_SNAKE_CASE =True _SCREAMING_SNAKE_CASE =id_ id_ += 1 for to in graph[at]: if to == parent: pass elif not visited[to]: dfs(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , id_ ) _SCREAMING_SNAKE_CASE =min(low[at] , low[to] ) if id_ <= low[to]: bridges.append((at, to) if at < to else (to, at) ) else: # This edge is a back edge and cannot be a bridge _SCREAMING_SNAKE_CASE =min(low[at] , low[to] ) _SCREAMING_SNAKE_CASE =[] for i in range(_UpperCamelCase ): if not visited[i]: dfs(_UpperCamelCase , -1 , _UpperCamelCase , id_ ) return bridges if __name__ == "__main__": import doctest doctest.testmod()
47
'''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. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class A__ ( A__ ): A__ = ( 'This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.' 'It takes two arguments named `image` which should be the original image, and `label` which should be a text ' 'describing the elements what should be identified in the segmentation mask. The tool returns the mask.' ) A__ = 'CIDAS/clipseg-rd64-refined' A__ = 'image_segmenter' A__ = CLIPSegForImageSegmentation A__ = ['image', 'text'] A__ = ['image'] def __init__( self : Any , *_a : Dict , **_a : str ) -> Any: '''simple docstring''' requires_backends(self , ['vision'] ) super().__init__(*_a , **_a ) def A ( self : int , _a : "Image" , _a : str ) -> Optional[Any]: '''simple docstring''' return self.pre_processor(text=[label] , images=[image] , padding=_a , return_tensors='pt' ) def A ( self : Dict , _a : Dict ) -> str: '''simple docstring''' with torch.no_grad(): _SCREAMING_SNAKE_CASE =self.model(**_a ).logits return logits def A ( self : Any , _a : str ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =outputs.cpu().detach().numpy() _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =1 return Image.fromarray((array * 255).astype(np.uinta ) )
47
1
'''simple docstring''' from __future__ import annotations from typing import Any class A__ : def __init__( self : List[str] , _a : int = 6 ) -> None: '''simple docstring''' _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =None self.create_linked_list(_a ) def A ( self : Dict , _a : int ) -> None: '''simple docstring''' _SCREAMING_SNAKE_CASE =Node() _SCREAMING_SNAKE_CASE =current_node _SCREAMING_SNAKE_CASE =current_node _SCREAMING_SNAKE_CASE =current_node for _ in range(1 , _a ): _SCREAMING_SNAKE_CASE =Node() _SCREAMING_SNAKE_CASE =current_node _SCREAMING_SNAKE_CASE =previous_node _SCREAMING_SNAKE_CASE =current_node _SCREAMING_SNAKE_CASE =self.front _SCREAMING_SNAKE_CASE =previous_node def A ( self : Any ) -> bool: '''simple docstring''' return ( self.front == self.rear and self.front is not None and self.front.data is None ) def A ( self : Any ) -> Any | None: '''simple docstring''' self.check_can_perform_operation() return self.front.data if self.front else None def A ( self : List[str] , _a : Any ) -> None: '''simple docstring''' if self.rear is None: return self.check_is_full() if not self.is_empty(): _SCREAMING_SNAKE_CASE =self.rear.next if self.rear: _SCREAMING_SNAKE_CASE =data def A ( self : Optional[int] ) -> Any: '''simple docstring''' self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: _SCREAMING_SNAKE_CASE =self.front.data _SCREAMING_SNAKE_CASE =None return data _SCREAMING_SNAKE_CASE =self.front _SCREAMING_SNAKE_CASE =old_front.next _SCREAMING_SNAKE_CASE =old_front.data _SCREAMING_SNAKE_CASE =None return data def A ( self : Union[str, Any] ) -> None: '''simple docstring''' if self.is_empty(): raise Exception('Empty Queue' ) def A ( self : str ) -> None: '''simple docstring''' if self.rear and self.rear.next == self.front: raise Exception('Full Queue' ) class A__ : def __init__( self : List[Any] ) -> None: '''simple docstring''' _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =None if __name__ == "__main__": import doctest doctest.testmod()
47
'''simple docstring''' from __future__ import annotations import math def _lowerCAmelCase ( _UpperCamelCase : int ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_UpperCamelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowerCAmelCase ( _UpperCamelCase : int ) -> list[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =str(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =[n] for i in range(1 , len(_UpperCamelCase ) ): list_nums.append(int(str_num[i:] ) ) list_nums.append(int(str_num[:-i] ) ) return list_nums def _lowerCAmelCase ( _UpperCamelCase : int ) -> bool: """simple docstring""" if len(str(_UpperCamelCase ) ) > 3: if not is_prime(int(str(_UpperCamelCase )[-3:] ) ) or not is_prime(int(str(_UpperCamelCase )[:3] ) ): return False return True def _lowerCAmelCase ( _UpperCamelCase : int = 11 ) -> list[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =13 while len(_UpperCamelCase ) != count: if validate(_UpperCamelCase ): _SCREAMING_SNAKE_CASE =list_truncated_nums(_UpperCamelCase ) if all(is_prime(_UpperCamelCase ) for i in list_nums ): list_truncated_primes.append(_UpperCamelCase ) num += 2 return list_truncated_primes def _lowerCAmelCase ( ) -> int: """simple docstring""" return sum(compute_truncated_primes(11 ) ) if __name__ == "__main__": print(f'''{sum(compute_truncated_primes(1_1)) = }''')
47
1
'''simple docstring''' from collections.abc import Callable import numpy as np def _lowerCAmelCase ( _UpperCamelCase : Callable , _UpperCamelCase : float , _UpperCamelCase : float , _UpperCamelCase : float , _UpperCamelCase : float ) -> np.array: """simple docstring""" _SCREAMING_SNAKE_CASE =int(np.ceil((x_end - xa) / step_size ) ) _SCREAMING_SNAKE_CASE =np.zeros((n + 1,) ) _SCREAMING_SNAKE_CASE =ya _SCREAMING_SNAKE_CASE =xa for k in range(_UpperCamelCase ): _SCREAMING_SNAKE_CASE =y[k] + step_size * ode_func(_UpperCamelCase , y[k] ) _SCREAMING_SNAKE_CASE =y[k] + ( (step_size / 2) * (ode_func(_UpperCamelCase , y[k] ) + ode_func(x + step_size , _UpperCamelCase )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
47
'''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: lowerCamelCase : int = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class A__ ( unittest.TestCase ): def __init__( self : List[str] , _a : List[Any] , _a : List[str]=7 , _a : List[str]=3 , _a : Tuple=18 , _a : Tuple=30 , _a : str=400 , _a : Tuple=None , _a : Union[str, Any]=True , _a : List[str]=True , _a : Optional[int]=None , ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =size if size is not None else {'height': 20, 'width': 20} _SCREAMING_SNAKE_CASE =parent _SCREAMING_SNAKE_CASE =batch_size _SCREAMING_SNAKE_CASE =num_channels _SCREAMING_SNAKE_CASE =image_size _SCREAMING_SNAKE_CASE =min_resolution _SCREAMING_SNAKE_CASE =max_resolution _SCREAMING_SNAKE_CASE =size _SCREAMING_SNAKE_CASE =do_normalize _SCREAMING_SNAKE_CASE =do_convert_rgb _SCREAMING_SNAKE_CASE =[512, 1024, 2048, 4096] _SCREAMING_SNAKE_CASE =patch_size if patch_size is not None else {'height': 16, 'width': 16} def A ( self : Any ) -> List[str]: '''simple docstring''' return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def A ( self : int ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE ='https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg' _SCREAMING_SNAKE_CASE =Image.open(requests.get(_a , stream=_a ).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 A__ ( A__ , unittest.TestCase ): A__ = PixaStructImageProcessor if is_vision_available() else None def A ( self : Dict ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =PixaStructImageProcessingTester(self ) @property def A ( self : Optional[Any] ) -> int: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def A ( self : Any ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_a , 'do_normalize' ) ) self.assertTrue(hasattr(_a , 'do_convert_rgb' ) ) def A ( self : Any ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processor_tester.prepare_dummy_image() _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) _SCREAMING_SNAKE_CASE =2048 _SCREAMING_SNAKE_CASE =image_processor(_a , return_tensors='pt' , max_patches=_a ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.06_06 ) , atol=1e-3 , rtol=1e-3 ) ) def A ( self : Any ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PIL images _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input _SCREAMING_SNAKE_CASE =( (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 _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def A ( self : List[str] ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PIL images _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input _SCREAMING_SNAKE_CASE =( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 _SCREAMING_SNAKE_CASE =True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(_a ): _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches _SCREAMING_SNAKE_CASE ='Hello' _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a , header_text=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a , header_text=_a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def A ( self : List[Any] ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , numpify=_a ) for image in image_inputs: self.assertIsInstance(_a , np.ndarray ) _SCREAMING_SNAKE_CASE =( (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 _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def A ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , torchify=_a ) for image in image_inputs: self.assertIsInstance(_a , torch.Tensor ) # Test not batched input _SCREAMING_SNAKE_CASE =( (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 _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a ).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 A__ ( A__ , unittest.TestCase ): A__ = PixaStructImageProcessor if is_vision_available() else None def A ( self : str ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =PixaStructImageProcessingTester(self , num_channels=4 ) _SCREAMING_SNAKE_CASE =3 @property def A ( self : List[str] ) -> Optional[Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def A ( self : List[str] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_a , 'do_normalize' ) ) self.assertTrue(hasattr(_a , 'do_convert_rgb' ) ) def A ( self : Dict ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PIL images _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input _SCREAMING_SNAKE_CASE =( (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 _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
47
1
'''simple docstring''' import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version lowerCamelCase : List[Any] = version.parse(importlib_metadata.version("nltk")) if NLTK_VERSION >= version.Version("3.6.4"): from nltk import word_tokenize lowerCamelCase : Any = "\\n@inproceedings{banarjee2005,\n title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n author = {Banerjee, Satanjeev and Lavie, Alon},\n booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n month = jun,\n year = {2005},\n address = {Ann Arbor, Michigan},\n publisher = {Association for Computational Linguistics},\n url = {https://www.aclweb.org/anthology/W05-0909},\n pages = {65--72},\n}\n" lowerCamelCase : Optional[Any] = "\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n" lowerCamelCase : Optional[Any] = "\nComputes METEOR score of translated segments against one or more references.\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n 'meteor': meteor score.\nExamples:\n\n >>> meteor = datasets.load_metric('meteor')\n >>> predictions = [\"It is a guide to action which ensures that the military always obeys the commands of the party\"]\n >>> references = [\"It is a guide to action that ensures that the military will forever heed Party commands\"]\n >>> results = meteor.compute(predictions=predictions, references=references)\n >>> print(round(results[\"meteor\"], 4))\n 0.6944\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def A ( self : Tuple ) -> str: '''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/nltk/nltk/blob/develop/nltk/translate/meteor_score.py'] , reference_urls=[ 'https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score', 'https://en.wikipedia.org/wiki/METEOR', ] , ) def A ( self : Union[str, Any] , _a : Union[str, Any] ) -> Optional[int]: '''simple docstring''' import nltk nltk.download('wordnet' ) if NLTK_VERSION >= version.Version('3.6.5' ): nltk.download('punkt' ) if NLTK_VERSION >= version.Version('3.6.6' ): nltk.download('omw-1.4' ) def A ( self : int , _a : Tuple , _a : List[str] , _a : List[str]=0.9 , _a : Dict=3 , _a : Optional[int]=0.5 ) -> Optional[int]: '''simple docstring''' if NLTK_VERSION >= version.Version('3.6.5' ): _SCREAMING_SNAKE_CASE =[ meteor_score.single_meteor_score( word_tokenize(_a ) , word_tokenize(_a ) , alpha=_a , beta=_a , gamma=_a ) for ref, pred in zip(_a , _a ) ] else: _SCREAMING_SNAKE_CASE =[ meteor_score.single_meteor_score(_a , _a , alpha=_a , beta=_a , gamma=_a ) for ref, pred in zip(_a , _a ) ] return {"meteor": np.mean(_a )}
47
'''simple docstring''' import copy import re class A__ : A__ = 'hp' A__ = {} A__ = None @classmethod def A ( cls : Optional[Any] , _a : Optional[Any] , _a : Any ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =prefix _SCREAMING_SNAKE_CASE =defaults cls.build_naming_info() @staticmethod def A ( _a : Optional[Any] , _a : List[Any] ) -> Any: '''simple docstring''' if len(_a ) == 0: return "" _SCREAMING_SNAKE_CASE =None if any(char.isdigit() for char in word ): raise Exception(f"Parameters should not contain numbers: '{word}' contains a number" ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(_a ) + 1 ): _SCREAMING_SNAKE_CASE =word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: _SCREAMING_SNAKE_CASE =prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(_a : str ): _SCREAMING_SNAKE_CASE ='' while integer != 0: _SCREAMING_SNAKE_CASE =chr(ord('A' ) + integer % 10 ) + s integer //= 10 return s _SCREAMING_SNAKE_CASE =0 while True: _SCREAMING_SNAKE_CASE =word + '#' + int_to_alphabetic(_a ) if sword in info["reverse_short_word"]: continue else: _SCREAMING_SNAKE_CASE =sword break _SCREAMING_SNAKE_CASE =short_word _SCREAMING_SNAKE_CASE =word return short_word @staticmethod def A ( _a : Optional[Any] , _a : int ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =param_name.split('_' ) _SCREAMING_SNAKE_CASE =[TrialShortNamer.shortname_for_word(_a , _a ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name _SCREAMING_SNAKE_CASE =['', '_'] for separator in separators: _SCREAMING_SNAKE_CASE =separator.join(_a ) if shortname not in info["reverse_short_param"]: _SCREAMING_SNAKE_CASE =shortname _SCREAMING_SNAKE_CASE =param_name return shortname return param_name @staticmethod def A ( _a : Dict , _a : int ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =TrialShortNamer.shortname_for_key(_a , _a ) _SCREAMING_SNAKE_CASE =short_name _SCREAMING_SNAKE_CASE =param_name @classmethod def A ( cls : Optional[int] ) -> Tuple: '''simple docstring''' if cls.NAMING_INFO is not None: return _SCREAMING_SNAKE_CASE ={ 'short_word': {}, 'reverse_short_word': {}, 'short_param': {}, 'reverse_short_param': {}, } _SCREAMING_SNAKE_CASE =list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(_a , _a ) _SCREAMING_SNAKE_CASE =info @classmethod def A ( cls : List[Any] , _a : int ) -> int: '''simple docstring''' cls.build_naming_info() assert cls.PREFIX is not None _SCREAMING_SNAKE_CASE =[copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(f"You should provide a default value for the param name {k} with value {v}" ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue _SCREAMING_SNAKE_CASE =cls.NAMING_INFO['short_param'][k] if isinstance(_a , _a ): _SCREAMING_SNAKE_CASE =1 if v else 0 _SCREAMING_SNAKE_CASE ='' if isinstance(_a , (int, float) ) else '-' _SCREAMING_SNAKE_CASE =f"{key}{sep}{v}" name.append(_a ) return "_".join(_a ) @classmethod def A ( cls : Optional[Any] , _a : List[Any] ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =repr[len(cls.PREFIX ) + 1 :] if repr == "": _SCREAMING_SNAKE_CASE =[] else: _SCREAMING_SNAKE_CASE =repr.split('_' ) _SCREAMING_SNAKE_CASE ={} for value in values: if "-" in value: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =value.split('-' ) else: _SCREAMING_SNAKE_CASE =re.sub('[0-9.]' , '' , _a ) _SCREAMING_SNAKE_CASE =float(re.sub('[^0-9.]' , '' , _a ) ) _SCREAMING_SNAKE_CASE =cls.NAMING_INFO['reverse_short_param'][p_k] _SCREAMING_SNAKE_CASE =p_v for k in cls.DEFAULTS: if k not in parameters: _SCREAMING_SNAKE_CASE =cls.DEFAULTS[k] return parameters
47
1
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class A__ ( A__ , unittest.TestCase ): A__ = ShapEPipeline A__ = ['prompt'] A__ = ['prompt'] A__ = [ 'num_images_per_prompt', 'num_inference_steps', 'generator', 'latents', 'guidance_scale', 'frame_size', 'output_type', 'return_dict', ] A__ = False @property def A ( self : int ) -> int: '''simple docstring''' return 32 @property def A ( self : Dict ) -> List[Any]: '''simple docstring''' return 32 @property def A ( self : int ) -> List[Any]: '''simple docstring''' return self.time_input_dim * 4 @property def A ( self : str ) -> Optional[Any]: '''simple docstring''' return 8 @property def A ( self : Union[str, Any] ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE =CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(_a ) @property def A ( self : Tuple ) -> int: '''simple docstring''' torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE ={ 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } _SCREAMING_SNAKE_CASE =PriorTransformer(**_a ) return model @property def A ( self : Dict ) -> Any: '''simple docstring''' torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE ={ 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } _SCREAMING_SNAKE_CASE =ShapERenderer(**_a ) return model def A ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.dummy_prior _SCREAMING_SNAKE_CASE =self.dummy_text_encoder _SCREAMING_SNAKE_CASE =self.dummy_tokenizer _SCREAMING_SNAKE_CASE =self.dummy_renderer _SCREAMING_SNAKE_CASE =HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=_a , clip_sample=_a , clip_sample_range=1.0 , ) _SCREAMING_SNAKE_CASE ={ 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def A ( self : int , _a : Optional[Any] , _a : Any=0 ) -> Union[str, Any]: '''simple docstring''' if str(_a ).startswith('mps' ): _SCREAMING_SNAKE_CASE =torch.manual_seed(_a ) else: _SCREAMING_SNAKE_CASE =torch.Generator(device=_a ).manual_seed(_a ) _SCREAMING_SNAKE_CASE ={ 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def A ( self : int ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE ='cpu' _SCREAMING_SNAKE_CASE =self.get_dummy_components() _SCREAMING_SNAKE_CASE =self.pipeline_class(**_a ) _SCREAMING_SNAKE_CASE =pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) _SCREAMING_SNAKE_CASE =pipe(**self.get_dummy_inputs(_a ) ) _SCREAMING_SNAKE_CASE =output.images[0] _SCREAMING_SNAKE_CASE =image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) _SCREAMING_SNAKE_CASE =np.array( [ 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def A ( self : Dict ) -> List[str]: '''simple docstring''' self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def A ( self : Optional[Any] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =torch_device == 'cpu' _SCREAMING_SNAKE_CASE =True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=_a , relax_max_difference=_a , ) def A ( self : str ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.get_dummy_components() _SCREAMING_SNAKE_CASE =self.pipeline_class(**_a ) _SCREAMING_SNAKE_CASE =pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) _SCREAMING_SNAKE_CASE =1 _SCREAMING_SNAKE_CASE =2 _SCREAMING_SNAKE_CASE =self.get_dummy_inputs(_a ) for key in inputs.keys(): if key in self.batch_params: _SCREAMING_SNAKE_CASE =batch_size * [inputs[key]] _SCREAMING_SNAKE_CASE =pipe(**_a , num_images_per_prompt=_a )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class A__ ( unittest.TestCase ): def A ( self : str ) -> Any: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def A ( self : Optional[Any] ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) _SCREAMING_SNAKE_CASE =ShapEPipeline.from_pretrained('openai/shap-e' ) _SCREAMING_SNAKE_CASE =pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) _SCREAMING_SNAKE_CASE =torch.Generator(device=_a ).manual_seed(0 ) _SCREAMING_SNAKE_CASE =pipe( 'a shark' , generator=_a , guidance_scale=15.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(_a , _a )
47
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version lowerCamelCase : Optional[int] = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt") @dataclass class A__ : A__ = field( default='cifar10' , metadata={'help': 'Name of a dataset from the datasets package'} ) A__ = field( default=A__ , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) A__ = field( default=A__ , metadata={'help': 'The column name of the images in the files.'} ) A__ = field(default=A__ , metadata={'help': 'A folder containing the training data.'} ) A__ = field(default=A__ , metadata={'help': 'A folder containing the validation data.'} ) A__ = field( default=0.15 , metadata={'help': 'Percent to split off of train for validation.'} ) A__ = field( default=A__ , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) A__ = field( default=A__ , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of evaluation examples to this ' 'value if set.' ) } , ) def A ( self : Union[str, Any] ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE ={} if self.train_dir is not None: _SCREAMING_SNAKE_CASE =self.train_dir if self.validation_dir is not None: _SCREAMING_SNAKE_CASE =self.validation_dir _SCREAMING_SNAKE_CASE =data_files if data_files else None @dataclass class A__ : A__ = field( default=A__ , metadata={ 'help': ( 'The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.' ) } , ) A__ = field( default=A__ , metadata={'help': 'Pretrained config name or path if not the same as model_name_or_path'} ) A__ = field( default=A__ , metadata={ 'help': ( 'Override some existing default config settings when a model is trained from scratch. Example: ' 'n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index' ) } , ) A__ = field( default=A__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from s3'} ) A__ = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) A__ = field(default=A__ , metadata={'help': 'Name or path of preprocessor config.'} ) A__ = field( default=A__ , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) A__ = field( default=0.75 , metadata={'help': 'The ratio of the number of masked tokens in the input sequence.'} ) A__ = field( default=A__ , metadata={'help': 'Whether or not to train with normalized pixel values as target.'} ) @dataclass class A__ ( A__ ): A__ = field( default=1E-3 , metadata={'help': 'Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'} ) def _lowerCAmelCase ( _UpperCamelCase : int ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE =torch.stack([example['pixel_values'] for example in examples] ) return {"pixel_values": pixel_values} def _lowerCAmelCase ( ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE =HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) 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. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('run_mae' , _UpperCamelCase , _UpperCamelCase ) # 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 )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _SCREAMING_SNAKE_CASE =training_args.get_process_log_level() logger.setLevel(_UpperCamelCase ) transformers.utils.logging.set_verbosity(_UpperCamelCase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # 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}" ) logger.info(f"Training/evaluation parameters {training_args}" ) # Detecting last checkpoint. _SCREAMING_SNAKE_CASE =None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _SCREAMING_SNAKE_CASE =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 and training_args.resume_from_checkpoint is 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.' ) # Initialize our dataset. _SCREAMING_SNAKE_CASE =load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. _SCREAMING_SNAKE_CASE =None if 'validation' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , _UpperCamelCase ) and data_args.train_val_split > 0.0: _SCREAMING_SNAKE_CASE =ds['train'].train_test_split(data_args.train_val_split ) _SCREAMING_SNAKE_CASE =split['train'] _SCREAMING_SNAKE_CASE =split['test'] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _SCREAMING_SNAKE_CASE ={ 'cache_dir': model_args.cache_dir, 'revision': model_args.model_revision, 'use_auth_token': True if model_args.use_auth_token else None, } if model_args.config_name: _SCREAMING_SNAKE_CASE =ViTMAEConfig.from_pretrained(model_args.config_name , **_UpperCamelCase ) elif model_args.model_name_or_path: _SCREAMING_SNAKE_CASE =ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **_UpperCamelCase ) else: _SCREAMING_SNAKE_CASE =ViTMAEConfig() logger.warning('You are instantiating a new config instance from scratch.' ) if model_args.config_overrides is not None: logger.info(f"Overriding config: {model_args.config_overrides}" ) config.update_from_string(model_args.config_overrides ) logger.info(f"New config: {config}" ) # adapt config config.update( { 'mask_ratio': model_args.mask_ratio, 'norm_pix_loss': model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: _SCREAMING_SNAKE_CASE =ViTImageProcessor.from_pretrained(model_args.image_processor_name , **_UpperCamelCase ) elif model_args.model_name_or_path: _SCREAMING_SNAKE_CASE =ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **_UpperCamelCase ) else: _SCREAMING_SNAKE_CASE =ViTImageProcessor() # create model if model_args.model_name_or_path: _SCREAMING_SNAKE_CASE =ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=_UpperCamelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('Training new model from scratch' ) _SCREAMING_SNAKE_CASE =ViTMAEForPreTraining(_UpperCamelCase ) if training_args.do_train: _SCREAMING_SNAKE_CASE =ds['train'].column_names else: _SCREAMING_SNAKE_CASE =ds['validation'].column_names if data_args.image_column_name is not None: _SCREAMING_SNAKE_CASE =data_args.image_column_name elif "image" in column_names: _SCREAMING_SNAKE_CASE ='image' elif "img" in column_names: _SCREAMING_SNAKE_CASE ='img' else: _SCREAMING_SNAKE_CASE =column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: _SCREAMING_SNAKE_CASE =image_processor.size['shortest_edge'] else: _SCREAMING_SNAKE_CASE =(image_processor.size['height'], image_processor.size['width']) _SCREAMING_SNAKE_CASE =Compose( [ Lambda(lambda _UpperCamelCase : img.convert('RGB' ) if img.mode != "RGB" else img ), RandomResizedCrop(_UpperCamelCase , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(_UpperCamelCase : Dict ): _SCREAMING_SNAKE_CASE =[transforms(_UpperCamelCase ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError('--do_train requires a train dataset' ) if data_args.max_train_samples is not None: _SCREAMING_SNAKE_CASE =ds['train'].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(_UpperCamelCase ) if training_args.do_eval: if "validation" not in ds: raise ValueError('--do_eval requires a validation dataset' ) if data_args.max_eval_samples is not None: _SCREAMING_SNAKE_CASE =( ds['validation'].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(_UpperCamelCase ) # Compute absolute learning rate _SCREAMING_SNAKE_CASE =( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: _SCREAMING_SNAKE_CASE =training_args.base_learning_rate * total_train_batch_size / 2_56 # Initialize our trainer _SCREAMING_SNAKE_CASE =Trainer( model=_UpperCamelCase , args=_UpperCamelCase , train_dataset=ds['train'] if training_args.do_train else None , eval_dataset=ds['validation'] if training_args.do_eval else None , tokenizer=_UpperCamelCase , data_collator=_UpperCamelCase , ) # Training if training_args.do_train: _SCREAMING_SNAKE_CASE =None if training_args.resume_from_checkpoint is not None: _SCREAMING_SNAKE_CASE =training_args.resume_from_checkpoint elif last_checkpoint is not None: _SCREAMING_SNAKE_CASE =last_checkpoint _SCREAMING_SNAKE_CASE =trainer.train(resume_from_checkpoint=_UpperCamelCase ) trainer.save_model() trainer.log_metrics('train' , train_result.metrics ) trainer.save_metrics('train' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _SCREAMING_SNAKE_CASE =trainer.evaluate() trainer.log_metrics('eval' , _UpperCamelCase ) trainer.save_metrics('eval' , _UpperCamelCase ) # Write model card and (optionally) push to hub _SCREAMING_SNAKE_CASE ={ 'tasks': 'masked-auto-encoding', 'dataset': data_args.dataset_name, 'tags': ['masked-auto-encoding'], } if training_args.push_to_hub: trainer.push_to_hub(**_UpperCamelCase ) else: trainer.create_model_card(**_UpperCamelCase ) def _lowerCAmelCase ( _UpperCamelCase : List[str] ) -> Optional[int]: """simple docstring""" main() if __name__ == "__main__": main()
47
1
'''simple docstring''' import json import os import shutil import warnings from argparse import ArgumentParser, Namespace from pathlib import Path from typing import List from ..utils import logging from . import BaseTransformersCLICommand try: from cookiecutter.main import cookiecutter lowerCamelCase : Any = True except ImportError: lowerCamelCase : Union[str, Any] = False lowerCamelCase : Any = logging.get_logger(__name__) # pylint: disable=invalid-name def _lowerCAmelCase ( _UpperCamelCase : Namespace ) -> Any: """simple docstring""" return AddNewModelCommand(args.testing , args.testing_file , path=args.path ) class A__ ( A__ ): @staticmethod def A ( _a : ArgumentParser ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =parser.add_parser('add-new-model' ) add_new_model_parser.add_argument('--testing' , action='store_true' , help='If in testing mode.' ) add_new_model_parser.add_argument('--testing_file' , type=_a , help='Configuration file on which to run.' ) add_new_model_parser.add_argument( '--path' , type=_a , help='Path to cookiecutter. Should only be used for testing purposes.' ) add_new_model_parser.set_defaults(func=_a ) def __init__( self : Optional[Any] , _a : bool , _a : str , _a : Optional[Any]=None , *_a : List[Any] ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =testing _SCREAMING_SNAKE_CASE =testing_file _SCREAMING_SNAKE_CASE =path def A ( self : str ) -> int: '''simple docstring''' warnings.warn( 'The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. ' 'It is not actively maintained anymore, so might give a result that won\'t pass all tests and quality ' 'checks, you should use `transformers-cli add-new-model-like` instead.' ) if not _has_cookiecutter: raise ImportError( 'Model creation dependencies are required to use the `add_new_model` command. Install them by running ' 'the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n' ) # Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory _SCREAMING_SNAKE_CASE =[directory for directory in os.listdir() if 'cookiecutter-template-' == directory[:22]] if len(_a ) > 0: raise ValueError( 'Several directories starting with `cookiecutter-template-` in current working directory. ' 'Please clean your directory by removing all folders starting with `cookiecutter-template-` or ' 'change your working directory.' ) _SCREAMING_SNAKE_CASE =( Path(_a ).parent.parent.parent.parent if self._path is None else Path(self._path ).parent.parent ) _SCREAMING_SNAKE_CASE =path_to_transformer_root / 'templates' / 'adding_a_new_model' # Execute cookiecutter if not self._testing: cookiecutter(str(_a ) ) else: with open(self._testing_file , 'r' ) as configuration_file: _SCREAMING_SNAKE_CASE =json.load(_a ) cookiecutter( str(path_to_cookiecutter if self._path is None else self._path ) , no_input=_a , extra_context=_a , ) _SCREAMING_SNAKE_CASE =[directory for directory in os.listdir() if 'cookiecutter-template-' in directory[:22]][0] # Retrieve configuration with open(directory + '/configuration.json' , 'r' ) as configuration_file: _SCREAMING_SNAKE_CASE =json.load(_a ) _SCREAMING_SNAKE_CASE =configuration['lowercase_modelname'] _SCREAMING_SNAKE_CASE =configuration['generate_tensorflow_pytorch_and_flax'] os.remove(f"{directory}/configuration.json" ) _SCREAMING_SNAKE_CASE ='PyTorch' in generate_tensorflow_pytorch_and_flax _SCREAMING_SNAKE_CASE ='TensorFlow' in generate_tensorflow_pytorch_and_flax _SCREAMING_SNAKE_CASE ='Flax' in generate_tensorflow_pytorch_and_flax _SCREAMING_SNAKE_CASE =f"{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}" os.makedirs(_a , exist_ok=_a ) os.makedirs(f"{path_to_transformer_root}/tests/models/{lowercase_model_name}" , exist_ok=_a ) # Tests require submodules as they have parent imports with open(f"{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py" , 'w' ): pass shutil.move( f"{directory}/__init__.py" , f"{model_dir}/__init__.py" , ) shutil.move( f"{directory}/configuration_{lowercase_model_name}.py" , f"{model_dir}/configuration_{lowercase_model_name}.py" , ) def remove_copy_lines(_a : Any ): with open(_a , 'r' ) as f: _SCREAMING_SNAKE_CASE =f.readlines() with open(_a , 'w' ) as f: for line in lines: if "# Copied from transformers." not in line: f.write(_a ) if output_pytorch: if not self._testing: remove_copy_lines(f"{directory}/modeling_{lowercase_model_name}.py" ) shutil.move( f"{directory}/modeling_{lowercase_model_name}.py" , f"{model_dir}/modeling_{lowercase_model_name}.py" , ) shutil.move( f"{directory}/test_modeling_{lowercase_model_name}.py" , f"{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py" , ) else: os.remove(f"{directory}/modeling_{lowercase_model_name}.py" ) os.remove(f"{directory}/test_modeling_{lowercase_model_name}.py" ) if output_tensorflow: if not self._testing: remove_copy_lines(f"{directory}/modeling_tf_{lowercase_model_name}.py" ) shutil.move( f"{directory}/modeling_tf_{lowercase_model_name}.py" , f"{model_dir}/modeling_tf_{lowercase_model_name}.py" , ) shutil.move( f"{directory}/test_modeling_tf_{lowercase_model_name}.py" , f"{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py" , ) else: os.remove(f"{directory}/modeling_tf_{lowercase_model_name}.py" ) os.remove(f"{directory}/test_modeling_tf_{lowercase_model_name}.py" ) if output_flax: if not self._testing: remove_copy_lines(f"{directory}/modeling_flax_{lowercase_model_name}.py" ) shutil.move( f"{directory}/modeling_flax_{lowercase_model_name}.py" , f"{model_dir}/modeling_flax_{lowercase_model_name}.py" , ) shutil.move( f"{directory}/test_modeling_flax_{lowercase_model_name}.py" , f"{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py" , ) else: os.remove(f"{directory}/modeling_flax_{lowercase_model_name}.py" ) os.remove(f"{directory}/test_modeling_flax_{lowercase_model_name}.py" ) shutil.move( f"{directory}/{lowercase_model_name}.md" , f"{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md" , ) shutil.move( f"{directory}/tokenization_{lowercase_model_name}.py" , f"{model_dir}/tokenization_{lowercase_model_name}.py" , ) shutil.move( f"{directory}/tokenization_fast_{lowercase_model_name}.py" , f"{model_dir}/tokenization_{lowercase_model_name}_fast.py" , ) from os import fdopen, remove from shutil import copymode, move from tempfile import mkstemp def replace(_a : str , _a : str , _a : List[str] ): # Create temp file _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =mkstemp() _SCREAMING_SNAKE_CASE =False with fdopen(_a , 'w' ) as new_file: with open(_a ) as old_file: for line in old_file: new_file.write(_a ) if line_to_copy_below in line: _SCREAMING_SNAKE_CASE =True for line_to_copy in lines_to_copy: new_file.write(_a ) if not line_found: raise ValueError(f"Line {line_to_copy_below} was not found in file." ) # Copy the file permissions from the old file to the new file copymode(_a , _a ) # Remove original file remove(_a ) # Move new file move(_a , _a ) def skip_units(_a : str ): return ( ("generating PyTorch" in line and not output_pytorch) or ("generating TensorFlow" in line and not output_tensorflow) or ("generating Flax" in line and not output_flax) ) def replace_in_files(_a : str ): with open(_a ) as datafile: _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =False _SCREAMING_SNAKE_CASE =False for line in datafile: if "# To replace in: " in line and "##" not in line: _SCREAMING_SNAKE_CASE =line.split('"' )[1] _SCREAMING_SNAKE_CASE =skip_units(_a ) elif "# Below: " in line and "##" not in line: _SCREAMING_SNAKE_CASE =line.split('"' )[1] _SCREAMING_SNAKE_CASE =skip_units(_a ) elif "# End." in line and "##" not in line: if not skip_file and not skip_snippet: replace(_a , _a , _a ) _SCREAMING_SNAKE_CASE =[] elif "# Replace with" in line and "##" not in line: _SCREAMING_SNAKE_CASE =[] elif "##" not in line: lines_to_copy.append(_a ) remove(_a ) replace_in_files(f"{directory}/to_replace_{lowercase_model_name}.py" ) os.rmdir(_a )
47
'''simple docstring''' from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class A__ ( A__ , A__ ): @register_to_config def __init__( self : Dict , _a : int = 768 , ) -> Union[str, Any]: '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =nn.Parameter(torch.zeros(1 , _a ) ) _SCREAMING_SNAKE_CASE =nn.Parameter(torch.ones(1 , _a ) ) def A ( self : Tuple , _a : Optional[Union[str, torch.device]] = None , _a : Optional[torch.dtype] = None , ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =nn.Parameter(self.mean.to(_a ).to(_a ) ) _SCREAMING_SNAKE_CASE =nn.Parameter(self.std.to(_a ).to(_a ) ) return self def A ( self : Tuple , _a : str ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =(embeds - self.mean) * 1.0 / self.std return embeds def A ( self : List[str] , _a : Optional[Any] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =(embeds * self.std) + self.mean return embeds
47
1
'''simple docstring''' lowerCamelCase : List[str] = "\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" lowerCamelCase : Any = [{"type": "code", "content": INSTALL_CONTENT}] lowerCamelCase : Optional[int] = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
47
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def _lowerCAmelCase ( _UpperCamelCase : Optional[int] ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =botoa.client('iam' ) _SCREAMING_SNAKE_CASE ={ 'Version': '2012-10-17', 'Statement': [ {'Effect': 'Allow', 'Principal': {'Service': 'sagemaker.amazonaws.com'}, 'Action': 'sts:AssumeRole'} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=_UpperCamelCase , AssumeRolePolicyDocument=json.dumps(_UpperCamelCase , indent=2 ) ) _SCREAMING_SNAKE_CASE ={ 'Version': '2012-10-17', 'Statement': [ { 'Effect': 'Allow', 'Action': [ 'sagemaker:*', 'ecr:GetDownloadUrlForLayer', 'ecr:BatchGetImage', 'ecr:BatchCheckLayerAvailability', 'ecr:GetAuthorizationToken', 'cloudwatch:PutMetricData', 'cloudwatch:GetMetricData', 'cloudwatch:GetMetricStatistics', 'cloudwatch:ListMetrics', 'logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:DescribeLogStreams', 'logs:PutLogEvents', 'logs:GetLogEvents', 's3:CreateBucket', 's3:ListBucket', 's3:GetBucketLocation', 's3:GetObject', 's3:PutObject', ], 'Resource': '*', } ], } # attach policy to role iam_client.put_role_policy( RoleName=_UpperCamelCase , PolicyName=f"{role_name}_policy_permission" , PolicyDocument=json.dumps(_UpperCamelCase , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(f"role {role_name} already exists. Using existing one" ) def _lowerCAmelCase ( _UpperCamelCase : List[str] ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =botoa.client('iam' ) return iam_client.get_role(RoleName=_UpperCamelCase )["Role"]["Arn"] def _lowerCAmelCase ( ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =_ask_options( 'How do you want to authorize?' , ['AWS Profile', 'Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) '] , _UpperCamelCase , ) _SCREAMING_SNAKE_CASE =None if credentials_configuration == 0: _SCREAMING_SNAKE_CASE =_ask_field('Enter your AWS Profile name: [default] ' , default='default' ) _SCREAMING_SNAKE_CASE =aws_profile else: print( 'Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,' '`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`' ) _SCREAMING_SNAKE_CASE =_ask_field('AWS Access Key ID: ' ) _SCREAMING_SNAKE_CASE =aws_access_key_id _SCREAMING_SNAKE_CASE =_ask_field('AWS Secret Access Key: ' ) _SCREAMING_SNAKE_CASE =aws_secret_access_key _SCREAMING_SNAKE_CASE =_ask_field('Enter your AWS Region: [us-east-1]' , default='us-east-1' ) _SCREAMING_SNAKE_CASE =aws_region _SCREAMING_SNAKE_CASE =_ask_options( 'Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?' , ['Provide IAM Role name', 'Create new IAM role using credentials'] , _UpperCamelCase , ) if role_management == 0: _SCREAMING_SNAKE_CASE =_ask_field('Enter your IAM role name: ' ) else: _SCREAMING_SNAKE_CASE ='accelerate_sagemaker_execution_role' print(f"Accelerate will create an iam role \"{iam_role_name}\" using the provided credentials" ) _create_iam_role_for_sagemaker(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to use custom Docker image? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE =None if is_custom_docker_image: _SCREAMING_SNAKE_CASE =_ask_field('Enter your Docker image: ' , lambda _UpperCamelCase : str(_UpperCamelCase ).lower() ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to provide SageMaker input channels with data locations? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE =None if is_sagemaker_inputs_enabled: _SCREAMING_SNAKE_CASE =_ask_field( 'Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): ' , lambda _UpperCamelCase : str(_UpperCamelCase ).lower() , ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to enable SageMaker metrics? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE =None if is_sagemaker_metrics_enabled: _SCREAMING_SNAKE_CASE =_ask_field( 'Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): ' , lambda _UpperCamelCase : str(_UpperCamelCase ).lower() , ) _SCREAMING_SNAKE_CASE =_ask_options( 'What is the distributed mode?' , ['No distributed training', 'Data parallelism'] , _convert_sagemaker_distributed_mode , ) _SCREAMING_SNAKE_CASE ={} _SCREAMING_SNAKE_CASE =_ask_field( 'Do you wish to optimize your script with torch dynamo?[yes/NO]:' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) if use_dynamo: _SCREAMING_SNAKE_CASE ='dynamo_' _SCREAMING_SNAKE_CASE =_ask_options( 'Which dynamo backend would you like to use?' , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to customize the defaults sent to torch.compile? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) if use_custom_options: _SCREAMING_SNAKE_CASE =_ask_options( 'Which mode do you want to use?' , _UpperCamelCase , lambda _UpperCamelCase : TORCH_DYNAMO_MODES[int(_UpperCamelCase )] , default='default' , ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to enable dynamic shape tracing? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE ='Which EC2 instance type you want to use for your training?' if distributed_type != SageMakerDistributedType.NO: _SCREAMING_SNAKE_CASE =_ask_options( _UpperCamelCase , _UpperCamelCase , lambda _UpperCamelCase : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(_UpperCamelCase )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" _SCREAMING_SNAKE_CASE =_ask_field(_UpperCamelCase , lambda _UpperCamelCase : str(_UpperCamelCase ).lower() , default='ml.p3.2xlarge' ) _SCREAMING_SNAKE_CASE =1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): _SCREAMING_SNAKE_CASE =_ask_field( 'How many machines do you want use? [1]: ' , _UpperCamelCase , default=1 , ) _SCREAMING_SNAKE_CASE =_ask_options( 'Do you wish to use FP16 or BF16 (mixed precision)?' , ['no', 'fp16', 'bf16', 'fp8'] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( 'Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.' ) return SageMakerConfig( image_uri=_UpperCamelCase , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=_UpperCamelCase , use_cpu=_UpperCamelCase , dynamo_config=_UpperCamelCase , eca_instance_type=_UpperCamelCase , profile=_UpperCamelCase , region=_UpperCamelCase , iam_role_name=_UpperCamelCase , mixed_precision=_UpperCamelCase , num_machines=_UpperCamelCase , sagemaker_inputs_file=_UpperCamelCase , sagemaker_metrics_file=_UpperCamelCase , )
47
1
'''simple docstring''' import unittest from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class A__ : @staticmethod def A ( *_a : Optional[Any] , **_a : int ) -> Union[str, Any]: '''simple docstring''' pass @is_pipeline_test @require_vision @require_torch class A__ ( unittest.TestCase ): A__ = MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING def A ( self : Tuple , _a : Union[str, Any] , _a : Optional[int] , _a : int ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =pipeline( 'zero-shot-object-detection' , model='hf-internal-testing/tiny-random-owlvit-object-detection' ) _SCREAMING_SNAKE_CASE =[ { 'image': './tests/fixtures/tests_samples/COCO/000000039769.png', 'candidate_labels': ['cat', 'remote', 'couch'], } ] return object_detector, examples def A ( self : List[str] , _a : Any , _a : Tuple ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =object_detector(examples[0] , threshold=0.0 ) _SCREAMING_SNAKE_CASE =len(_a ) self.assertGreater(_a , 0 ) self.assertEqual( _a , [ { 'score': ANY(_a ), 'label': ANY(_a ), 'box': {'xmin': ANY(_a ), 'ymin': ANY(_a ), 'xmax': ANY(_a ), 'ymax': ANY(_a )}, } for i in range(_a ) ] , ) @require_tf @unittest.skip('Zero Shot Object Detection not implemented in TF' ) def A ( self : Any ) -> Tuple: '''simple docstring''' pass @require_torch def A ( self : str ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =pipeline( 'zero-shot-object-detection' , model='hf-internal-testing/tiny-random-owlvit-object-detection' ) _SCREAMING_SNAKE_CASE =object_detector( './tests/fixtures/tests_samples/COCO/000000039769.png' , candidate_labels=['cat', 'remote', 'couch'] , threshold=0.64 , ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {'score': 0.72_35, 'label': 'cat', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}}, {'score': 0.72_18, 'label': 'remote', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}}, {'score': 0.71_84, 'label': 'couch', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}}, {'score': 0.67_48, 'label': 'remote', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}}, {'score': 0.66_56, 'label': 'cat', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}}, {'score': 0.66_14, 'label': 'couch', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}}, {'score': 0.64_56, 'label': 'remote', 'box': {'xmin': 494, 'ymin': 105, 'xmax': 521, 'ymax': 127}}, {'score': 0.6_42, 'label': 'remote', 'box': {'xmin': 67, 'ymin': 274, 'xmax': 93, 'ymax': 297}}, {'score': 0.64_19, 'label': 'cat', 'box': {'xmin': 494, 'ymin': 105, 'xmax': 521, 'ymax': 127}}, ] , ) _SCREAMING_SNAKE_CASE =object_detector( [ { 'image': './tests/fixtures/tests_samples/COCO/000000039769.png', 'candidate_labels': ['cat', 'remote', 'couch'], } ] , threshold=0.64 , ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ [ {'score': 0.72_35, 'label': 'cat', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}}, {'score': 0.72_18, 'label': 'remote', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}}, {'score': 0.71_84, 'label': 'couch', 'box': {'xmin': 204, 'ymin': 167, 'xmax': 232, 'ymax': 190}}, {'score': 0.67_48, 'label': 'remote', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}}, {'score': 0.66_56, 'label': 'cat', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}}, {'score': 0.66_14, 'label': 'couch', 'box': {'xmin': 571, 'ymin': 83, 'xmax': 598, 'ymax': 103}}, {'score': 0.64_56, 'label': 'remote', 'box': {'xmin': 494, 'ymin': 105, 'xmax': 521, 'ymax': 127}}, {'score': 0.6_42, 'label': 'remote', 'box': {'xmin': 67, 'ymin': 274, 'xmax': 93, 'ymax': 297}}, {'score': 0.64_19, 'label': 'cat', 'box': {'xmin': 494, 'ymin': 105, 'xmax': 521, 'ymax': 127}}, ] ] , ) @require_torch @slow def A ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =pipeline('zero-shot-object-detection' ) _SCREAMING_SNAKE_CASE =object_detector( 'http://images.cocodataset.org/val2017/000000039769.jpg' , candidate_labels=['cat', 'remote', 'couch'] , ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {'score': 0.28_68, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.2_77, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}}, {'score': 0.25_37, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.14_74, 'label': 'remote', 'box': {'xmin': 335, 'ymin': 74, 'xmax': 371, 'ymax': 187}}, {'score': 0.12_08, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}, ] , ) _SCREAMING_SNAKE_CASE =object_detector( [ { 'image': 'http://images.cocodataset.org/val2017/000000039769.jpg', 'candidate_labels': ['cat', 'remote', 'couch'], }, { 'image': 'http://images.cocodataset.org/val2017/000000039769.jpg', 'candidate_labels': ['cat', 'remote', 'couch'], }, ] , ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ [ {'score': 0.28_68, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.2_77, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}}, {'score': 0.25_37, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.14_74, 'label': 'remote', 'box': {'xmin': 335, 'ymin': 74, 'xmax': 371, 'ymax': 187}}, {'score': 0.12_08, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}, ], [ {'score': 0.28_68, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.2_77, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}}, {'score': 0.25_37, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.14_74, 'label': 'remote', 'box': {'xmin': 335, 'ymin': 74, 'xmax': 371, 'ymax': 187}}, {'score': 0.12_08, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}, ], ] , ) @require_tf @unittest.skip('Zero Shot Object Detection not implemented in TF' ) def A ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' pass @require_torch @slow def A ( self : Union[str, Any] ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =0.2 _SCREAMING_SNAKE_CASE =pipeline('zero-shot-object-detection' ) _SCREAMING_SNAKE_CASE =object_detector( 'http://images.cocodataset.org/val2017/000000039769.jpg' , candidate_labels=['cat', 'remote', 'couch'] , threshold=_a , ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {'score': 0.28_68, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.2_77, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}}, {'score': 0.25_37, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, ] , ) @require_torch @slow def A ( self : Optional[int] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =2 _SCREAMING_SNAKE_CASE =pipeline('zero-shot-object-detection' ) _SCREAMING_SNAKE_CASE =object_detector( 'http://images.cocodataset.org/val2017/000000039769.jpg' , candidate_labels=['cat', 'remote', 'couch'] , top_k=_a , ) self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {'score': 0.28_68, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.2_77, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}}, ] , )
47
'''simple docstring''' class A__ : def __init__( self : Union[str, Any] , _a : int ) -> None: '''simple docstring''' _SCREAMING_SNAKE_CASE =size _SCREAMING_SNAKE_CASE =[0] * size _SCREAMING_SNAKE_CASE =[0] * size @staticmethod def A ( _a : int ) -> int: '''simple docstring''' return index | (index + 1) @staticmethod def A ( _a : int ) -> int: '''simple docstring''' return (index & (index + 1)) - 1 def A ( self : Tuple , _a : int , _a : int ) -> None: '''simple docstring''' _SCREAMING_SNAKE_CASE =value while index < self.size: _SCREAMING_SNAKE_CASE =self.get_prev(_a ) + 1 if current_left_border == index: _SCREAMING_SNAKE_CASE =value else: _SCREAMING_SNAKE_CASE =max(_a , _a , _a ) _SCREAMING_SNAKE_CASE =self.get_next(_a ) def A ( self : int , _a : int , _a : int ) -> int: '''simple docstring''' right -= 1 # Because of right is exclusive _SCREAMING_SNAKE_CASE =0 while left <= right: _SCREAMING_SNAKE_CASE =self.get_prev(_a ) if left <= current_left: _SCREAMING_SNAKE_CASE =max(_a , self.tree[right] ) _SCREAMING_SNAKE_CASE =current_left else: _SCREAMING_SNAKE_CASE =max(_a , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
47
1
'''simple docstring''' # We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings("ignore", category=UserWarning, module="torch.optim.lr_scheduler") class A__ : def __init__( self : List[str] , _a : Optional[Any] , _a : str , _a : bool = True , _a : bool = False ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =scheduler _SCREAMING_SNAKE_CASE =optimizers if isinstance(_a , (list, tuple) ) else [optimizers] _SCREAMING_SNAKE_CASE =split_batches _SCREAMING_SNAKE_CASE =step_with_optimizer _SCREAMING_SNAKE_CASE =GradientState() def A ( self : Dict , *_a : List[Any] , **_a : Any ) -> Union[str, Any]: '''simple docstring''' if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*_a , **_a ) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*_a , **_a ) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step _SCREAMING_SNAKE_CASE =AcceleratorState().num_processes for _ in range(_a ): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , 'total_steps' ): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*_a , **_a ) else: self.scheduler.step(*_a , **_a ) def A ( self : Dict ) -> Tuple: '''simple docstring''' return self.scheduler.get_last_lr() def A ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' return self.scheduler.state_dict() def A ( self : Any , _a : str ) -> int: '''simple docstring''' self.scheduler.load_state_dict(_a ) def A ( self : Any ) -> Optional[Any]: '''simple docstring''' return self.scheduler.get_lr() def A ( self : List[Any] , *_a : List[str] , **_a : int ) -> int: '''simple docstring''' return self.scheduler.print_lr(*_a , **_a )
47
'''simple docstring''' from __future__ import annotations from random import random from typing import Generic, TypeVar lowerCamelCase : Union[str, Any] = TypeVar("KT") lowerCamelCase : Dict = TypeVar("VT") class A__ ( Generic[KT, VT] ): def __init__( self : str , _a : KT | str = "root" , _a : VT | None = None ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =key _SCREAMING_SNAKE_CASE =value _SCREAMING_SNAKE_CASE =[] def __repr__( self : Union[str, Any] ) -> str: '''simple docstring''' return f"Node({self.key}: {self.value})" @property def A ( self : int ) -> int: '''simple docstring''' return len(self.forward ) class A__ ( Generic[KT, VT] ): def __init__( self : Optional[Any] , _a : float = 0.5 , _a : int = 16 ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =Node[KT, VT]() _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =p _SCREAMING_SNAKE_CASE =max_level def __str__( self : Tuple ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =list(self ) if len(_a ) == 0: return f"SkipList(level={self.level})" _SCREAMING_SNAKE_CASE =max((len(str(_a ) ) for item in items) , default=4 ) _SCREAMING_SNAKE_CASE =max(_a , 4 ) + 4 _SCREAMING_SNAKE_CASE =self.head _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =node.forward.copy() lines.append(f"[{node.key}]".ljust(_a , '-' ) + '* ' * len(_a ) ) lines.append(' ' * label_size + '| ' * len(_a ) ) while len(node.forward ) != 0: _SCREAMING_SNAKE_CASE =node.forward[0] lines.append( f"[{node.key}]".ljust(_a , '-' ) + ' '.join(str(n.key ) if n.key == node.key else '|' for n in forwards ) ) lines.append(' ' * label_size + '| ' * len(_a ) ) _SCREAMING_SNAKE_CASE =node.forward lines.append('None'.ljust(_a ) + '* ' * len(_a ) ) return f"SkipList(level={self.level})\n" + "\n".join(_a ) def __iter__( self : Dict ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.head while len(node.forward ) != 0: yield node.forward[0].key _SCREAMING_SNAKE_CASE =node.forward[0] def A ( self : List[Any] ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =1 while random() < self.p and level < self.max_level: level += 1 return level def A ( self : Any , _a : Any ) -> tuple[Node[KT, VT] | None, list[Node[KT, VT]]]: '''simple docstring''' _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =self.head for i in reversed(range(self.level ) ): # i < node.level - When node level is lesser than `i` decrement `i`. # node.forward[i].key < key - Jumping to node with key value higher # or equal to searched key would result # in skipping searched key. while i < node.level and node.forward[i].key < key: _SCREAMING_SNAKE_CASE =node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(_a ) update_vector.reverse() # Note that we were inserting values in reverse order. # len(node.forward) != 0 - If current node doesn't contain any further # references then searched key is not present. # node.forward[0].key == key - Next node key should be equal to search key # if key is present. if len(node.forward ) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def A ( self : Union[str, Any] , _a : KT ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self._locate_node(_a ) if node is not None: for i, update_node in enumerate(_a ): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: _SCREAMING_SNAKE_CASE =node.forward[i] else: _SCREAMING_SNAKE_CASE =update_node.forward[:i] def A ( self : Optional[Any] , _a : KT , _a : VT ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self._locate_node(_a ) if node is not None: _SCREAMING_SNAKE_CASE =value else: _SCREAMING_SNAKE_CASE =self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for _ in range(self.level - 1 , _a ): update_vector.append(self.head ) _SCREAMING_SNAKE_CASE =level _SCREAMING_SNAKE_CASE =Node(_a , _a ) for i, update_node in enumerate(update_vector[:level] ): # Change references to pass through new node. if update_node.level > i: new_node.forward.append(update_node.forward[i] ) if update_node.level < i + 1: update_node.forward.append(_a ) else: _SCREAMING_SNAKE_CASE =new_node def A ( self : List[str] , _a : VT ) -> VT | None: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self._locate_node(_a ) if node is not None: return node.value return None def _lowerCAmelCase ( ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key1' , 3 ) skip_list.insert('Key2' , 12 ) skip_list.insert('Key3' , 41 ) skip_list.insert('Key4' , -19 ) _SCREAMING_SNAKE_CASE =skip_list.head _SCREAMING_SNAKE_CASE ={} while node.level != 0: _SCREAMING_SNAKE_CASE =node.forward[0] _SCREAMING_SNAKE_CASE =node.value assert len(_UpperCamelCase ) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def _lowerCAmelCase ( ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key1' , 10 ) skip_list.insert('Key1' , 12 ) skip_list.insert('Key5' , 7 ) skip_list.insert('Key7' , 10 ) skip_list.insert('Key10' , 5 ) skip_list.insert('Key7' , 7 ) skip_list.insert('Key5' , 5 ) skip_list.insert('Key10' , 10 ) _SCREAMING_SNAKE_CASE =skip_list.head _SCREAMING_SNAKE_CASE ={} while node.level != 0: _SCREAMING_SNAKE_CASE =node.forward[0] _SCREAMING_SNAKE_CASE =node.value if len(_UpperCamelCase ) != 4: print() assert len(_UpperCamelCase ) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def _lowerCAmelCase ( ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() assert skip_list.find('Some key' ) is None def _lowerCAmelCase ( ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key2' , 20 ) assert skip_list.find('Key2' ) == 20 skip_list.insert('Some Key' , 10 ) skip_list.insert('Key2' , 8 ) skip_list.insert('V' , 13 ) assert skip_list.find('Y' ) is None assert skip_list.find('Key2' ) == 8 assert skip_list.find('Some Key' ) == 10 assert skip_list.find('V' ) == 13 def _lowerCAmelCase ( ) -> List[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.delete('Some key' ) assert len(skip_list.head.forward ) == 0 def _lowerCAmelCase ( ) -> Optional[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key1' , 12 ) skip_list.insert('V' , 13 ) skip_list.insert('X' , 14 ) skip_list.insert('Key2' , 15 ) skip_list.delete('V' ) skip_list.delete('Key2' ) assert skip_list.find('V' ) is None assert skip_list.find('Key2' ) is None def _lowerCAmelCase ( ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key1' , 12 ) skip_list.insert('V' , 13 ) skip_list.insert('X' , 14 ) skip_list.insert('Key2' , 15 ) skip_list.delete('V' ) assert skip_list.find('V' ) is None assert skip_list.find('X' ) == 14 assert skip_list.find('Key1' ) == 12 assert skip_list.find('Key2' ) == 15 skip_list.delete('X' ) assert skip_list.find('V' ) is None assert skip_list.find('X' ) is None assert skip_list.find('Key1' ) == 12 assert skip_list.find('Key2' ) == 15 skip_list.delete('Key1' ) assert skip_list.find('V' ) is None assert skip_list.find('X' ) is None assert skip_list.find('Key1' ) is None assert skip_list.find('Key2' ) == 15 skip_list.delete('Key2' ) assert skip_list.find('V' ) is None assert skip_list.find('X' ) is None assert skip_list.find('Key1' ) is None assert skip_list.find('Key2' ) is None def _lowerCAmelCase ( ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key1' , 12 ) skip_list.insert('V' , 13 ) skip_list.insert('X' , 1_42 ) skip_list.insert('Key2' , 15 ) skip_list.delete('X' ) def traverse_keys(_UpperCamelCase : Dict ): yield node.key for forward_node in node.forward: yield from traverse_keys(_UpperCamelCase ) assert len(set(traverse_keys(skip_list.head ) ) ) == 4 def _lowerCAmelCase ( ) -> Union[str, Any]: """simple docstring""" def is_sorted(_UpperCamelCase : str ): return all(next_item >= item for item, next_item in zip(_UpperCamelCase , lst[1:] ) ) _SCREAMING_SNAKE_CASE =SkipList() for i in range(10 ): skip_list.insert(_UpperCamelCase , _UpperCamelCase ) assert is_sorted(list(_UpperCamelCase ) ) skip_list.delete(5 ) skip_list.delete(8 ) skip_list.delete(2 ) assert is_sorted(list(_UpperCamelCase ) ) skip_list.insert(-12 , -12 ) skip_list.insert(77 , 77 ) assert is_sorted(list(_UpperCamelCase ) ) def _lowerCAmelCase ( ) -> List[str]: """simple docstring""" for _ in range(1_00 ): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def _lowerCAmelCase ( ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert(2 , '2' ) skip_list.insert(4 , '4' ) skip_list.insert(6 , '4' ) skip_list.insert(4 , '5' ) skip_list.insert(8 , '4' ) skip_list.insert(9 , '4' ) skip_list.delete(4 ) print(_UpperCamelCase ) if __name__ == "__main__": import doctest doctest.testmod() main()
47
1
'''simple docstring''' from typing import List import numpy as np def _lowerCAmelCase ( _UpperCamelCase : dict ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE ={key: len(_UpperCamelCase ) for key, value in gen_kwargs.items() if isinstance(_UpperCamelCase , _UpperCamelCase )} if len(set(lists_lengths.values() ) ) > 1: raise RuntimeError( ( 'Sharding is ambiguous for this dataset: ' + 'we found several data sources lists of different lengths, and we don\'t know over which list we should parallelize:\n' + '\n'.join(f"\t- key {key} has length {length}" for key, length in lists_lengths.items() ) + '\nTo fix this, check the \'gen_kwargs\' and make sure to use lists only for data sources, ' + 'and use tuples otherwise. In the end there should only be one single list, or several lists with the same length.' ) ) _SCREAMING_SNAKE_CASE =max(lists_lengths.values() , default=0 ) return max(1 , _UpperCamelCase ) def _lowerCAmelCase ( _UpperCamelCase : int , _UpperCamelCase : int ) -> List[range]: """simple docstring""" _SCREAMING_SNAKE_CASE =[] for group_idx in range(_UpperCamelCase ): _SCREAMING_SNAKE_CASE =num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs)) if num_shards_to_add == 0: break _SCREAMING_SNAKE_CASE =shards_indices_per_group[-1].stop if shards_indices_per_group else 0 _SCREAMING_SNAKE_CASE =range(_UpperCamelCase , start + num_shards_to_add ) shards_indices_per_group.append(_UpperCamelCase ) return shards_indices_per_group def _lowerCAmelCase ( _UpperCamelCase : dict , _UpperCamelCase : int ) -> List[dict]: """simple docstring""" _SCREAMING_SNAKE_CASE =_number_of_shards_in_gen_kwargs(_UpperCamelCase ) if num_shards == 1: return [dict(_UpperCamelCase )] else: _SCREAMING_SNAKE_CASE =_distribute_shards(num_shards=_UpperCamelCase , max_num_jobs=_UpperCamelCase ) return [ { key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]] if isinstance(_UpperCamelCase , _UpperCamelCase ) else value for key, value in gen_kwargs.items() } for group_idx in range(len(_UpperCamelCase ) ) ] def _lowerCAmelCase ( _UpperCamelCase : List[dict] ) -> dict: """simple docstring""" return { key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]] if isinstance(gen_kwargs_list[0][key] , _UpperCamelCase ) else gen_kwargs_list[0][key] for key in gen_kwargs_list[0] } def _lowerCAmelCase ( _UpperCamelCase : np.random.Generator , _UpperCamelCase : dict ) -> dict: """simple docstring""" _SCREAMING_SNAKE_CASE ={len(_UpperCamelCase ) for value in gen_kwargs.values() if isinstance(_UpperCamelCase , _UpperCamelCase )} _SCREAMING_SNAKE_CASE ={} for size in list_sizes: _SCREAMING_SNAKE_CASE =list(range(_UpperCamelCase ) ) rng.shuffle(indices_per_size[size] ) # Now let's copy the gen_kwargs and shuffle the lists based on their sizes _SCREAMING_SNAKE_CASE =dict(_UpperCamelCase ) for key, value in shuffled_kwargs.items(): if isinstance(_UpperCamelCase , _UpperCamelCase ): _SCREAMING_SNAKE_CASE =[value[i] for i in indices_per_size[len(_UpperCamelCase )]] return shuffled_kwargs
47
'''simple docstring''' import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version lowerCamelCase : List[Any] = version.parse(importlib_metadata.version("nltk")) if NLTK_VERSION >= version.Version("3.6.4"): from nltk import word_tokenize lowerCamelCase : Any = "\\n@inproceedings{banarjee2005,\n title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n author = {Banerjee, Satanjeev and Lavie, Alon},\n booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n month = jun,\n year = {2005},\n address = {Ann Arbor, Michigan},\n publisher = {Association for Computational Linguistics},\n url = {https://www.aclweb.org/anthology/W05-0909},\n pages = {65--72},\n}\n" lowerCamelCase : Optional[Any] = "\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n" lowerCamelCase : Optional[Any] = "\nComputes METEOR score of translated segments against one or more references.\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n 'meteor': meteor score.\nExamples:\n\n >>> meteor = datasets.load_metric('meteor')\n >>> predictions = [\"It is a guide to action which ensures that the military always obeys the commands of the party\"]\n >>> references = [\"It is a guide to action that ensures that the military will forever heed Party commands\"]\n >>> results = meteor.compute(predictions=predictions, references=references)\n >>> print(round(results[\"meteor\"], 4))\n 0.6944\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def A ( self : Tuple ) -> str: '''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/nltk/nltk/blob/develop/nltk/translate/meteor_score.py'] , reference_urls=[ 'https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score', 'https://en.wikipedia.org/wiki/METEOR', ] , ) def A ( self : Union[str, Any] , _a : Union[str, Any] ) -> Optional[int]: '''simple docstring''' import nltk nltk.download('wordnet' ) if NLTK_VERSION >= version.Version('3.6.5' ): nltk.download('punkt' ) if NLTK_VERSION >= version.Version('3.6.6' ): nltk.download('omw-1.4' ) def A ( self : int , _a : Tuple , _a : List[str] , _a : List[str]=0.9 , _a : Dict=3 , _a : Optional[int]=0.5 ) -> Optional[int]: '''simple docstring''' if NLTK_VERSION >= version.Version('3.6.5' ): _SCREAMING_SNAKE_CASE =[ meteor_score.single_meteor_score( word_tokenize(_a ) , word_tokenize(_a ) , alpha=_a , beta=_a , gamma=_a ) for ref, pred in zip(_a , _a ) ] else: _SCREAMING_SNAKE_CASE =[ meteor_score.single_meteor_score(_a , _a , alpha=_a , beta=_a , gamma=_a ) for ref, pred in zip(_a , _a ) ] return {"meteor": np.mean(_a )}
47
1
'''simple docstring''' import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() lowerCamelCase : Any = logging.get_logger(__name__) lowerCamelCase : Optional[int] = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "encoder.layer_norm_for_extract": "layer_norm_for_extract", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "label_embs_concat": "label_embeddings_concat", "mask_emb": "masked_spec_embed", "spk_proj": "speaker_proj", } lowerCamelCase : Any = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", "label_embeddings_concat", "speaker_proj", "layer_norm_for_extract", ] def _lowerCAmelCase ( _UpperCamelCase : List[str] , _UpperCamelCase : Optional[Any] , _UpperCamelCase : Any , _UpperCamelCase : Dict , _UpperCamelCase : Any ) -> Any: """simple docstring""" for attribute in key.split('.' ): _SCREAMING_SNAKE_CASE =getattr(_UpperCamelCase , _UpperCamelCase ) if weight_type is not None: _SCREAMING_SNAKE_CASE =getattr(_UpperCamelCase , _UpperCamelCase ).shape else: _SCREAMING_SNAKE_CASE =hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" f" {value.shape} for {full_name}" ) if weight_type == "weight": _SCREAMING_SNAKE_CASE =value elif weight_type == "weight_g": _SCREAMING_SNAKE_CASE =value elif weight_type == "weight_v": _SCREAMING_SNAKE_CASE =value elif weight_type == "bias": _SCREAMING_SNAKE_CASE =value else: _SCREAMING_SNAKE_CASE =value logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def _lowerCAmelCase ( _UpperCamelCase : str , _UpperCamelCase : Dict ) -> List[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =fairseq_model.state_dict() _SCREAMING_SNAKE_CASE =hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): _SCREAMING_SNAKE_CASE =False if "conv_layers" in name: load_conv_layer( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , hf_model.config.feat_extract_norm == 'group' , ) _SCREAMING_SNAKE_CASE =True else: for key, mapped_key in MAPPING.items(): _SCREAMING_SNAKE_CASE ='unispeech_sat.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: if "layer_norm_for_extract" in name and (".".join(name.split('.' )[:-1] ) != key): # special case since naming is very similar continue _SCREAMING_SNAKE_CASE =True if "*" in mapped_key: _SCREAMING_SNAKE_CASE =name.split(_UpperCamelCase )[0].split('.' )[-2] _SCREAMING_SNAKE_CASE =mapped_key.replace('*' , _UpperCamelCase ) if "weight_g" in name: _SCREAMING_SNAKE_CASE ='weight_g' elif "weight_v" in name: _SCREAMING_SNAKE_CASE ='weight_v' elif "bias" in name: _SCREAMING_SNAKE_CASE ='bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj _SCREAMING_SNAKE_CASE ='weight' else: _SCREAMING_SNAKE_CASE =None set_recursively(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) continue if not is_used: unused_weights.append(_UpperCamelCase ) logger.warning(f"Unused weights: {unused_weights}" ) def _lowerCAmelCase ( _UpperCamelCase : Optional[int] , _UpperCamelCase : Optional[Any] , _UpperCamelCase : Optional[int] , _UpperCamelCase : Dict , _UpperCamelCase : List[str] ) -> List[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =full_name.split('conv_layers.' )[-1] _SCREAMING_SNAKE_CASE =name.split('.' ) _SCREAMING_SNAKE_CASE =int(items[0] ) _SCREAMING_SNAKE_CASE =int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) _SCREAMING_SNAKE_CASE =value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) _SCREAMING_SNAKE_CASE =value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"{full_name} has size {value.shape}, but" f" {feature_extractor[layer_id].layer_norm.bias.data.shape} was found." ) _SCREAMING_SNAKE_CASE =value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"{full_name} has size {value.shape}, but" f" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) _SCREAMING_SNAKE_CASE =value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(_UpperCamelCase ) @torch.no_grad() def _lowerCAmelCase ( _UpperCamelCase : Optional[int] , _UpperCamelCase : List[str] , _UpperCamelCase : List[Any]=None , _UpperCamelCase : str=None , _UpperCamelCase : Tuple=True ) -> str: """simple docstring""" if config_path is not None: _SCREAMING_SNAKE_CASE =UniSpeechSatConfig.from_pretrained(_UpperCamelCase ) else: _SCREAMING_SNAKE_CASE =UniSpeechSatConfig() _SCREAMING_SNAKE_CASE ='' if is_finetuned: _SCREAMING_SNAKE_CASE =UniSpeechSatForCTC(_UpperCamelCase ) else: _SCREAMING_SNAKE_CASE =UniSpeechSatForPreTraining(_UpperCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) _SCREAMING_SNAKE_CASE =model[0].eval() recursively_load_weights(_UpperCamelCase , _UpperCamelCase ) hf_wavavec.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": lowerCamelCase : List[str] = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not" ) lowerCamelCase : Union[str, Any] = parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
47
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowerCamelCase : List[str] = logging.get_logger(__name__) lowerCamelCase : List[Any] = { "facebook/convnextv2-tiny-1k-224": "https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json", } class A__ ( A__ , A__ ): A__ = 'convnextv2' def __init__( self : Tuple , _a : Optional[int]=3 , _a : Any=4 , _a : int=4 , _a : Union[str, Any]=None , _a : List[str]=None , _a : Optional[Any]="gelu" , _a : Any=0.02 , _a : Any=1e-12 , _a : Tuple=0.0 , _a : int=224 , _a : Any=None , _a : Optional[int]=None , **_a : List[str] , ) -> Optional[Any]: '''simple docstring''' super().__init__(**_a ) _SCREAMING_SNAKE_CASE =num_channels _SCREAMING_SNAKE_CASE =patch_size _SCREAMING_SNAKE_CASE =num_stages _SCREAMING_SNAKE_CASE =[96, 192, 384, 768] if hidden_sizes is None else hidden_sizes _SCREAMING_SNAKE_CASE =[3, 3, 9, 3] if depths is None else depths _SCREAMING_SNAKE_CASE =hidden_act _SCREAMING_SNAKE_CASE =initializer_range _SCREAMING_SNAKE_CASE =layer_norm_eps _SCREAMING_SNAKE_CASE =drop_path_rate _SCREAMING_SNAKE_CASE =image_size _SCREAMING_SNAKE_CASE =['stem'] + [f"stage{idx}" for idx in range(1 , len(self.depths ) + 1 )] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =get_aligned_output_features_output_indices( out_features=_a , out_indices=_a , stage_names=self.stage_names )
47
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_realm import RealmTokenizer lowerCamelCase : str = logging.get_logger(__name__) lowerCamelCase : int = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} lowerCamelCase : Optional[int] = { "vocab_file": { "google/realm-cc-news-pretrained-embedder": ( "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-encoder": ( "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-scorer": ( "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-openqa": ( "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt" ), "google/realm-orqa-nq-openqa": "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt", "google/realm-orqa-nq-reader": "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt", "google/realm-orqa-wq-openqa": "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt", "google/realm-orqa-wq-reader": "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt", }, "tokenizer_file": { "google/realm-cc-news-pretrained-embedder": ( "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont" ), "google/realm-cc-news-pretrained-encoder": ( "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json" ), "google/realm-cc-news-pretrained-scorer": ( "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json" ), "google/realm-cc-news-pretrained-openqa": ( "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json" ), "google/realm-orqa-nq-openqa": ( "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json" ), "google/realm-orqa-nq-reader": ( "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json" ), "google/realm-orqa-wq-openqa": ( "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json" ), "google/realm-orqa-wq-reader": ( "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json" ), }, } lowerCamelCase : Dict = { "google/realm-cc-news-pretrained-embedder": 5_1_2, "google/realm-cc-news-pretrained-encoder": 5_1_2, "google/realm-cc-news-pretrained-scorer": 5_1_2, "google/realm-cc-news-pretrained-openqa": 5_1_2, "google/realm-orqa-nq-openqa": 5_1_2, "google/realm-orqa-nq-reader": 5_1_2, "google/realm-orqa-wq-openqa": 5_1_2, "google/realm-orqa-wq-reader": 5_1_2, } lowerCamelCase : int = { "google/realm-cc-news-pretrained-embedder": {"do_lower_case": True}, "google/realm-cc-news-pretrained-encoder": {"do_lower_case": True}, "google/realm-cc-news-pretrained-scorer": {"do_lower_case": True}, "google/realm-cc-news-pretrained-openqa": {"do_lower_case": True}, "google/realm-orqa-nq-openqa": {"do_lower_case": True}, "google/realm-orqa-nq-reader": {"do_lower_case": True}, "google/realm-orqa-wq-openqa": {"do_lower_case": True}, "google/realm-orqa-wq-reader": {"do_lower_case": True}, } class A__ ( A__ ): A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_INIT_CONFIGURATION A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = RealmTokenizer def __init__( self : Tuple , _a : Union[str, Any]=None , _a : List[Any]=None , _a : str=True , _a : Dict="[UNK]" , _a : List[Any]="[SEP]" , _a : List[str]="[PAD]" , _a : int="[CLS]" , _a : List[Any]="[MASK]" , _a : List[Any]=True , _a : str=None , **_a : Any , ) -> str: '''simple docstring''' super().__init__( _a , tokenizer_file=_a , do_lower_case=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , tokenize_chinese_chars=_a , strip_accents=_a , **_a , ) _SCREAMING_SNAKE_CASE =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , _a ) != do_lower_case or normalizer_state.get('strip_accents' , _a ) != strip_accents or normalizer_state.get('handle_chinese_chars' , _a ) != tokenize_chinese_chars ): _SCREAMING_SNAKE_CASE =getattr(_a , normalizer_state.pop('type' ) ) _SCREAMING_SNAKE_CASE =do_lower_case _SCREAMING_SNAKE_CASE =strip_accents _SCREAMING_SNAKE_CASE =tokenize_chinese_chars _SCREAMING_SNAKE_CASE =normalizer_class(**_a ) _SCREAMING_SNAKE_CASE =do_lower_case def A ( self : int , _a : Union[str, Any] , **_a : List[Any] ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =PaddingStrategy.MAX_LENGTH _SCREAMING_SNAKE_CASE =text _SCREAMING_SNAKE_CASE =kwargs.pop('text_pair' , _a ) _SCREAMING_SNAKE_CASE =kwargs.pop('return_tensors' , _a ) _SCREAMING_SNAKE_CASE ={ 'input_ids': [], 'attention_mask': [], 'token_type_ids': [], } for idx, candidate_text in enumerate(_a ): if batch_text_pair is not None: _SCREAMING_SNAKE_CASE =batch_text_pair[idx] else: _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =super().__call__(_a , _a , return_tensors=_a , **_a ) _SCREAMING_SNAKE_CASE =encoded_candidates.get('input_ids' ) _SCREAMING_SNAKE_CASE =encoded_candidates.get('attention_mask' ) _SCREAMING_SNAKE_CASE =encoded_candidates.get('token_type_ids' ) if encoded_input_ids is not None: output_data["input_ids"].append(_a ) if encoded_attention_mask is not None: output_data["attention_mask"].append(_a ) if encoded_token_type_ids is not None: output_data["token_type_ids"].append(_a ) _SCREAMING_SNAKE_CASE ={key: item for key, item in output_data.items() if len(_a ) != 0} return BatchEncoding(_a , tensor_type=_a ) def A ( self : int , _a : Optional[Any] , _a : Optional[int]=None ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =[self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def A ( self : str , _a : List[int] , _a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =[self.sep_token_id] _SCREAMING_SNAKE_CASE =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def A ( self : Dict , _a : str , _a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self._tokenizer.model.save(_a , name=_a ) return tuple(_a )
47
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase : int = {"configuration_glpn": ["GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP", "GLPNConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : int = ["GLPNFeatureExtractor"] lowerCamelCase : Optional[int] = ["GLPNImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Union[str, Any] = [ "GLPN_PRETRAINED_MODEL_ARCHIVE_LIST", "GLPNForDepthEstimation", "GLPNLayer", "GLPNModel", "GLPNPreTrainedModel", ] if TYPE_CHECKING: from .configuration_glpn import GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP, GLPNConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_glpn import GLPNFeatureExtractor from .image_processing_glpn import GLPNImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_glpn import ( GLPN_PRETRAINED_MODEL_ARCHIVE_LIST, GLPNForDepthEstimation, GLPNLayer, GLPNModel, GLPNPreTrainedModel, ) else: import sys lowerCamelCase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
47
1
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class A__ ( A__ ): def __init__( self : str , _a : List[Any] , _a : Dict ) -> Union[str, Any]: '''simple docstring''' super().__init__() # make sure scheduler can always be converted to DDIM _SCREAMING_SNAKE_CASE =DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=_a , scheduler=_a ) @torch.no_grad() def __call__( self : List[Any] , _a : int = 1 , _a : Optional[Union[torch.Generator, List[torch.Generator]]] = None , _a : float = 0.0 , _a : int = 50 , _a : Optional[bool] = None , _a : Optional[str] = "pil" , _a : bool = True , ) -> Union[ImagePipelineOutput, Tuple]: '''simple docstring''' if isinstance(self.unet.config.sample_size , _a ): _SCREAMING_SNAKE_CASE =( batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size, ) else: _SCREAMING_SNAKE_CASE =(batch_size, self.unet.config.in_channels, *self.unet.config.sample_size) if isinstance(_a , _a ) and len(_a ) != batch_size: raise ValueError( f"You have passed a list of generators of length {len(_a )}, but requested an effective batch" f" size of {batch_size}. Make sure the batch size matches the length of the generators." ) _SCREAMING_SNAKE_CASE =randn_tensor(_a , generator=_a , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(_a ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output _SCREAMING_SNAKE_CASE =self.unet(_a , _a ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 _SCREAMING_SNAKE_CASE =self.scheduler.step( _a , _a , _a , eta=_a , use_clipped_model_output=_a , generator=_a ).prev_sample _SCREAMING_SNAKE_CASE =(image / 2 + 0.5).clamp(0 , 1 ) _SCREAMING_SNAKE_CASE =image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": _SCREAMING_SNAKE_CASE =self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
47
'''simple docstring''' lowerCamelCase : Any = "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" lowerCamelCase : int = [{"type": "code", "content": INSTALL_CONTENT}] lowerCamelCase : str = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
47
1
'''simple docstring''' import os def _lowerCAmelCase ( ) -> List[str]: """simple docstring""" with open(os.path.dirname(_UpperCamelCase ) + '/grid.txt' ) as f: _SCREAMING_SNAKE_CASE =[] # noqa: E741 for _ in range(20 ): l.append([int(_UpperCamelCase ) for x in f.readline().split()] ) _SCREAMING_SNAKE_CASE =0 # right for i in range(20 ): for j in range(17 ): _SCREAMING_SNAKE_CASE =l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: _SCREAMING_SNAKE_CASE =temp # down for i in range(17 ): for j in range(20 ): _SCREAMING_SNAKE_CASE =l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: _SCREAMING_SNAKE_CASE =temp # diagonal 1 for i in range(17 ): for j in range(17 ): _SCREAMING_SNAKE_CASE =l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: _SCREAMING_SNAKE_CASE =temp # diagonal 2 for i in range(17 ): for j in range(3 , 20 ): _SCREAMING_SNAKE_CASE =l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: _SCREAMING_SNAKE_CASE =temp return maximum if __name__ == "__main__": print(solution())
47
'''simple docstring''' import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device lowerCamelCase : Optional[int] = False class A__ ( unittest.TestCase ): pass @slow @require_torch_gpu class A__ ( unittest.TestCase ): def A ( self : Tuple ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =VersatileDiffusionImageVariationPipeline.from_pretrained('shi-labs/versatile-diffusion' ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) _SCREAMING_SNAKE_CASE =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg' ) _SCREAMING_SNAKE_CASE =torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE =pipe( image=_a , generator=_a , guidance_scale=7.5 , num_inference_steps=50 , output_type='numpy' , ).images _SCREAMING_SNAKE_CASE =image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) _SCREAMING_SNAKE_CASE =np.array([0.04_41, 0.04_69, 0.05_07, 0.05_75, 0.06_32, 0.06_50, 0.08_65, 0.09_09, 0.09_45] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
47
1
'''simple docstring''' def _lowerCAmelCase ( _UpperCamelCase : str , _UpperCamelCase : int ) -> list[str]: """simple docstring""" return [sentence[i : i + ngram_size] for i in range(len(_UpperCamelCase ) - ngram_size + 1 )] if __name__ == "__main__": from doctest import testmod testmod()
47
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase : Any = { "configuration_funnel": ["FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP", "FunnelConfig"], "convert_funnel_original_tf_checkpoint_to_pytorch": [], "tokenization_funnel": ["FunnelTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[Any] = ["FunnelTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[str] = [ "FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST", "FunnelBaseModel", "FunnelForMaskedLM", "FunnelForMultipleChoice", "FunnelForPreTraining", "FunnelForQuestionAnswering", "FunnelForSequenceClassification", "FunnelForTokenClassification", "FunnelModel", "FunnelPreTrainedModel", "load_tf_weights_in_funnel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Union[str, Any] = [ "TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST", "TFFunnelBaseModel", "TFFunnelForMaskedLM", "TFFunnelForMultipleChoice", "TFFunnelForPreTraining", "TFFunnelForQuestionAnswering", "TFFunnelForSequenceClassification", "TFFunnelForTokenClassification", "TFFunnelModel", "TFFunnelPreTrainedModel", ] if TYPE_CHECKING: from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig from .tokenization_funnel import FunnelTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_funnel_fast import FunnelTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_funnel import ( FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, FunnelBaseModel, FunnelForMaskedLM, FunnelForMultipleChoice, FunnelForPreTraining, FunnelForQuestionAnswering, FunnelForSequenceClassification, FunnelForTokenClassification, FunnelModel, FunnelPreTrainedModel, load_tf_weights_in_funnel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_funnel import ( TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, TFFunnelPreTrainedModel, ) else: import sys lowerCamelCase : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
47
1
'''simple docstring''' import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer lowerCamelCase : Optional[int] = logging.get_logger(__name__) lowerCamelCase : Union[str, Any] = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} lowerCamelCase : Any = { "vocab_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } lowerCamelCase : int = { "vocab_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } lowerCamelCase : Optional[int] = { "vocab_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json" ), }, } lowerCamelCase : Union[str, Any] = { "facebook/dpr-ctx_encoder-single-nq-base": 5_1_2, "facebook/dpr-ctx_encoder-multiset-base": 5_1_2, } lowerCamelCase : str = { "facebook/dpr-question_encoder-single-nq-base": 5_1_2, "facebook/dpr-question_encoder-multiset-base": 5_1_2, } lowerCamelCase : Tuple = { "facebook/dpr-reader-single-nq-base": 5_1_2, "facebook/dpr-reader-multiset-base": 5_1_2, } lowerCamelCase : List[Any] = { "facebook/dpr-ctx_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-ctx_encoder-multiset-base": {"do_lower_case": True}, } lowerCamelCase : List[str] = { "facebook/dpr-question_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-question_encoder-multiset-base": {"do_lower_case": True}, } lowerCamelCase : int = { "facebook/dpr-reader-single-nq-base": {"do_lower_case": True}, "facebook/dpr-reader-multiset-base": {"do_lower_case": True}, } class A__ ( A__ ): A__ = VOCAB_FILES_NAMES A__ = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP A__ = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION A__ = DPRContextEncoderTokenizer class A__ ( A__ ): A__ = VOCAB_FILES_NAMES A__ = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP A__ = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION A__ = DPRQuestionEncoderTokenizer lowerCamelCase : int = collections.namedtuple( "DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"] ) lowerCamelCase : Optional[Any] = collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"]) lowerCamelCase : Union[str, Any] = r"\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `'tf'`: Return TensorFlow `tf.constant` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer's default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Return:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n " @add_start_docstrings(A__ ) class A__ : def __call__( self : Dict , _a : Optional[int] , _a : Optional[str] = None , _a : Optional[str] = None , _a : Union[bool, str] = False , _a : Union[bool, str] = False , _a : Optional[int] = None , _a : Optional[Union[str, TensorType]] = None , _a : Optional[bool] = None , **_a : Optional[Any] , ) -> BatchEncoding: '''simple docstring''' if titles is None and texts is None: return super().__call__( _a , padding=_a , truncation=_a , max_length=_a , return_tensors=_a , return_attention_mask=_a , **_a , ) elif titles is None or texts is None: _SCREAMING_SNAKE_CASE =titles if texts is None else texts return super().__call__( _a , _a , padding=_a , truncation=_a , max_length=_a , return_tensors=_a , return_attention_mask=_a , **_a , ) _SCREAMING_SNAKE_CASE =titles if not isinstance(_a , _a ) else [titles] _SCREAMING_SNAKE_CASE =texts if not isinstance(_a , _a ) else [texts] _SCREAMING_SNAKE_CASE =len(_a ) _SCREAMING_SNAKE_CASE =questions if not isinstance(_a , _a ) else [questions] * n_passages assert len(_a ) == len( _a ), f"There should be as many titles than texts but got {len(_a )} titles and {len(_a )} texts." _SCREAMING_SNAKE_CASE =super().__call__(_a , _a , padding=_a , truncation=_a )['input_ids'] _SCREAMING_SNAKE_CASE =super().__call__(_a , add_special_tokens=_a , padding=_a , truncation=_a )['input_ids'] _SCREAMING_SNAKE_CASE ={ 'input_ids': [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(_a , _a ) ] } if return_attention_mask is not False: _SCREAMING_SNAKE_CASE =[] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) _SCREAMING_SNAKE_CASE =attention_mask return self.pad(_a , padding=_a , max_length=_a , return_tensors=_a ) def A ( self : Optional[Any] , _a : BatchEncoding , _a : DPRReaderOutput , _a : int = 16 , _a : int = 64 , _a : int = 4 , ) -> List[DPRSpanPrediction]: '''simple docstring''' _SCREAMING_SNAKE_CASE =reader_input['input_ids'] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =reader_output[:3] _SCREAMING_SNAKE_CASE =len(_a ) _SCREAMING_SNAKE_CASE =sorted(range(_a ) , reverse=_a , key=relevance_logits.__getitem__ ) _SCREAMING_SNAKE_CASE =[] for doc_id in sorted_docs: _SCREAMING_SNAKE_CASE =list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence _SCREAMING_SNAKE_CASE =sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: _SCREAMING_SNAKE_CASE =sequence_ids.index(self.pad_token_id ) else: _SCREAMING_SNAKE_CASE =len(_a ) _SCREAMING_SNAKE_CASE =self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=_a , top_spans=_a , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=_a , start_index=_a , end_index=_a , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(_a ) >= num_spans: break return nbest_spans_predictions[:num_spans] def A ( self : List[Any] , _a : List[int] , _a : List[int] , _a : int , _a : int , ) -> List[DPRSpanPrediction]: '''simple docstring''' _SCREAMING_SNAKE_CASE =[] for start_index, start_score in enumerate(_a ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) _SCREAMING_SNAKE_CASE =sorted(_a , key=lambda _a : x[1] , reverse=_a ) _SCREAMING_SNAKE_CASE =[] for (start_index, end_index), score in scores: assert start_index <= end_index, f"Wrong span indices: [{start_index}:{end_index}]" _SCREAMING_SNAKE_CASE =end_index - start_index + 1 assert length <= max_answer_length, f"Span is too long: {length} > {max_answer_length}" if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(_a ) == top_spans: break return chosen_span_intervals @add_end_docstrings(A__ ) class A__ ( A__ , A__ ): A__ = VOCAB_FILES_NAMES A__ = READER_PRETRAINED_VOCAB_FILES_MAP A__ = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = READER_PRETRAINED_INIT_CONFIGURATION A__ = ['input_ids', 'attention_mask'] A__ = DPRReaderTokenizer
47
'''simple docstring''' import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def _lowerCAmelCase ( _UpperCamelCase : Dict , _UpperCamelCase : Any=False ) -> Optional[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =OmegaConf.load(_UpperCamelCase ) if display: print(yaml.dump(OmegaConf.to_container(_UpperCamelCase ) ) ) return config def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : Optional[Any]=None , _UpperCamelCase : Union[str, Any]=None ) -> Optional[Any]: """simple docstring""" if conf_path is None: _SCREAMING_SNAKE_CASE ='./model_checkpoints/vqgan_only.yaml' _SCREAMING_SNAKE_CASE =load_config(_UpperCamelCase , display=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =VQModel(**config.model.params ) if ckpt_path is None: _SCREAMING_SNAKE_CASE ='./model_checkpoints/vqgan_only.pt' _SCREAMING_SNAKE_CASE =torch.load(_UpperCamelCase , map_location=_UpperCamelCase ) if ".ckpt" in ckpt_path: _SCREAMING_SNAKE_CASE =sd['state_dict'] model.load_state_dict(_UpperCamelCase , strict=_UpperCamelCase ) model.to(_UpperCamelCase ) del sd return model def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : int ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =model.encode(_UpperCamelCase ) print(f"VQGAN --- {model.__class__.__name__}: latent shape: {z.shape[2:]}" ) _SCREAMING_SNAKE_CASE =model.decode(_UpperCamelCase ) return xrec def _lowerCAmelCase ( _UpperCamelCase : Dict , _UpperCamelCase : List[str]=False ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =string.rsplit('.' , 1 ) if reload: _SCREAMING_SNAKE_CASE =importlib.import_module(_UpperCamelCase ) importlib.reload(_UpperCamelCase ) return getattr(importlib.import_module(_UpperCamelCase , package=_UpperCamelCase ) , cls ) def _lowerCAmelCase ( _UpperCamelCase : str ) -> List[str]: """simple docstring""" if "target" not in config: raise KeyError('Expected key `target` to instantiate.' ) return get_obj_from_str(config['target'] )(**config.get('params' , {} ) ) def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : List[Any] , _UpperCamelCase : List[str]=True , _UpperCamelCase : int=True ) -> Union[str, Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =instantiate_from_config(_UpperCamelCase ) if sd is not None: model.load_state_dict(_UpperCamelCase ) if gpu: model.cuda() if eval_mode: model.eval() return {"model": model} def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Optional[Any] , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Optional[int] ) -> List[Any]: """simple docstring""" if ckpt: _SCREAMING_SNAKE_CASE =torch.load(_UpperCamelCase , map_location='cpu' ) _SCREAMING_SNAKE_CASE =pl_sd['global_step'] print(f"loaded model from global step {global_step}." ) else: _SCREAMING_SNAKE_CASE ={'state_dict': None} _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =load_model_from_config(config.model , pl_sd['state_dict'] , gpu=_UpperCamelCase , eval_mode=_UpperCamelCase )['model'] return model, global_step
47
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCamelCase : str = logging.get_logger(__name__) lowerCamelCase : Dict = { "google/bigbird-roberta-base": "https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json", "google/bigbird-roberta-large": "https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json", "google/bigbird-base-trivia-itc": "https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json", # See all BigBird models at https://huggingface.co/models?filter=big_bird } class A__ ( A__ ): A__ = 'big_bird' def __init__( self : Any , _a : Dict=5_0358 , _a : int=768 , _a : Tuple=12 , _a : Dict=12 , _a : Optional[Any]=3072 , _a : Dict="gelu_new" , _a : str=0.1 , _a : str=0.1 , _a : Any=4096 , _a : Dict=2 , _a : Optional[Any]=0.02 , _a : Union[str, Any]=1e-12 , _a : List[Any]=True , _a : Dict=0 , _a : Union[str, Any]=1 , _a : List[str]=2 , _a : int=66 , _a : Optional[int]="block_sparse" , _a : Any=True , _a : Union[str, Any]=False , _a : str=64 , _a : Optional[Any]=3 , _a : List[str]=None , **_a : List[str] , ) -> str: '''simple docstring''' super().__init__( pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , sep_token_id=_a , **_a , ) _SCREAMING_SNAKE_CASE =vocab_size _SCREAMING_SNAKE_CASE =max_position_embeddings _SCREAMING_SNAKE_CASE =hidden_size _SCREAMING_SNAKE_CASE =num_hidden_layers _SCREAMING_SNAKE_CASE =num_attention_heads _SCREAMING_SNAKE_CASE =intermediate_size _SCREAMING_SNAKE_CASE =hidden_act _SCREAMING_SNAKE_CASE =hidden_dropout_prob _SCREAMING_SNAKE_CASE =attention_probs_dropout_prob _SCREAMING_SNAKE_CASE =initializer_range _SCREAMING_SNAKE_CASE =type_vocab_size _SCREAMING_SNAKE_CASE =layer_norm_eps _SCREAMING_SNAKE_CASE =use_cache _SCREAMING_SNAKE_CASE =rescale_embeddings _SCREAMING_SNAKE_CASE =attention_type _SCREAMING_SNAKE_CASE =use_bias _SCREAMING_SNAKE_CASE =block_size _SCREAMING_SNAKE_CASE =num_random_blocks _SCREAMING_SNAKE_CASE =classifier_dropout class A__ ( A__ ): @property def A ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": _SCREAMING_SNAKE_CASE ={0: 'batch', 1: 'choice', 2: 'sequence'} else: _SCREAMING_SNAKE_CASE ={0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
47
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase : int = {"configuration_mbart": ["MBART_PRETRAINED_CONFIG_ARCHIVE_MAP", "MBartConfig", "MBartOnnxConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[Any] = ["MBartTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Dict = ["MBartTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : int = [ "MBART_PRETRAINED_MODEL_ARCHIVE_LIST", "MBartForCausalLM", "MBartForConditionalGeneration", "MBartForQuestionAnswering", "MBartForSequenceClassification", "MBartModel", "MBartPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Union[str, Any] = [ "TFMBartForConditionalGeneration", "TFMBartModel", "TFMBartPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[Any] = [ "FlaxMBartForConditionalGeneration", "FlaxMBartForQuestionAnswering", "FlaxMBartForSequenceClassification", "FlaxMBartModel", "FlaxMBartPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys lowerCamelCase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
47
1
'''simple docstring''' def _lowerCAmelCase ( _UpperCamelCase : int = 1_00_00_00 ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE =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 ) ) ) _SCREAMING_SNAKE_CASE =[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() = }''')
47
'''simple docstring''' from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : List[Any] = logging.get_logger(__name__) lowerCamelCase : str = { "huggingface/time-series-transformer-tourism-monthly": ( "https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json" ), # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer } class A__ ( A__ ): A__ = 'time_series_transformer' A__ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self : Optional[int] , _a : Optional[int] = None , _a : Optional[int] = None , _a : str = "student_t" , _a : str = "nll" , _a : int = 1 , _a : List[int] = [1, 2, 3, 4, 5, 6, 7] , _a : Optional[Union[str, bool]] = "mean" , _a : int = 0 , _a : int = 0 , _a : int = 0 , _a : int = 0 , _a : Optional[List[int]] = None , _a : Optional[List[int]] = None , _a : int = 32 , _a : int = 32 , _a : int = 2 , _a : int = 2 , _a : int = 2 , _a : int = 2 , _a : bool = True , _a : str = "gelu" , _a : int = 64 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : int = 100 , _a : float = 0.02 , _a : Union[str, Any]=True , **_a : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =prediction_length _SCREAMING_SNAKE_CASE =context_length or prediction_length _SCREAMING_SNAKE_CASE =distribution_output _SCREAMING_SNAKE_CASE =loss _SCREAMING_SNAKE_CASE =input_size _SCREAMING_SNAKE_CASE =num_time_features _SCREAMING_SNAKE_CASE =lags_sequence _SCREAMING_SNAKE_CASE =scaling _SCREAMING_SNAKE_CASE =num_dynamic_real_features _SCREAMING_SNAKE_CASE =num_static_real_features _SCREAMING_SNAKE_CASE =num_static_categorical_features 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`' ) _SCREAMING_SNAKE_CASE =cardinality else: _SCREAMING_SNAKE_CASE =[0] 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`' ) _SCREAMING_SNAKE_CASE =embedding_dimension else: _SCREAMING_SNAKE_CASE =[min(50 , (cat + 1) // 2 ) for cat in self.cardinality] _SCREAMING_SNAKE_CASE =num_parallel_samples # Transformer architecture configuration _SCREAMING_SNAKE_CASE =input_size * len(_a ) + self._number_of_features _SCREAMING_SNAKE_CASE =d_model _SCREAMING_SNAKE_CASE =encoder_attention_heads _SCREAMING_SNAKE_CASE =decoder_attention_heads _SCREAMING_SNAKE_CASE =encoder_ffn_dim _SCREAMING_SNAKE_CASE =decoder_ffn_dim _SCREAMING_SNAKE_CASE =encoder_layers _SCREAMING_SNAKE_CASE =decoder_layers _SCREAMING_SNAKE_CASE =dropout _SCREAMING_SNAKE_CASE =attention_dropout _SCREAMING_SNAKE_CASE =activation_dropout _SCREAMING_SNAKE_CASE =encoder_layerdrop _SCREAMING_SNAKE_CASE =decoder_layerdrop _SCREAMING_SNAKE_CASE =activation_function _SCREAMING_SNAKE_CASE =init_std _SCREAMING_SNAKE_CASE =use_cache super().__init__(is_encoder_decoder=_a , **_a ) @property def A ( self : List[Any] ) -> int: '''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 )
47
1
'''simple docstring''' from __future__ import annotations def _lowerCAmelCase ( _UpperCamelCase : list[int] , _UpperCamelCase : list[int] , _UpperCamelCase : int ) -> tuple[float, list[float]]: """simple docstring""" _SCREAMING_SNAKE_CASE =list(range(len(_UpperCamelCase ) ) ) _SCREAMING_SNAKE_CASE =[v / w for v, w in zip(_UpperCamelCase , _UpperCamelCase )] index.sort(key=lambda _UpperCamelCase : ratio[i] , reverse=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =[0] * len(_UpperCamelCase ) for i in index: if weight[i] <= capacity: _SCREAMING_SNAKE_CASE =1 max_value += value[i] capacity -= weight[i] else: _SCREAMING_SNAKE_CASE =capacity / weight[i] max_value += value[i] * capacity / weight[i] break return max_value, fractions if __name__ == "__main__": import doctest doctest.testmod()
47
'''simple docstring''' import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets lowerCamelCase : List[Any] = "\\n @inproceedings{kakwani2020indicnlpsuite,\n title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}},\n author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar},\n year={2020},\n booktitle={Findings of EMNLP},\n}\n" lowerCamelCase : Optional[Any] = "\\n IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide\n variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te.\n" lowerCamelCase : int = "\nCompute IndicGLUE evaluation metric associated to each IndicGLUE dataset.\nArgs:\n predictions: list of predictions to score (as int64),\n except for 'cvit-mkb-clsr' where each prediction is a vector (of float32).\n references: list of ground truth labels corresponding to the predictions (as int64),\n except for 'cvit-mkb-clsr' where each reference is a vector (of float32).\nReturns: depending on the IndicGLUE subset, one or several of:\n \"accuracy\": Accuracy\n \"f1\": F1 score\n \"precision\": Precision@10\nExamples:\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr')\n >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'precision@10': 1.0}\n\n" def _lowerCAmelCase ( _UpperCamelCase : List[str] , _UpperCamelCase : Tuple ) -> List[Any]: """simple docstring""" return float((preds == labels).mean() ) def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Any ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =simple_accuracy(_UpperCamelCase , _UpperCamelCase ) _SCREAMING_SNAKE_CASE =float(fa_score(y_true=_UpperCamelCase , y_pred=_UpperCamelCase ) ) return { "accuracy": acc, "f1": fa, } def _lowerCAmelCase ( _UpperCamelCase : Any , _UpperCamelCase : int ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =en_sentvecs.shape[0] # mean centering _SCREAMING_SNAKE_CASE =en_sentvecs - np.mean(_UpperCamelCase , axis=0 ) _SCREAMING_SNAKE_CASE =in_sentvecs - np.mean(_UpperCamelCase , axis=0 ) _SCREAMING_SNAKE_CASE =cdist(_UpperCamelCase , _UpperCamelCase , 'cosine' ) _SCREAMING_SNAKE_CASE =np.array(range(_UpperCamelCase ) ) _SCREAMING_SNAKE_CASE =sim.argsort(axis=1 )[:, :10] _SCREAMING_SNAKE_CASE =np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def A ( self : Any ) -> List[str]: '''simple docstring''' if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('int64' ) if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32' ) ), 'references': datasets.Value('int64' ) if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32' ) ), } ) , codebase_urls=[] , reference_urls=[] , format='numpy' if self.config_name != 'cvit-mkb-clsr' else None , ) def A ( self : List[str] , _a : Tuple , _a : Optional[int] ) -> int: '''simple docstring''' if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(_a , _a )} elif self.config_name in ["wiki-ner"]: return acc_and_fa(_a , _a ) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(_a , _a )} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]' )
47
1
'''simple docstring''' import argparse import logging import os import re import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, DataCollatorForLanguageModeling, PushToHubCallback, TFAutoModelForMaskedLM, create_optimizer, ) lowerCamelCase : Any = logging.getLogger(__name__) lowerCamelCase : Optional[Any] = tf.data.AUTOTUNE def _lowerCAmelCase ( ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE =argparse.ArgumentParser(description='Train a masked language model on TPU.' ) parser.add_argument( '--pretrained_model_config' , type=_UpperCamelCase , default='roberta-base' , help='The model config to use. Note that we don\'t copy the model\'s weights, only the config!' , ) parser.add_argument( '--tokenizer' , type=_UpperCamelCase , default='unigram-tokenizer-wikitext' , help='The name of the tokenizer to load. We use the pretrained tokenizer to initialize the model\'s vocab size.' , ) parser.add_argument( '--per_replica_batch_size' , type=_UpperCamelCase , default=8 , help='Batch size per TPU core.' , ) parser.add_argument( '--no_tpu' , action='store_true' , help='If set, run on CPU and don\'t try to initialize a TPU. Useful for debugging on non-TPU instances.' , ) parser.add_argument( '--tpu_name' , type=_UpperCamelCase , help='Name of TPU resource to initialize. Should be blank on Colab, and \'local\' on TPU VMs.' , default='local' , ) parser.add_argument( '--tpu_zone' , type=_UpperCamelCase , help='Google cloud zone that TPU resource is located in. Only used for non-Colab TPU nodes.' , ) parser.add_argument( '--gcp_project' , type=_UpperCamelCase , help='Google cloud project name. Only used for non-Colab TPU nodes.' ) parser.add_argument( '--bfloat16' , action='store_true' , help='Use mixed-precision bfloat16 for training. This is the recommended lower-precision format for TPU.' , ) parser.add_argument( '--train_dataset' , type=_UpperCamelCase , help='Path to training dataset to load. If the path begins with `gs://`' ' then the dataset will be loaded from a Google Cloud Storage bucket.' , ) parser.add_argument( '--shuffle_buffer_size' , type=_UpperCamelCase , default=2**18 , help='Size of the shuffle buffer (in samples)' , ) parser.add_argument( '--eval_dataset' , type=_UpperCamelCase , help='Path to evaluation dataset to load. If the path begins with `gs://`' ' then the dataset will be loaded from a Google Cloud Storage bucket.' , ) parser.add_argument( '--num_epochs' , type=_UpperCamelCase , default=1 , help='Number of epochs to train for.' , ) parser.add_argument( '--learning_rate' , type=_UpperCamelCase , default=1E-4 , help='Learning rate to use for training.' , ) parser.add_argument( '--weight_decay_rate' , type=_UpperCamelCase , default=1E-3 , help='Weight decay rate to use for training.' , ) parser.add_argument( '--max_length' , type=_UpperCamelCase , default=5_12 , help='Maximum length of tokenized sequences. Should match the setting used in prepare_tfrecord_shards.py' , ) parser.add_argument( '--mlm_probability' , type=_UpperCamelCase , default=0.15 , help='Fraction of tokens to mask during training.' , ) parser.add_argument('--output_dir' , type=_UpperCamelCase , required=_UpperCamelCase , help='Path to save model checkpoints to.' ) parser.add_argument('--hub_model_id' , type=_UpperCamelCase , help='Model ID to upload to on the Hugging Face Hub.' ) _SCREAMING_SNAKE_CASE =parser.parse_args() return args def _lowerCAmelCase ( _UpperCamelCase : Any ) -> int: """simple docstring""" try: if args.tpu_name: _SCREAMING_SNAKE_CASE =tf.distribute.cluster_resolver.TPUClusterResolver( args.tpu_name , zone=args.tpu_zone , project=args.gcp_project ) else: _SCREAMING_SNAKE_CASE =tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: raise RuntimeError( 'Couldn\'t connect to TPU! Most likely you need to specify --tpu_name, --tpu_zone, or ' '--gcp_project. When running on a TPU VM, use --tpu_name local.' ) tf.config.experimental_connect_to_cluster(_UpperCamelCase ) tf.tpu.experimental.initialize_tpu_system(_UpperCamelCase ) return tpu def _lowerCAmelCase ( _UpperCamelCase : List[Any] ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =0 for file in file_list: _SCREAMING_SNAKE_CASE =file.split('/' )[-1] _SCREAMING_SNAKE_CASE =re.search(r'-\d+-(\d+)\.tfrecord' , _UpperCamelCase ).group(1 ) _SCREAMING_SNAKE_CASE =int(_UpperCamelCase ) num_samples += sample_count return num_samples def _lowerCAmelCase ( _UpperCamelCase : List[Any] , _UpperCamelCase : Dict , _UpperCamelCase : Dict , _UpperCamelCase : Optional[Any] , _UpperCamelCase : Any , _UpperCamelCase : str=None ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE =count_samples(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =tf.data.Dataset.from_tensor_slices(_UpperCamelCase ) if shuffle: _SCREAMING_SNAKE_CASE =dataset.shuffle(len(_UpperCamelCase ) ) _SCREAMING_SNAKE_CASE =tf.data.TFRecordDataset(_UpperCamelCase , num_parallel_reads=_UpperCamelCase ) # TF can't infer the total sample count because it doesn't read all the records yet, so we assert it here _SCREAMING_SNAKE_CASE =dataset.apply(tf.data.experimental.assert_cardinality(_UpperCamelCase ) ) _SCREAMING_SNAKE_CASE =dataset.map(_UpperCamelCase , num_parallel_calls=_UpperCamelCase ) if shuffle: assert shuffle_buffer_size is not None _SCREAMING_SNAKE_CASE =dataset.shuffle(args.shuffle_buffer_size ) _SCREAMING_SNAKE_CASE =dataset.batch(_UpperCamelCase , drop_remainder=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =dataset.map(_UpperCamelCase , num_parallel_calls=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =dataset.prefetch(_UpperCamelCase ) return dataset def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] ) -> Tuple: """simple docstring""" if not args.no_tpu: _SCREAMING_SNAKE_CASE =initialize_tpu(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =tf.distribute.TPUStrategy(_UpperCamelCase ) else: _SCREAMING_SNAKE_CASE =tf.distribute.OneDeviceStrategy(device='/gpu:0' ) if args.bfloataa: tf.keras.mixed_precision.set_global_policy('mixed_bfloat16' ) _SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(args.tokenizer ) _SCREAMING_SNAKE_CASE =AutoConfig.from_pretrained(args.pretrained_model_config ) _SCREAMING_SNAKE_CASE =tokenizer.vocab_size _SCREAMING_SNAKE_CASE =tf.io.gfile.glob(os.path.join(args.train_dataset , '*.tfrecord' ) ) if not training_records: raise ValueError(f"No .tfrecord files found in {args.train_dataset}." ) _SCREAMING_SNAKE_CASE =tf.io.gfile.glob(os.path.join(args.eval_dataset , '*.tfrecord' ) ) if not eval_records: raise ValueError(f"No .tfrecord files found in {args.eval_dataset}." ) _SCREAMING_SNAKE_CASE =count_samples(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =num_train_samples // (args.per_replica_batch_size * strategy.num_replicas_in_sync) _SCREAMING_SNAKE_CASE =steps_per_epoch * args.num_epochs with strategy.scope(): _SCREAMING_SNAKE_CASE =TFAutoModelForMaskedLM.from_config(_UpperCamelCase ) model(model.dummy_inputs ) # Pass some dummy inputs through the model to ensure all the weights are built _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =create_optimizer( num_train_steps=_UpperCamelCase , num_warmup_steps=total_train_steps // 20 , init_lr=args.learning_rate , weight_decay_rate=args.weight_decay_rate , ) # Transformers models compute the right loss for their task by default when labels are passed, and will # use this for training unless you specify your own loss function in compile(). model.compile(optimizer=_UpperCamelCase , metrics=['accuracy'] ) def decode_fn(_UpperCamelCase : Any ): _SCREAMING_SNAKE_CASE ={ 'input_ids': tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), 'attention_mask': tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), } return tf.io.parse_single_example(_UpperCamelCase , _UpperCamelCase ) # Many of the data collators in Transformers are TF-compilable when return_tensors == "tf", so we can # use their methods in our data pipeline. _SCREAMING_SNAKE_CASE =DataCollatorForLanguageModeling( tokenizer=_UpperCamelCase , mlm_probability=args.mlm_probability , mlm=_UpperCamelCase , return_tensors='tf' ) def mask_with_collator(_UpperCamelCase : List[str] ): # TF really needs an isin() function _SCREAMING_SNAKE_CASE =( ~tf.cast(batch['attention_mask'] , tf.bool ) | (batch['input_ids'] == tokenizer.cls_token_id) | (batch['input_ids'] == tokenizer.sep_token_id) ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =data_collator.tf_mask_tokens( batch['input_ids'] , vocab_size=len(_UpperCamelCase ) , mask_token_id=tokenizer.mask_token_id , special_tokens_mask=_UpperCamelCase , ) return batch _SCREAMING_SNAKE_CASE =args.per_replica_batch_size * strategy.num_replicas_in_sync _SCREAMING_SNAKE_CASE =prepare_dataset( _UpperCamelCase , decode_fn=_UpperCamelCase , mask_fn=_UpperCamelCase , batch_size=_UpperCamelCase , shuffle=_UpperCamelCase , shuffle_buffer_size=args.shuffle_buffer_size , ) _SCREAMING_SNAKE_CASE =prepare_dataset( _UpperCamelCase , decode_fn=_UpperCamelCase , mask_fn=_UpperCamelCase , batch_size=_UpperCamelCase , shuffle=_UpperCamelCase , ) _SCREAMING_SNAKE_CASE =[] if args.hub_model_id: callbacks.append( PushToHubCallback(output_dir=args.output_dir , hub_model_id=args.hub_model_id , tokenizer=_UpperCamelCase ) ) model.fit( _UpperCamelCase , validation_data=_UpperCamelCase , epochs=args.num_epochs , callbacks=_UpperCamelCase , ) model.save_pretrained(args.output_dir ) if __name__ == "__main__": lowerCamelCase : Union[str, Any] = parse_args() main(args)
47
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase : Dict = logging.get_logger(__name__) lowerCamelCase : List[Any] = { "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json", } class A__ ( A__ ): A__ = 'deta' A__ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Tuple , _a : Optional[int]=None , _a : int=900 , _a : Optional[Any]=2048 , _a : int=6 , _a : Tuple=2048 , _a : Optional[int]=8 , _a : Any=6 , _a : str=1024 , _a : int=8 , _a : int=0.0 , _a : Optional[Any]=True , _a : Tuple="relu" , _a : Union[str, Any]=256 , _a : Tuple=0.1 , _a : str=0.0 , _a : Dict=0.0 , _a : Tuple=0.02 , _a : Union[str, Any]=1.0 , _a : Any=True , _a : Tuple=False , _a : List[Any]="sine" , _a : str=5 , _a : List[Any]=4 , _a : str=4 , _a : Union[str, Any]=True , _a : Optional[int]=300 , _a : Dict=True , _a : List[Any]=True , _a : List[Any]=1 , _a : List[str]=5 , _a : int=2 , _a : Dict=1 , _a : str=1 , _a : Optional[Any]=5 , _a : Union[str, Any]=2 , _a : List[str]=0.1 , _a : List[Any]=0.25 , **_a : Union[str, Any] , ) -> List[str]: '''simple docstring''' if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) _SCREAMING_SNAKE_CASE =CONFIG_MAPPING['resnet'](out_features=['stage2', 'stage3', 'stage4'] ) else: if isinstance(_a , _a ): _SCREAMING_SNAKE_CASE =backbone_config.pop('model_type' ) _SCREAMING_SNAKE_CASE =CONFIG_MAPPING[backbone_model_type] _SCREAMING_SNAKE_CASE =config_class.from_dict(_a ) _SCREAMING_SNAKE_CASE =backbone_config _SCREAMING_SNAKE_CASE =num_queries _SCREAMING_SNAKE_CASE =max_position_embeddings _SCREAMING_SNAKE_CASE =d_model _SCREAMING_SNAKE_CASE =encoder_ffn_dim _SCREAMING_SNAKE_CASE =encoder_layers _SCREAMING_SNAKE_CASE =encoder_attention_heads _SCREAMING_SNAKE_CASE =decoder_ffn_dim _SCREAMING_SNAKE_CASE =decoder_layers _SCREAMING_SNAKE_CASE =decoder_attention_heads _SCREAMING_SNAKE_CASE =dropout _SCREAMING_SNAKE_CASE =attention_dropout _SCREAMING_SNAKE_CASE =activation_dropout _SCREAMING_SNAKE_CASE =activation_function _SCREAMING_SNAKE_CASE =init_std _SCREAMING_SNAKE_CASE =init_xavier_std _SCREAMING_SNAKE_CASE =encoder_layerdrop _SCREAMING_SNAKE_CASE =auxiliary_loss _SCREAMING_SNAKE_CASE =position_embedding_type # deformable attributes _SCREAMING_SNAKE_CASE =num_feature_levels _SCREAMING_SNAKE_CASE =encoder_n_points _SCREAMING_SNAKE_CASE =decoder_n_points _SCREAMING_SNAKE_CASE =two_stage _SCREAMING_SNAKE_CASE =two_stage_num_proposals _SCREAMING_SNAKE_CASE =with_box_refine _SCREAMING_SNAKE_CASE =assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError('If two_stage is True, with_box_refine must be True.' ) # Hungarian matcher _SCREAMING_SNAKE_CASE =class_cost _SCREAMING_SNAKE_CASE =bbox_cost _SCREAMING_SNAKE_CASE =giou_cost # Loss coefficients _SCREAMING_SNAKE_CASE =mask_loss_coefficient _SCREAMING_SNAKE_CASE =dice_loss_coefficient _SCREAMING_SNAKE_CASE =bbox_loss_coefficient _SCREAMING_SNAKE_CASE =giou_loss_coefficient _SCREAMING_SNAKE_CASE =eos_coefficient _SCREAMING_SNAKE_CASE =focal_alpha super().__init__(is_encoder_decoder=_a , **_a ) @property def A ( self : Dict ) -> int: '''simple docstring''' return self.encoder_attention_heads @property def A ( self : List[Any] ) -> int: '''simple docstring''' return self.d_model def A ( self : Optional[int] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =copy.deepcopy(self.__dict__ ) _SCREAMING_SNAKE_CASE =self.backbone_config.to_dict() _SCREAMING_SNAKE_CASE =self.__class__.model_type return output
47
1
'''simple docstring''' def _lowerCAmelCase ( _UpperCamelCase : dict ) -> bool: """simple docstring""" _SCREAMING_SNAKE_CASE =set() # To detect a back edge, keep track of vertices currently in the recursion stack _SCREAMING_SNAKE_CASE =set() return any( node not in visited and depth_first_search(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) for node in graph ) def _lowerCAmelCase ( _UpperCamelCase : dict , _UpperCamelCase : int , _UpperCamelCase : set , _UpperCamelCase : set ) -> bool: """simple docstring""" visited.add(_UpperCamelCase ) rec_stk.add(_UpperCamelCase ) for node in graph[vertex]: if node not in visited: if depth_first_search(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return True elif node in rec_stk: return True # The node needs to be removed from recursion stack before function ends rec_stk.remove(_UpperCamelCase ) return False if __name__ == "__main__": from doctest import testmod testmod()
47
'''simple docstring''' import numpy as np from PIL import Image def _lowerCAmelCase ( _UpperCamelCase : np.ndarray , _UpperCamelCase : int , _UpperCamelCase : int ) -> np.ndarray: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 # compute the shape of the output matrix _SCREAMING_SNAKE_CASE =(arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape _SCREAMING_SNAKE_CASE =np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix _SCREAMING_SNAKE_CASE =np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 return updated_arr def _lowerCAmelCase ( _UpperCamelCase : np.ndarray , _UpperCamelCase : int , _UpperCamelCase : int ) -> np.ndarray: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 # compute the shape of the output matrix _SCREAMING_SNAKE_CASE =(arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape _SCREAMING_SNAKE_CASE =np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix _SCREAMING_SNAKE_CASE =int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name="avgpooling", verbose=True) # Loading the image lowerCamelCase : Optional[Any] = Image.open("path_to_image") # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
47
1
'''simple docstring''' import warnings from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A__ ( A__ ): A__ = ['image_processor', 'tokenizer'] A__ = 'FlavaImageProcessor' A__ = ('BertTokenizer', 'BertTokenizerFast') def __init__( self : Optional[Any] , _a : Tuple=None , _a : Optional[Any]=None , **_a : List[str] ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , _a , ) _SCREAMING_SNAKE_CASE =kwargs.pop('feature_extractor' ) _SCREAMING_SNAKE_CASE =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(_a , _a ) _SCREAMING_SNAKE_CASE =self.image_processor def __call__( self : List[str] , _a : Optional[ImageInput] = None , _a : Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None , _a : bool = True , _a : Union[bool, str, PaddingStrategy] = False , _a : Union[bool, str, TruncationStrategy] = False , _a : Optional[int] = None , _a : int = 0 , _a : Optional[int] = None , _a : Optional[bool] = None , _a : Optional[bool] = None , _a : Optional[bool] = None , _a : Optional[bool] = None , _a : bool = False , _a : bool = False , _a : bool = False , _a : bool = False , _a : bool = True , _a : Optional[Union[str, TensorType]] = None , **_a : str , ) -> Tuple: '''simple docstring''' if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: _SCREAMING_SNAKE_CASE =self.tokenizer( text=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_token_type_ids=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) if images is not None: _SCREAMING_SNAKE_CASE =self.image_processor( _a , return_image_mask=_a , return_codebook_pixels=_a , return_tensors=_a , **_a , ) if text is not None and images is not None: encoding.update(_a ) return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**_a ) , tensor_type=_a ) def A ( self : Dict , *_a : Optional[Any] , **_a : Tuple ) -> List[Any]: '''simple docstring''' return self.tokenizer.batch_decode(*_a , **_a ) def A ( self : List[str] , *_a : Optional[Any] , **_a : List[Any] ) -> List[Any]: '''simple docstring''' return self.tokenizer.decode(*_a , **_a ) @property def A ( self : Any ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.tokenizer.model_input_names _SCREAMING_SNAKE_CASE =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def A ( self : Optional[int] ) -> Dict: '''simple docstring''' warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , _a , ) return self.image_processor_class @property def A ( self : Optional[Any] ) -> Dict: '''simple docstring''' warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , _a , ) return self.image_processor
47
'''simple docstring''' import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _lowerCAmelCase ( ) -> Any: """simple docstring""" _SCREAMING_SNAKE_CASE =ArgumentParser( description=( 'PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes' ) ) # Optional arguments for the launch helper parser.add_argument('--num_cores' , type=_UpperCamelCase , default=1 , help='Number of TPU cores to use (1 or 8).' ) # positional parser.add_argument( 'training_script' , type=_UpperCamelCase , help=( 'The full path to the single TPU training ' 'program/script to be launched in parallel, ' 'followed by all the arguments for the ' 'training script' ) , ) # rest from the training program parser.add_argument('training_script_args' , nargs=_UpperCamelCase ) return parser.parse_args() def _lowerCAmelCase ( ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =parse_args() # Import training_script as a module. _SCREAMING_SNAKE_CASE =Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) _SCREAMING_SNAKE_CASE =script_fpath.stem _SCREAMING_SNAKE_CASE =importlib.import_module(_UpperCamelCase ) # Patch sys.argv _SCREAMING_SNAKE_CASE =[args.training_script] + args.training_script_args + ['--tpu_num_cores', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
47
1
'''simple docstring''' import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) lowerCamelCase : List[Any] = logging.getLogger() def _lowerCAmelCase ( _UpperCamelCase : Path , _UpperCamelCase : list ) -> Any: """simple docstring""" _SCREAMING_SNAKE_CASE ='\n'.join(_UpperCamelCase ) Path(_UpperCamelCase ).open('w' ).writelines(_UpperCamelCase ) lowerCamelCase : Tuple = "patrickvonplaten/t5-tiny-random" lowerCamelCase : Tuple = "sshleifer/bart-tiny-random" lowerCamelCase : List[Any] = "sshleifer/tiny-mbart" lowerCamelCase : str = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class A__ ( A__ ): def A ( self : Any , _a : Dict ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =Path(self.get_auto_remove_tmp_dir() ) / 'utest_input.source' _SCREAMING_SNAKE_CASE =input_file_name.parent / 'utest_output.txt' assert not output_file_name.exists() _SCREAMING_SNAKE_CASE =[' New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County.'] _dump_articles(_a , _a ) _SCREAMING_SNAKE_CASE =str(Path(self.get_auto_remove_tmp_dir() ) / 'scores.json' ) _SCREAMING_SNAKE_CASE ='translation_en_to_de' if model == T5_TINY else 'summarization' _SCREAMING_SNAKE_CASE =f"\n run_eval_search.py\n {model}\n {input_file_name}\n {output_file_name}\n --score_path {score_path}\n --task {task}\n --num_beams 2\n --length_penalty 2.0\n ".split() with patch.object(_a , 'argv' , _a ): run_generate() assert Path(_a ).exists() # os.remove(Path(output_file_name)) def A ( self : List[str] ) -> str: '''simple docstring''' self.run_eval_tester(_a ) @parameterized.expand([BART_TINY, MBART_TINY] ) @slow def A ( self : Optional[Any] , _a : Tuple ) -> List[str]: '''simple docstring''' self.run_eval_tester(_a ) @parameterized.expand([T5_TINY, MBART_TINY] ) @slow def A ( self : Dict , _a : Dict ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =Path(self.get_auto_remove_tmp_dir() ) / 'utest_input.source' _SCREAMING_SNAKE_CASE =input_file_name.parent / 'utest_output.txt' assert not output_file_name.exists() _SCREAMING_SNAKE_CASE ={ 'en': ['Machine learning is great, isn\'t it?', 'I like to eat bananas', 'Tomorrow is another great day!'], 'de': [ 'Maschinelles Lernen ist großartig, oder?', 'Ich esse gerne Bananen', 'Morgen ist wieder ein toller Tag!', ], } _SCREAMING_SNAKE_CASE =Path(self.get_auto_remove_tmp_dir() ) _SCREAMING_SNAKE_CASE =str(tmp_dir / 'scores.json' ) _SCREAMING_SNAKE_CASE =str(tmp_dir / 'val.target' ) _dump_articles(_a , text['en'] ) _dump_articles(_a , text['de'] ) _SCREAMING_SNAKE_CASE ='translation_en_to_de' if model == T5_TINY else 'summarization' _SCREAMING_SNAKE_CASE =f"\n run_eval_search.py\n {model}\n {str(_a )}\n {str(_a )}\n --score_path {score_path}\n --reference_path {reference_path}\n --task {task}\n ".split() testargs.extend(['--search', 'num_beams=1:2 length_penalty=0.9:1.0'] ) with patch.object(_a , 'argv' , _a ): with CaptureStdout() as cs: run_search() _SCREAMING_SNAKE_CASE =[' num_beams | length_penalty', model, 'Best score args'] _SCREAMING_SNAKE_CASE =['Info'] if "translation" in task: expected_strings.append('bleu' ) else: expected_strings.extend(_a ) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(_a ).exists() os.remove(Path(_a ) )
47
'''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. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class A__ ( A__ ): A__ = ( 'This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.' 'It takes two arguments named `image` which should be the original image, and `label` which should be a text ' 'describing the elements what should be identified in the segmentation mask. The tool returns the mask.' ) A__ = 'CIDAS/clipseg-rd64-refined' A__ = 'image_segmenter' A__ = CLIPSegForImageSegmentation A__ = ['image', 'text'] A__ = ['image'] def __init__( self : Any , *_a : Dict , **_a : str ) -> Any: '''simple docstring''' requires_backends(self , ['vision'] ) super().__init__(*_a , **_a ) def A ( self : int , _a : "Image" , _a : str ) -> Optional[Any]: '''simple docstring''' return self.pre_processor(text=[label] , images=[image] , padding=_a , return_tensors='pt' ) def A ( self : Dict , _a : Dict ) -> str: '''simple docstring''' with torch.no_grad(): _SCREAMING_SNAKE_CASE =self.model(**_a ).logits return logits def A ( self : Any , _a : str ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =outputs.cpu().detach().numpy() _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =1 return Image.fromarray((array * 255).astype(np.uinta ) )
47
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase : Tuple = { "configuration_maskformer": ["MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "MaskFormerConfig"], "configuration_maskformer_swin": ["MaskFormerSwinConfig"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[str] = ["MaskFormerFeatureExtractor"] lowerCamelCase : str = ["MaskFormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : int = [ "MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "MaskFormerForInstanceSegmentation", "MaskFormerModel", "MaskFormerPreTrainedModel", ] lowerCamelCase : List[str] = [ "MaskFormerSwinBackbone", "MaskFormerSwinModel", "MaskFormerSwinPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig from .configuration_maskformer_swin import MaskFormerSwinConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_maskformer import MaskFormerFeatureExtractor from .image_processing_maskformer import MaskFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskformer import ( MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskFormerForInstanceSegmentation, MaskFormerModel, MaskFormerPreTrainedModel, ) from .modeling_maskformer_swin import ( MaskFormerSwinBackbone, MaskFormerSwinModel, MaskFormerSwinPreTrainedModel, ) else: import sys lowerCamelCase : int = _LazyModule(__name__, globals()["__file__"], _import_structure)
47
'''simple docstring''' from __future__ import annotations import math def _lowerCAmelCase ( _UpperCamelCase : int ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_UpperCamelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowerCAmelCase ( _UpperCamelCase : int ) -> list[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =str(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =[n] for i in range(1 , len(_UpperCamelCase ) ): list_nums.append(int(str_num[i:] ) ) list_nums.append(int(str_num[:-i] ) ) return list_nums def _lowerCAmelCase ( _UpperCamelCase : int ) -> bool: """simple docstring""" if len(str(_UpperCamelCase ) ) > 3: if not is_prime(int(str(_UpperCamelCase )[-3:] ) ) or not is_prime(int(str(_UpperCamelCase )[:3] ) ): return False return True def _lowerCAmelCase ( _UpperCamelCase : int = 11 ) -> list[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =13 while len(_UpperCamelCase ) != count: if validate(_UpperCamelCase ): _SCREAMING_SNAKE_CASE =list_truncated_nums(_UpperCamelCase ) if all(is_prime(_UpperCamelCase ) for i in list_nums ): list_truncated_primes.append(_UpperCamelCase ) num += 2 return list_truncated_primes def _lowerCAmelCase ( ) -> int: """simple docstring""" return sum(compute_truncated_primes(11 ) ) if __name__ == "__main__": print(f'''{sum(compute_truncated_primes(1_1)) = }''')
47
1
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_camembert import CamembertTokenizer else: lowerCamelCase : Optional[int] = None lowerCamelCase : int = logging.get_logger(__name__) lowerCamelCase : Tuple = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} lowerCamelCase : Optional[int] = { "vocab_file": { "camembert-base": "https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model", }, "tokenizer_file": { "camembert-base": "https://huggingface.co/camembert-base/resolve/main/tokenizer.json", }, } lowerCamelCase : List[Any] = { "camembert-base": 5_1_2, } lowerCamelCase : List[Any] = "▁" class A__ ( A__ ): A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = ['input_ids', 'attention_mask'] A__ = CamembertTokenizer def __init__( self : List[Any] , _a : Optional[Any]=None , _a : Optional[Any]=None , _a : Union[str, Any]="<s>" , _a : Dict="</s>" , _a : Tuple="</s>" , _a : List[Any]="<s>" , _a : Optional[int]="<unk>" , _a : Dict="<pad>" , _a : List[Any]="<mask>" , _a : Dict=["<s>NOTUSED", "</s>NOTUSED"] , **_a : str , ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token super().__init__( _a , tokenizer_file=_a , bos_token=_a , eos_token=_a , sep_token=_a , cls_token=_a , unk_token=_a , pad_token=_a , mask_token=_a , additional_special_tokens=_a , **_a , ) _SCREAMING_SNAKE_CASE =vocab_file _SCREAMING_SNAKE_CASE =False if not self.vocab_file else True def A ( self : List[Any] , _a : List[int] , _a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _SCREAMING_SNAKE_CASE =[self.cls_token_id] _SCREAMING_SNAKE_CASE =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def A ( self : int , _a : List[int] , _a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =[self.sep_token_id] _SCREAMING_SNAKE_CASE =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def A ( self : Optional[int] , _a : str , _a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(_a ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return _SCREAMING_SNAKE_CASE =os.path.join( _a , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ): copyfile(self.vocab_file , _a ) return (out_vocab_file,)
47
'''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: lowerCamelCase : int = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class A__ ( unittest.TestCase ): def __init__( self : List[str] , _a : List[Any] , _a : List[str]=7 , _a : List[str]=3 , _a : Tuple=18 , _a : Tuple=30 , _a : str=400 , _a : Tuple=None , _a : Union[str, Any]=True , _a : List[str]=True , _a : Optional[int]=None , ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =size if size is not None else {'height': 20, 'width': 20} _SCREAMING_SNAKE_CASE =parent _SCREAMING_SNAKE_CASE =batch_size _SCREAMING_SNAKE_CASE =num_channels _SCREAMING_SNAKE_CASE =image_size _SCREAMING_SNAKE_CASE =min_resolution _SCREAMING_SNAKE_CASE =max_resolution _SCREAMING_SNAKE_CASE =size _SCREAMING_SNAKE_CASE =do_normalize _SCREAMING_SNAKE_CASE =do_convert_rgb _SCREAMING_SNAKE_CASE =[512, 1024, 2048, 4096] _SCREAMING_SNAKE_CASE =patch_size if patch_size is not None else {'height': 16, 'width': 16} def A ( self : Any ) -> List[str]: '''simple docstring''' return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def A ( self : int ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE ='https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg' _SCREAMING_SNAKE_CASE =Image.open(requests.get(_a , stream=_a ).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 A__ ( A__ , unittest.TestCase ): A__ = PixaStructImageProcessor if is_vision_available() else None def A ( self : Dict ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =PixaStructImageProcessingTester(self ) @property def A ( self : Optional[Any] ) -> int: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def A ( self : Any ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_a , 'do_normalize' ) ) self.assertTrue(hasattr(_a , 'do_convert_rgb' ) ) def A ( self : Any ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processor_tester.prepare_dummy_image() _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) _SCREAMING_SNAKE_CASE =2048 _SCREAMING_SNAKE_CASE =image_processor(_a , return_tensors='pt' , max_patches=_a ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.06_06 ) , atol=1e-3 , rtol=1e-3 ) ) def A ( self : Any ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PIL images _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input _SCREAMING_SNAKE_CASE =( (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 _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def A ( self : List[str] ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PIL images _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input _SCREAMING_SNAKE_CASE =( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 _SCREAMING_SNAKE_CASE =True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(_a ): _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches _SCREAMING_SNAKE_CASE ='Hello' _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a , header_text=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a , header_text=_a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def A ( self : List[Any] ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , numpify=_a ) for image in image_inputs: self.assertIsInstance(_a , np.ndarray ) _SCREAMING_SNAKE_CASE =( (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 _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def A ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , torchify=_a ) for image in image_inputs: self.assertIsInstance(_a , torch.Tensor ) # Test not batched input _SCREAMING_SNAKE_CASE =( (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 _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a ).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 A__ ( A__ , unittest.TestCase ): A__ = PixaStructImageProcessor if is_vision_available() else None def A ( self : str ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =PixaStructImageProcessingTester(self , num_channels=4 ) _SCREAMING_SNAKE_CASE =3 @property def A ( self : List[str] ) -> Optional[Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def A ( self : List[str] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_a , 'do_normalize' ) ) self.assertTrue(hasattr(_a , 'do_convert_rgb' ) ) def A ( self : Dict ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PIL images _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input _SCREAMING_SNAKE_CASE =( (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 _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
47
1
'''simple docstring''' from __future__ import annotations def _lowerCAmelCase ( _UpperCamelCase : str , _UpperCamelCase : str ) -> bool: """simple docstring""" _SCREAMING_SNAKE_CASE =get_failure_array(_UpperCamelCase ) # 2) Step through text searching for pattern _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =0, 0 # index into text, pattern while i < len(_UpperCamelCase ): if pattern[j] == text[i]: if j == (len(_UpperCamelCase ) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: _SCREAMING_SNAKE_CASE =failure[j - 1] continue i += 1 return False def _lowerCAmelCase ( _UpperCamelCase : str ) -> list[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =[0] _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =1 while j < len(_UpperCamelCase ): if pattern[i] == pattern[j]: i += 1 elif i > 0: _SCREAMING_SNAKE_CASE =failure[i - 1] continue j += 1 failure.append(_UpperCamelCase ) return failure if __name__ == "__main__": # Test 1) lowerCamelCase : List[str] = "abc1abc12" lowerCamelCase : Optional[int] = "alskfjaldsabc1abc1abc12k23adsfabcabc" lowerCamelCase : Any = "alskfjaldsk23adsfabcabc" assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) lowerCamelCase : List[str] = "ABABX" lowerCamelCase : Any = "ABABZABABYABABX" assert kmp(pattern, text) # Test 3) lowerCamelCase : Optional[int] = "AAAB" lowerCamelCase : Dict = "ABAAAAAB" assert kmp(pattern, text) # Test 4) lowerCamelCase : str = "abcdabcy" lowerCamelCase : List[Any] = "abcxabcdabxabcdabcdabcy" assert kmp(pattern, text) # Test 5) lowerCamelCase : int = "aabaabaaa" assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
47
'''simple docstring''' import copy import re class A__ : A__ = 'hp' A__ = {} A__ = None @classmethod def A ( cls : Optional[Any] , _a : Optional[Any] , _a : Any ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =prefix _SCREAMING_SNAKE_CASE =defaults cls.build_naming_info() @staticmethod def A ( _a : Optional[Any] , _a : List[Any] ) -> Any: '''simple docstring''' if len(_a ) == 0: return "" _SCREAMING_SNAKE_CASE =None if any(char.isdigit() for char in word ): raise Exception(f"Parameters should not contain numbers: '{word}' contains a number" ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(_a ) + 1 ): _SCREAMING_SNAKE_CASE =word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: _SCREAMING_SNAKE_CASE =prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(_a : str ): _SCREAMING_SNAKE_CASE ='' while integer != 0: _SCREAMING_SNAKE_CASE =chr(ord('A' ) + integer % 10 ) + s integer //= 10 return s _SCREAMING_SNAKE_CASE =0 while True: _SCREAMING_SNAKE_CASE =word + '#' + int_to_alphabetic(_a ) if sword in info["reverse_short_word"]: continue else: _SCREAMING_SNAKE_CASE =sword break _SCREAMING_SNAKE_CASE =short_word _SCREAMING_SNAKE_CASE =word return short_word @staticmethod def A ( _a : Optional[Any] , _a : int ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =param_name.split('_' ) _SCREAMING_SNAKE_CASE =[TrialShortNamer.shortname_for_word(_a , _a ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name _SCREAMING_SNAKE_CASE =['', '_'] for separator in separators: _SCREAMING_SNAKE_CASE =separator.join(_a ) if shortname not in info["reverse_short_param"]: _SCREAMING_SNAKE_CASE =shortname _SCREAMING_SNAKE_CASE =param_name return shortname return param_name @staticmethod def A ( _a : Dict , _a : int ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =TrialShortNamer.shortname_for_key(_a , _a ) _SCREAMING_SNAKE_CASE =short_name _SCREAMING_SNAKE_CASE =param_name @classmethod def A ( cls : Optional[int] ) -> Tuple: '''simple docstring''' if cls.NAMING_INFO is not None: return _SCREAMING_SNAKE_CASE ={ 'short_word': {}, 'reverse_short_word': {}, 'short_param': {}, 'reverse_short_param': {}, } _SCREAMING_SNAKE_CASE =list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(_a , _a ) _SCREAMING_SNAKE_CASE =info @classmethod def A ( cls : List[Any] , _a : int ) -> int: '''simple docstring''' cls.build_naming_info() assert cls.PREFIX is not None _SCREAMING_SNAKE_CASE =[copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(f"You should provide a default value for the param name {k} with value {v}" ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue _SCREAMING_SNAKE_CASE =cls.NAMING_INFO['short_param'][k] if isinstance(_a , _a ): _SCREAMING_SNAKE_CASE =1 if v else 0 _SCREAMING_SNAKE_CASE ='' if isinstance(_a , (int, float) ) else '-' _SCREAMING_SNAKE_CASE =f"{key}{sep}{v}" name.append(_a ) return "_".join(_a ) @classmethod def A ( cls : Optional[Any] , _a : List[Any] ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =repr[len(cls.PREFIX ) + 1 :] if repr == "": _SCREAMING_SNAKE_CASE =[] else: _SCREAMING_SNAKE_CASE =repr.split('_' ) _SCREAMING_SNAKE_CASE ={} for value in values: if "-" in value: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =value.split('-' ) else: _SCREAMING_SNAKE_CASE =re.sub('[0-9.]' , '' , _a ) _SCREAMING_SNAKE_CASE =float(re.sub('[^0-9.]' , '' , _a ) ) _SCREAMING_SNAKE_CASE =cls.NAMING_INFO['reverse_short_param'][p_k] _SCREAMING_SNAKE_CASE =p_v for k in cls.DEFAULTS: if k not in parameters: _SCREAMING_SNAKE_CASE =cls.DEFAULTS[k] return parameters
47
1
'''simple docstring''' import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class A__ ( A__ ): def A ( self : Any ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =tempfile.mkdtemp() _SCREAMING_SNAKE_CASE =5 # Realm tok _SCREAMING_SNAKE_CASE =[ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'test', 'question', 'this', 'is', 'the', 'first', 'second', 'third', 'fourth', 'fifth', 'record', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] _SCREAMING_SNAKE_CASE =os.path.join(self.tmpdirname , 'realm_tokenizer' ) os.makedirs(_a , exist_ok=_a ) _SCREAMING_SNAKE_CASE =os.path.join(_a , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) _SCREAMING_SNAKE_CASE =os.path.join(self.tmpdirname , 'realm_block_records' ) os.makedirs(_a , exist_ok=_a ) def A ( self : Union[str, Any] ) -> RealmTokenizer: '''simple docstring''' return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , 'realm_tokenizer' ) ) def A ( self : int ) -> Any: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def A ( self : Optional[int] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =RealmConfig(num_block_records=self.num_block_records ) return config def A ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =Dataset.from_dict( { 'id': ['0', '1'], 'question': ['foo', 'bar'], 'answers': [['Foo', 'Bar'], ['Bar']], } ) return dataset def A ( self : int ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =np.array( [ b'This is the first record', b'This is the second record', b'This is the third record', b'This is the fourth record', b'This is the fifth record', b'This is a longer longer longer record', ] , dtype=_a , ) return block_records def A ( self : int ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def A ( self : str ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.get_config() _SCREAMING_SNAKE_CASE =self.get_dummy_retriever() _SCREAMING_SNAKE_CASE =retriever.tokenizer _SCREAMING_SNAKE_CASE =np.array([0, 3] , dtype='long' ) _SCREAMING_SNAKE_CASE =tokenizer(['Test question'] ).input_ids _SCREAMING_SNAKE_CASE =tokenizer( ['the fourth'] , add_special_tokens=_a , return_token_type_ids=_a , return_attention_mask=_a , ).input_ids _SCREAMING_SNAKE_CASE =config.reader_seq_len _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =retriever( _a , _a , answer_ids=_a , max_length=_a , return_tensors='np' ) self.assertEqual(len(_a ) , 2 ) self.assertEqual(len(_a ) , 2 ) self.assertEqual(len(_a ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ['[CLS]', 'test', 'question', '[SEP]', 'this', 'is', 'the', 'first', 'record', '[SEP]'] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ['[CLS]', 'test', 'question', '[SEP]', 'this', 'is', 'the', 'fourth', 'record', '[SEP]'] , ) def A ( self : List[Any] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.get_config() _SCREAMING_SNAKE_CASE =self.get_dummy_retriever() _SCREAMING_SNAKE_CASE =retriever.tokenizer _SCREAMING_SNAKE_CASE =np.array([0, 3, 5] , dtype='long' ) _SCREAMING_SNAKE_CASE =tokenizer(['Test question'] ).input_ids _SCREAMING_SNAKE_CASE =tokenizer( ['the fourth', 'longer longer'] , add_special_tokens=_a , return_token_type_ids=_a , return_attention_mask=_a , ).input_ids _SCREAMING_SNAKE_CASE =config.reader_seq_len _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =retriever( _a , _a , answer_ids=_a , max_length=_a , return_tensors='np' ) self.assertEqual([False, True, True] , _a ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , _a ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , _a ) def A ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , 'realm_block_records' ) ) # Test local path _SCREAMING_SNAKE_CASE =retriever.from_pretrained(os.path.join(self.tmpdirname , 'realm_block_records' ) ) self.assertEqual(retriever.block_records[0] , b'This is the first record' ) # Test mocked remote path with patch('transformers.models.realm.retrieval_realm.hf_hub_download' ) as mock_hf_hub_download: _SCREAMING_SNAKE_CASE =os.path.join( os.path.join(self.tmpdirname , 'realm_block_records' ) , _REALM_BLOCK_RECORDS_FILENAME ) _SCREAMING_SNAKE_CASE =RealmRetriever.from_pretrained('google/realm-cc-news-pretrained-openqa' ) self.assertEqual(retriever.block_records[0] , b'This is the first record' )
47
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version lowerCamelCase : Optional[int] = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt") @dataclass class A__ : A__ = field( default='cifar10' , metadata={'help': 'Name of a dataset from the datasets package'} ) A__ = field( default=A__ , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) A__ = field( default=A__ , metadata={'help': 'The column name of the images in the files.'} ) A__ = field(default=A__ , metadata={'help': 'A folder containing the training data.'} ) A__ = field(default=A__ , metadata={'help': 'A folder containing the validation data.'} ) A__ = field( default=0.15 , metadata={'help': 'Percent to split off of train for validation.'} ) A__ = field( default=A__ , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) A__ = field( default=A__ , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of evaluation examples to this ' 'value if set.' ) } , ) def A ( self : Union[str, Any] ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE ={} if self.train_dir is not None: _SCREAMING_SNAKE_CASE =self.train_dir if self.validation_dir is not None: _SCREAMING_SNAKE_CASE =self.validation_dir _SCREAMING_SNAKE_CASE =data_files if data_files else None @dataclass class A__ : A__ = field( default=A__ , metadata={ 'help': ( 'The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.' ) } , ) A__ = field( default=A__ , metadata={'help': 'Pretrained config name or path if not the same as model_name_or_path'} ) A__ = field( default=A__ , metadata={ 'help': ( 'Override some existing default config settings when a model is trained from scratch. Example: ' 'n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index' ) } , ) A__ = field( default=A__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from s3'} ) A__ = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) A__ = field(default=A__ , metadata={'help': 'Name or path of preprocessor config.'} ) A__ = field( default=A__ , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) A__ = field( default=0.75 , metadata={'help': 'The ratio of the number of masked tokens in the input sequence.'} ) A__ = field( default=A__ , metadata={'help': 'Whether or not to train with normalized pixel values as target.'} ) @dataclass class A__ ( A__ ): A__ = field( default=1E-3 , metadata={'help': 'Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'} ) def _lowerCAmelCase ( _UpperCamelCase : int ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE =torch.stack([example['pixel_values'] for example in examples] ) return {"pixel_values": pixel_values} def _lowerCAmelCase ( ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE =HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) 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. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('run_mae' , _UpperCamelCase , _UpperCamelCase ) # 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 )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _SCREAMING_SNAKE_CASE =training_args.get_process_log_level() logger.setLevel(_UpperCamelCase ) transformers.utils.logging.set_verbosity(_UpperCamelCase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # 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}" ) logger.info(f"Training/evaluation parameters {training_args}" ) # Detecting last checkpoint. _SCREAMING_SNAKE_CASE =None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _SCREAMING_SNAKE_CASE =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 and training_args.resume_from_checkpoint is 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.' ) # Initialize our dataset. _SCREAMING_SNAKE_CASE =load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. _SCREAMING_SNAKE_CASE =None if 'validation' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , _UpperCamelCase ) and data_args.train_val_split > 0.0: _SCREAMING_SNAKE_CASE =ds['train'].train_test_split(data_args.train_val_split ) _SCREAMING_SNAKE_CASE =split['train'] _SCREAMING_SNAKE_CASE =split['test'] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _SCREAMING_SNAKE_CASE ={ 'cache_dir': model_args.cache_dir, 'revision': model_args.model_revision, 'use_auth_token': True if model_args.use_auth_token else None, } if model_args.config_name: _SCREAMING_SNAKE_CASE =ViTMAEConfig.from_pretrained(model_args.config_name , **_UpperCamelCase ) elif model_args.model_name_or_path: _SCREAMING_SNAKE_CASE =ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **_UpperCamelCase ) else: _SCREAMING_SNAKE_CASE =ViTMAEConfig() logger.warning('You are instantiating a new config instance from scratch.' ) if model_args.config_overrides is not None: logger.info(f"Overriding config: {model_args.config_overrides}" ) config.update_from_string(model_args.config_overrides ) logger.info(f"New config: {config}" ) # adapt config config.update( { 'mask_ratio': model_args.mask_ratio, 'norm_pix_loss': model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: _SCREAMING_SNAKE_CASE =ViTImageProcessor.from_pretrained(model_args.image_processor_name , **_UpperCamelCase ) elif model_args.model_name_or_path: _SCREAMING_SNAKE_CASE =ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **_UpperCamelCase ) else: _SCREAMING_SNAKE_CASE =ViTImageProcessor() # create model if model_args.model_name_or_path: _SCREAMING_SNAKE_CASE =ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=_UpperCamelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('Training new model from scratch' ) _SCREAMING_SNAKE_CASE =ViTMAEForPreTraining(_UpperCamelCase ) if training_args.do_train: _SCREAMING_SNAKE_CASE =ds['train'].column_names else: _SCREAMING_SNAKE_CASE =ds['validation'].column_names if data_args.image_column_name is not None: _SCREAMING_SNAKE_CASE =data_args.image_column_name elif "image" in column_names: _SCREAMING_SNAKE_CASE ='image' elif "img" in column_names: _SCREAMING_SNAKE_CASE ='img' else: _SCREAMING_SNAKE_CASE =column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: _SCREAMING_SNAKE_CASE =image_processor.size['shortest_edge'] else: _SCREAMING_SNAKE_CASE =(image_processor.size['height'], image_processor.size['width']) _SCREAMING_SNAKE_CASE =Compose( [ Lambda(lambda _UpperCamelCase : img.convert('RGB' ) if img.mode != "RGB" else img ), RandomResizedCrop(_UpperCamelCase , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(_UpperCamelCase : Dict ): _SCREAMING_SNAKE_CASE =[transforms(_UpperCamelCase ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError('--do_train requires a train dataset' ) if data_args.max_train_samples is not None: _SCREAMING_SNAKE_CASE =ds['train'].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(_UpperCamelCase ) if training_args.do_eval: if "validation" not in ds: raise ValueError('--do_eval requires a validation dataset' ) if data_args.max_eval_samples is not None: _SCREAMING_SNAKE_CASE =( ds['validation'].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(_UpperCamelCase ) # Compute absolute learning rate _SCREAMING_SNAKE_CASE =( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: _SCREAMING_SNAKE_CASE =training_args.base_learning_rate * total_train_batch_size / 2_56 # Initialize our trainer _SCREAMING_SNAKE_CASE =Trainer( model=_UpperCamelCase , args=_UpperCamelCase , train_dataset=ds['train'] if training_args.do_train else None , eval_dataset=ds['validation'] if training_args.do_eval else None , tokenizer=_UpperCamelCase , data_collator=_UpperCamelCase , ) # Training if training_args.do_train: _SCREAMING_SNAKE_CASE =None if training_args.resume_from_checkpoint is not None: _SCREAMING_SNAKE_CASE =training_args.resume_from_checkpoint elif last_checkpoint is not None: _SCREAMING_SNAKE_CASE =last_checkpoint _SCREAMING_SNAKE_CASE =trainer.train(resume_from_checkpoint=_UpperCamelCase ) trainer.save_model() trainer.log_metrics('train' , train_result.metrics ) trainer.save_metrics('train' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _SCREAMING_SNAKE_CASE =trainer.evaluate() trainer.log_metrics('eval' , _UpperCamelCase ) trainer.save_metrics('eval' , _UpperCamelCase ) # Write model card and (optionally) push to hub _SCREAMING_SNAKE_CASE ={ 'tasks': 'masked-auto-encoding', 'dataset': data_args.dataset_name, 'tags': ['masked-auto-encoding'], } if training_args.push_to_hub: trainer.push_to_hub(**_UpperCamelCase ) else: trainer.create_model_card(**_UpperCamelCase ) def _lowerCAmelCase ( _UpperCamelCase : List[str] ) -> Optional[int]: """simple docstring""" main() if __name__ == "__main__": main()
47
1
'''simple docstring''' import sys import turtle def _lowerCAmelCase ( _UpperCamelCase : tuple[float, float] , _UpperCamelCase : tuple[float, float] ) -> tuple[float, float]: """simple docstring""" return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def _lowerCAmelCase ( _UpperCamelCase : tuple[float, float] , _UpperCamelCase : tuple[float, float] , _UpperCamelCase : tuple[float, float] , _UpperCamelCase : int , ) -> None: """simple docstring""" my_pen.up() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) if depth == 0: return triangle(_UpperCamelCase , get_mid(_UpperCamelCase , _UpperCamelCase ) , get_mid(_UpperCamelCase , _UpperCamelCase ) , depth - 1 ) triangle(_UpperCamelCase , get_mid(_UpperCamelCase , _UpperCamelCase ) , get_mid(_UpperCamelCase , _UpperCamelCase ) , depth - 1 ) triangle(_UpperCamelCase , get_mid(_UpperCamelCase , _UpperCamelCase ) , get_mid(_UpperCamelCase , _UpperCamelCase ) , depth - 1 ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( "Correct format for using this script: " "python fractals.py <int:depth_for_fractal>" ) lowerCamelCase : Dict = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor("red") lowerCamelCase : Dict = [(-1_7_5, -1_2_5), (0, 1_7_5), (1_7_5, -1_2_5)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
47
'''simple docstring''' from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class A__ ( A__ , A__ ): @register_to_config def __init__( self : Dict , _a : int = 768 , ) -> Union[str, Any]: '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =nn.Parameter(torch.zeros(1 , _a ) ) _SCREAMING_SNAKE_CASE =nn.Parameter(torch.ones(1 , _a ) ) def A ( self : Tuple , _a : Optional[Union[str, torch.device]] = None , _a : Optional[torch.dtype] = None , ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =nn.Parameter(self.mean.to(_a ).to(_a ) ) _SCREAMING_SNAKE_CASE =nn.Parameter(self.std.to(_a ).to(_a ) ) return self def A ( self : Tuple , _a : str ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =(embeds - self.mean) * 1.0 / self.std return embeds def A ( self : List[str] , _a : Optional[Any] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =(embeds * self.std) + self.mean return embeds
47
1
'''simple docstring''' def _lowerCAmelCase ( _UpperCamelCase : int , _UpperCamelCase : int ) -> int: """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def _lowerCAmelCase ( ) -> None: """simple docstring""" assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
47
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def _lowerCAmelCase ( _UpperCamelCase : Optional[int] ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =botoa.client('iam' ) _SCREAMING_SNAKE_CASE ={ 'Version': '2012-10-17', 'Statement': [ {'Effect': 'Allow', 'Principal': {'Service': 'sagemaker.amazonaws.com'}, 'Action': 'sts:AssumeRole'} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=_UpperCamelCase , AssumeRolePolicyDocument=json.dumps(_UpperCamelCase , indent=2 ) ) _SCREAMING_SNAKE_CASE ={ 'Version': '2012-10-17', 'Statement': [ { 'Effect': 'Allow', 'Action': [ 'sagemaker:*', 'ecr:GetDownloadUrlForLayer', 'ecr:BatchGetImage', 'ecr:BatchCheckLayerAvailability', 'ecr:GetAuthorizationToken', 'cloudwatch:PutMetricData', 'cloudwatch:GetMetricData', 'cloudwatch:GetMetricStatistics', 'cloudwatch:ListMetrics', 'logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:DescribeLogStreams', 'logs:PutLogEvents', 'logs:GetLogEvents', 's3:CreateBucket', 's3:ListBucket', 's3:GetBucketLocation', 's3:GetObject', 's3:PutObject', ], 'Resource': '*', } ], } # attach policy to role iam_client.put_role_policy( RoleName=_UpperCamelCase , PolicyName=f"{role_name}_policy_permission" , PolicyDocument=json.dumps(_UpperCamelCase , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(f"role {role_name} already exists. Using existing one" ) def _lowerCAmelCase ( _UpperCamelCase : List[str] ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =botoa.client('iam' ) return iam_client.get_role(RoleName=_UpperCamelCase )["Role"]["Arn"] def _lowerCAmelCase ( ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =_ask_options( 'How do you want to authorize?' , ['AWS Profile', 'Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) '] , _UpperCamelCase , ) _SCREAMING_SNAKE_CASE =None if credentials_configuration == 0: _SCREAMING_SNAKE_CASE =_ask_field('Enter your AWS Profile name: [default] ' , default='default' ) _SCREAMING_SNAKE_CASE =aws_profile else: print( 'Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,' '`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`' ) _SCREAMING_SNAKE_CASE =_ask_field('AWS Access Key ID: ' ) _SCREAMING_SNAKE_CASE =aws_access_key_id _SCREAMING_SNAKE_CASE =_ask_field('AWS Secret Access Key: ' ) _SCREAMING_SNAKE_CASE =aws_secret_access_key _SCREAMING_SNAKE_CASE =_ask_field('Enter your AWS Region: [us-east-1]' , default='us-east-1' ) _SCREAMING_SNAKE_CASE =aws_region _SCREAMING_SNAKE_CASE =_ask_options( 'Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?' , ['Provide IAM Role name', 'Create new IAM role using credentials'] , _UpperCamelCase , ) if role_management == 0: _SCREAMING_SNAKE_CASE =_ask_field('Enter your IAM role name: ' ) else: _SCREAMING_SNAKE_CASE ='accelerate_sagemaker_execution_role' print(f"Accelerate will create an iam role \"{iam_role_name}\" using the provided credentials" ) _create_iam_role_for_sagemaker(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to use custom Docker image? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE =None if is_custom_docker_image: _SCREAMING_SNAKE_CASE =_ask_field('Enter your Docker image: ' , lambda _UpperCamelCase : str(_UpperCamelCase ).lower() ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to provide SageMaker input channels with data locations? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE =None if is_sagemaker_inputs_enabled: _SCREAMING_SNAKE_CASE =_ask_field( 'Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): ' , lambda _UpperCamelCase : str(_UpperCamelCase ).lower() , ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to enable SageMaker metrics? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE =None if is_sagemaker_metrics_enabled: _SCREAMING_SNAKE_CASE =_ask_field( 'Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): ' , lambda _UpperCamelCase : str(_UpperCamelCase ).lower() , ) _SCREAMING_SNAKE_CASE =_ask_options( 'What is the distributed mode?' , ['No distributed training', 'Data parallelism'] , _convert_sagemaker_distributed_mode , ) _SCREAMING_SNAKE_CASE ={} _SCREAMING_SNAKE_CASE =_ask_field( 'Do you wish to optimize your script with torch dynamo?[yes/NO]:' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) if use_dynamo: _SCREAMING_SNAKE_CASE ='dynamo_' _SCREAMING_SNAKE_CASE =_ask_options( 'Which dynamo backend would you like to use?' , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to customize the defaults sent to torch.compile? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) if use_custom_options: _SCREAMING_SNAKE_CASE =_ask_options( 'Which mode do you want to use?' , _UpperCamelCase , lambda _UpperCamelCase : TORCH_DYNAMO_MODES[int(_UpperCamelCase )] , default='default' , ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to enable dynamic shape tracing? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE ='Which EC2 instance type you want to use for your training?' if distributed_type != SageMakerDistributedType.NO: _SCREAMING_SNAKE_CASE =_ask_options( _UpperCamelCase , _UpperCamelCase , lambda _UpperCamelCase : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(_UpperCamelCase )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" _SCREAMING_SNAKE_CASE =_ask_field(_UpperCamelCase , lambda _UpperCamelCase : str(_UpperCamelCase ).lower() , default='ml.p3.2xlarge' ) _SCREAMING_SNAKE_CASE =1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): _SCREAMING_SNAKE_CASE =_ask_field( 'How many machines do you want use? [1]: ' , _UpperCamelCase , default=1 , ) _SCREAMING_SNAKE_CASE =_ask_options( 'Do you wish to use FP16 or BF16 (mixed precision)?' , ['no', 'fp16', 'bf16', 'fp8'] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( 'Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.' ) return SageMakerConfig( image_uri=_UpperCamelCase , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=_UpperCamelCase , use_cpu=_UpperCamelCase , dynamo_config=_UpperCamelCase , eca_instance_type=_UpperCamelCase , profile=_UpperCamelCase , region=_UpperCamelCase , iam_role_name=_UpperCamelCase , mixed_precision=_UpperCamelCase , num_machines=_UpperCamelCase , sagemaker_inputs_file=_UpperCamelCase , sagemaker_metrics_file=_UpperCamelCase , )
47
1
'''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 A__ : A__ = 42 A__ = None A__ = None def _lowerCAmelCase ( ) -> Node | None: """simple docstring""" _SCREAMING_SNAKE_CASE =Node(1 ) _SCREAMING_SNAKE_CASE =Node(2 ) _SCREAMING_SNAKE_CASE =Node(3 ) _SCREAMING_SNAKE_CASE =Node(4 ) _SCREAMING_SNAKE_CASE =Node(5 ) return tree def _lowerCAmelCase ( _UpperCamelCase : Node | None ) -> list[int]: """simple docstring""" return [root.data, *preorder(root.left ), *preorder(root.right )] if root else [] def _lowerCAmelCase ( _UpperCamelCase : Node | None ) -> list[int]: """simple docstring""" return postorder(root.left ) + postorder(root.right ) + [root.data] if root else [] def _lowerCAmelCase ( _UpperCamelCase : Node | None ) -> list[int]: """simple docstring""" return [*inorder(root.left ), root.data, *inorder(root.right )] if root else [] def _lowerCAmelCase ( _UpperCamelCase : Node | None ) -> int: """simple docstring""" return (max(height(root.left ) , height(root.right ) ) + 1) if root else 0 def _lowerCAmelCase ( _UpperCamelCase : Node | None ) -> Sequence[Node | None]: """simple docstring""" _SCREAMING_SNAKE_CASE =[] if root is None: return output _SCREAMING_SNAKE_CASE =deque([root] ) while process_queue: _SCREAMING_SNAKE_CASE =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 ) -> Sequence[Node | None]: """simple docstring""" _SCREAMING_SNAKE_CASE =[] 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(_UpperCamelCase , _UpperCamelCase ) return output def _lowerCAmelCase ( _UpperCamelCase : Node | None , _UpperCamelCase : int ) -> Sequence[Node | None]: """simple docstring""" _SCREAMING_SNAKE_CASE =[] 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(_UpperCamelCase , _UpperCamelCase ) return output def _lowerCAmelCase ( _UpperCamelCase : Node | None ) -> Sequence[Node | None] | list[Any]: """simple docstring""" if root is None: return [] _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =height(_UpperCamelCase ) for h in range(1 , height_tree + 1 ): if not flag: output.append(get_nodes_from_left_to_right(_UpperCamelCase , _UpperCamelCase ) ) _SCREAMING_SNAKE_CASE =1 else: output.append(get_nodes_from_right_to_left(_UpperCamelCase , _UpperCamelCase ) ) _SCREAMING_SNAKE_CASE =0 return output def _lowerCAmelCase ( ) -> None: # Main function for testing. """simple docstring""" _SCREAMING_SNAKE_CASE =make_tree() print(f"In-order Traversal: {inorder(_UpperCamelCase )}" ) print(f"Pre-order Traversal: {preorder(_UpperCamelCase )}" ) print(f"Post-order Traversal: {postorder(_UpperCamelCase )}" , '\n' ) print(f"Height of Tree: {height(_UpperCamelCase )}" , '\n' ) print('Complete Level Order Traversal: ' ) print(level_order(_UpperCamelCase ) , '\n' ) print('Level-wise order Traversal: ' ) for level in range(1 , height(_UpperCamelCase ) + 1 ): print(f"Level {level}:" , get_nodes_from_left_to_right(_UpperCamelCase , level=_UpperCamelCase ) ) print('\nZigZag order Traversal: ' ) print(zigzag(_UpperCamelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
47
'''simple docstring''' class A__ : def __init__( self : Union[str, Any] , _a : int ) -> None: '''simple docstring''' _SCREAMING_SNAKE_CASE =size _SCREAMING_SNAKE_CASE =[0] * size _SCREAMING_SNAKE_CASE =[0] * size @staticmethod def A ( _a : int ) -> int: '''simple docstring''' return index | (index + 1) @staticmethod def A ( _a : int ) -> int: '''simple docstring''' return (index & (index + 1)) - 1 def A ( self : Tuple , _a : int , _a : int ) -> None: '''simple docstring''' _SCREAMING_SNAKE_CASE =value while index < self.size: _SCREAMING_SNAKE_CASE =self.get_prev(_a ) + 1 if current_left_border == index: _SCREAMING_SNAKE_CASE =value else: _SCREAMING_SNAKE_CASE =max(_a , _a , _a ) _SCREAMING_SNAKE_CASE =self.get_next(_a ) def A ( self : int , _a : int , _a : int ) -> int: '''simple docstring''' right -= 1 # Because of right is exclusive _SCREAMING_SNAKE_CASE =0 while left <= right: _SCREAMING_SNAKE_CASE =self.get_prev(_a ) if left <= current_left: _SCREAMING_SNAKE_CASE =max(_a , self.tree[right] ) _SCREAMING_SNAKE_CASE =current_left else: _SCREAMING_SNAKE_CASE =max(_a , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
47
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase : List[Any] = { "configuration_bridgetower": [ "BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP", "BridgeTowerConfig", "BridgeTowerTextConfig", "BridgeTowerVisionConfig", ], "processing_bridgetower": ["BridgeTowerProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : str = ["BridgeTowerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Dict = [ "BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST", "BridgeTowerForContrastiveLearning", "BridgeTowerForImageAndTextRetrieval", "BridgeTowerForMaskedLM", "BridgeTowerModel", "BridgeTowerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_bridgetower import ( BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP, BridgeTowerConfig, BridgeTowerTextConfig, BridgeTowerVisionConfig, ) from .processing_bridgetower import BridgeTowerProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_bridgetower import BridgeTowerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bridgetower import ( BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST, BridgeTowerForContrastiveLearning, BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerModel, BridgeTowerPreTrainedModel, ) else: import sys lowerCamelCase : Any = _LazyModule(__name__, globals()["__file__"], _import_structure)
47
'''simple docstring''' from __future__ import annotations from random import random from typing import Generic, TypeVar lowerCamelCase : Union[str, Any] = TypeVar("KT") lowerCamelCase : Dict = TypeVar("VT") class A__ ( Generic[KT, VT] ): def __init__( self : str , _a : KT | str = "root" , _a : VT | None = None ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =key _SCREAMING_SNAKE_CASE =value _SCREAMING_SNAKE_CASE =[] def __repr__( self : Union[str, Any] ) -> str: '''simple docstring''' return f"Node({self.key}: {self.value})" @property def A ( self : int ) -> int: '''simple docstring''' return len(self.forward ) class A__ ( Generic[KT, VT] ): def __init__( self : Optional[Any] , _a : float = 0.5 , _a : int = 16 ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =Node[KT, VT]() _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =p _SCREAMING_SNAKE_CASE =max_level def __str__( self : Tuple ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =list(self ) if len(_a ) == 0: return f"SkipList(level={self.level})" _SCREAMING_SNAKE_CASE =max((len(str(_a ) ) for item in items) , default=4 ) _SCREAMING_SNAKE_CASE =max(_a , 4 ) + 4 _SCREAMING_SNAKE_CASE =self.head _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =node.forward.copy() lines.append(f"[{node.key}]".ljust(_a , '-' ) + '* ' * len(_a ) ) lines.append(' ' * label_size + '| ' * len(_a ) ) while len(node.forward ) != 0: _SCREAMING_SNAKE_CASE =node.forward[0] lines.append( f"[{node.key}]".ljust(_a , '-' ) + ' '.join(str(n.key ) if n.key == node.key else '|' for n in forwards ) ) lines.append(' ' * label_size + '| ' * len(_a ) ) _SCREAMING_SNAKE_CASE =node.forward lines.append('None'.ljust(_a ) + '* ' * len(_a ) ) return f"SkipList(level={self.level})\n" + "\n".join(_a ) def __iter__( self : Dict ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.head while len(node.forward ) != 0: yield node.forward[0].key _SCREAMING_SNAKE_CASE =node.forward[0] def A ( self : List[Any] ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =1 while random() < self.p and level < self.max_level: level += 1 return level def A ( self : Any , _a : Any ) -> tuple[Node[KT, VT] | None, list[Node[KT, VT]]]: '''simple docstring''' _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =self.head for i in reversed(range(self.level ) ): # i < node.level - When node level is lesser than `i` decrement `i`. # node.forward[i].key < key - Jumping to node with key value higher # or equal to searched key would result # in skipping searched key. while i < node.level and node.forward[i].key < key: _SCREAMING_SNAKE_CASE =node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(_a ) update_vector.reverse() # Note that we were inserting values in reverse order. # len(node.forward) != 0 - If current node doesn't contain any further # references then searched key is not present. # node.forward[0].key == key - Next node key should be equal to search key # if key is present. if len(node.forward ) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def A ( self : Union[str, Any] , _a : KT ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self._locate_node(_a ) if node is not None: for i, update_node in enumerate(_a ): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: _SCREAMING_SNAKE_CASE =node.forward[i] else: _SCREAMING_SNAKE_CASE =update_node.forward[:i] def A ( self : Optional[Any] , _a : KT , _a : VT ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self._locate_node(_a ) if node is not None: _SCREAMING_SNAKE_CASE =value else: _SCREAMING_SNAKE_CASE =self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for _ in range(self.level - 1 , _a ): update_vector.append(self.head ) _SCREAMING_SNAKE_CASE =level _SCREAMING_SNAKE_CASE =Node(_a , _a ) for i, update_node in enumerate(update_vector[:level] ): # Change references to pass through new node. if update_node.level > i: new_node.forward.append(update_node.forward[i] ) if update_node.level < i + 1: update_node.forward.append(_a ) else: _SCREAMING_SNAKE_CASE =new_node def A ( self : List[str] , _a : VT ) -> VT | None: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self._locate_node(_a ) if node is not None: return node.value return None def _lowerCAmelCase ( ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key1' , 3 ) skip_list.insert('Key2' , 12 ) skip_list.insert('Key3' , 41 ) skip_list.insert('Key4' , -19 ) _SCREAMING_SNAKE_CASE =skip_list.head _SCREAMING_SNAKE_CASE ={} while node.level != 0: _SCREAMING_SNAKE_CASE =node.forward[0] _SCREAMING_SNAKE_CASE =node.value assert len(_UpperCamelCase ) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def _lowerCAmelCase ( ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key1' , 10 ) skip_list.insert('Key1' , 12 ) skip_list.insert('Key5' , 7 ) skip_list.insert('Key7' , 10 ) skip_list.insert('Key10' , 5 ) skip_list.insert('Key7' , 7 ) skip_list.insert('Key5' , 5 ) skip_list.insert('Key10' , 10 ) _SCREAMING_SNAKE_CASE =skip_list.head _SCREAMING_SNAKE_CASE ={} while node.level != 0: _SCREAMING_SNAKE_CASE =node.forward[0] _SCREAMING_SNAKE_CASE =node.value if len(_UpperCamelCase ) != 4: print() assert len(_UpperCamelCase ) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def _lowerCAmelCase ( ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() assert skip_list.find('Some key' ) is None def _lowerCAmelCase ( ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key2' , 20 ) assert skip_list.find('Key2' ) == 20 skip_list.insert('Some Key' , 10 ) skip_list.insert('Key2' , 8 ) skip_list.insert('V' , 13 ) assert skip_list.find('Y' ) is None assert skip_list.find('Key2' ) == 8 assert skip_list.find('Some Key' ) == 10 assert skip_list.find('V' ) == 13 def _lowerCAmelCase ( ) -> List[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.delete('Some key' ) assert len(skip_list.head.forward ) == 0 def _lowerCAmelCase ( ) -> Optional[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key1' , 12 ) skip_list.insert('V' , 13 ) skip_list.insert('X' , 14 ) skip_list.insert('Key2' , 15 ) skip_list.delete('V' ) skip_list.delete('Key2' ) assert skip_list.find('V' ) is None assert skip_list.find('Key2' ) is None def _lowerCAmelCase ( ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key1' , 12 ) skip_list.insert('V' , 13 ) skip_list.insert('X' , 14 ) skip_list.insert('Key2' , 15 ) skip_list.delete('V' ) assert skip_list.find('V' ) is None assert skip_list.find('X' ) == 14 assert skip_list.find('Key1' ) == 12 assert skip_list.find('Key2' ) == 15 skip_list.delete('X' ) assert skip_list.find('V' ) is None assert skip_list.find('X' ) is None assert skip_list.find('Key1' ) == 12 assert skip_list.find('Key2' ) == 15 skip_list.delete('Key1' ) assert skip_list.find('V' ) is None assert skip_list.find('X' ) is None assert skip_list.find('Key1' ) is None assert skip_list.find('Key2' ) == 15 skip_list.delete('Key2' ) assert skip_list.find('V' ) is None assert skip_list.find('X' ) is None assert skip_list.find('Key1' ) is None assert skip_list.find('Key2' ) is None def _lowerCAmelCase ( ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key1' , 12 ) skip_list.insert('V' , 13 ) skip_list.insert('X' , 1_42 ) skip_list.insert('Key2' , 15 ) skip_list.delete('X' ) def traverse_keys(_UpperCamelCase : Dict ): yield node.key for forward_node in node.forward: yield from traverse_keys(_UpperCamelCase ) assert len(set(traverse_keys(skip_list.head ) ) ) == 4 def _lowerCAmelCase ( ) -> Union[str, Any]: """simple docstring""" def is_sorted(_UpperCamelCase : str ): return all(next_item >= item for item, next_item in zip(_UpperCamelCase , lst[1:] ) ) _SCREAMING_SNAKE_CASE =SkipList() for i in range(10 ): skip_list.insert(_UpperCamelCase , _UpperCamelCase ) assert is_sorted(list(_UpperCamelCase ) ) skip_list.delete(5 ) skip_list.delete(8 ) skip_list.delete(2 ) assert is_sorted(list(_UpperCamelCase ) ) skip_list.insert(-12 , -12 ) skip_list.insert(77 , 77 ) assert is_sorted(list(_UpperCamelCase ) ) def _lowerCAmelCase ( ) -> List[str]: """simple docstring""" for _ in range(1_00 ): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def _lowerCAmelCase ( ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert(2 , '2' ) skip_list.insert(4 , '4' ) skip_list.insert(6 , '4' ) skip_list.insert(4 , '5' ) skip_list.insert(8 , '4' ) skip_list.insert(9 , '4' ) skip_list.delete(4 ) print(_UpperCamelCase ) if __name__ == "__main__": import doctest doctest.testmod() main()
47
1
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class A__ ( A__ ): def __init__( self : Union[str, Any] , _a : Union[str, "sqlalchemy.sql.Selectable"] , _a : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] , _a : Optional[Features] = None , _a : str = None , _a : bool = False , **_a : Union[str, Any] , ) -> Union[str, Any]: '''simple docstring''' super().__init__(features=_a , cache_dir=_a , keep_in_memory=_a , **_a ) _SCREAMING_SNAKE_CASE =Sql( cache_dir=_a , features=_a , sql=_a , con=_a , **_a , ) def A ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =None self.builder.download_and_prepare( download_config=_a , download_mode=_a , verification_mode=_a , base_path=_a , ) # Build dataset for splits _SCREAMING_SNAKE_CASE =self.builder.as_dataset( split='train' , verification_mode=_a , in_memory=self.keep_in_memory ) return dataset class A__ : def __init__( self : List[Any] , _a : Dataset , _a : str , _a : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] , _a : Optional[int] = None , _a : Optional[int] = None , **_a : int , ) -> str: '''simple docstring''' if num_proc is not None and num_proc <= 0: raise ValueError(f"num_proc {num_proc} must be an integer > 0." ) _SCREAMING_SNAKE_CASE =dataset _SCREAMING_SNAKE_CASE =name _SCREAMING_SNAKE_CASE =con _SCREAMING_SNAKE_CASE =batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE _SCREAMING_SNAKE_CASE =num_proc _SCREAMING_SNAKE_CASE =to_sql_kwargs def A ( self : Dict ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.to_sql_kwargs.pop('sql' , _a ) _SCREAMING_SNAKE_CASE =self.to_sql_kwargs.pop('con' , _a ) _SCREAMING_SNAKE_CASE =self.to_sql_kwargs.pop('index' , _a ) _SCREAMING_SNAKE_CASE =self._write(index=_a , **self.to_sql_kwargs ) return written def A ( self : Dict , _a : List[str] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =args _SCREAMING_SNAKE_CASE ={**to_sql_kwargs, 'if_exists': 'append'} if offset > 0 else to_sql_kwargs _SCREAMING_SNAKE_CASE =query_table( table=self.dataset.data , key=slice(_a , offset + self.batch_size ) , indices=self.dataset._indices , ) _SCREAMING_SNAKE_CASE =batch.to_pandas() _SCREAMING_SNAKE_CASE =df.to_sql(self.name , self.con , index=_a , **_a ) return num_rows or len(_a ) def A ( self : Any , _a : Union[str, Any] , **_a : List[str] ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit='ba' , disable=not logging.is_progress_bar_enabled() , desc='Creating SQL from Arrow format' , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , _a , _a )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit='ba' , disable=not logging.is_progress_bar_enabled() , desc='Creating SQL from Arrow format' , ): written += num_rows return written
47
'''simple docstring''' import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version lowerCamelCase : List[Any] = version.parse(importlib_metadata.version("nltk")) if NLTK_VERSION >= version.Version("3.6.4"): from nltk import word_tokenize lowerCamelCase : Any = "\\n@inproceedings{banarjee2005,\n title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n author = {Banerjee, Satanjeev and Lavie, Alon},\n booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n month = jun,\n year = {2005},\n address = {Ann Arbor, Michigan},\n publisher = {Association for Computational Linguistics},\n url = {https://www.aclweb.org/anthology/W05-0909},\n pages = {65--72},\n}\n" lowerCamelCase : Optional[Any] = "\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n" lowerCamelCase : Optional[Any] = "\nComputes METEOR score of translated segments against one or more references.\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n 'meteor': meteor score.\nExamples:\n\n >>> meteor = datasets.load_metric('meteor')\n >>> predictions = [\"It is a guide to action which ensures that the military always obeys the commands of the party\"]\n >>> references = [\"It is a guide to action that ensures that the military will forever heed Party commands\"]\n >>> results = meteor.compute(predictions=predictions, references=references)\n >>> print(round(results[\"meteor\"], 4))\n 0.6944\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def A ( self : Tuple ) -> str: '''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/nltk/nltk/blob/develop/nltk/translate/meteor_score.py'] , reference_urls=[ 'https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score', 'https://en.wikipedia.org/wiki/METEOR', ] , ) def A ( self : Union[str, Any] , _a : Union[str, Any] ) -> Optional[int]: '''simple docstring''' import nltk nltk.download('wordnet' ) if NLTK_VERSION >= version.Version('3.6.5' ): nltk.download('punkt' ) if NLTK_VERSION >= version.Version('3.6.6' ): nltk.download('omw-1.4' ) def A ( self : int , _a : Tuple , _a : List[str] , _a : List[str]=0.9 , _a : Dict=3 , _a : Optional[int]=0.5 ) -> Optional[int]: '''simple docstring''' if NLTK_VERSION >= version.Version('3.6.5' ): _SCREAMING_SNAKE_CASE =[ meteor_score.single_meteor_score( word_tokenize(_a ) , word_tokenize(_a ) , alpha=_a , beta=_a , gamma=_a ) for ref, pred in zip(_a , _a ) ] else: _SCREAMING_SNAKE_CASE =[ meteor_score.single_meteor_score(_a , _a , alpha=_a , beta=_a , gamma=_a ) for ref, pred in zip(_a , _a ) ] return {"meteor": np.mean(_a )}
47
1
'''simple docstring''' import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm lowerCamelCase : List[str] = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex lowerCamelCase : Any = 1_0 lowerCamelCase : Tuple = 2_5_6 def _lowerCAmelCase ( _UpperCamelCase : List[str] ) -> Optional[MinHash]: """simple docstring""" if len(_UpperCamelCase ) < MIN_NUM_TOKENS: return None _SCREAMING_SNAKE_CASE =MinHash(num_perm=_UpperCamelCase ) for token in set(_UpperCamelCase ): min_hash.update(token.encode() ) return min_hash def _lowerCAmelCase ( _UpperCamelCase : str ) -> Set[str]: """simple docstring""" return {t for t in NON_ALPHA.split(_UpperCamelCase ) if len(t.strip() ) > 0} class A__ : def __init__( self : Dict , *, _a : float = 0.85 , ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =duplication_jaccard_threshold _SCREAMING_SNAKE_CASE =NUM_PERM _SCREAMING_SNAKE_CASE =MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) _SCREAMING_SNAKE_CASE =defaultdict(_a ) def A ( self : Tuple , _a : Tuple , _a : MinHash ) -> None: '''simple docstring''' _SCREAMING_SNAKE_CASE =self._index.query(_a ) if code_key in self._index.keys: print(f"Duplicate key {code_key}" ) return self._index.insert(_a , _a ) if len(_a ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(_a ) break else: self._duplicate_clusters[close_duplicates[0]].add(_a ) def A ( self : int ) -> List[List[Dict]]: '''simple docstring''' _SCREAMING_SNAKE_CASE =[] for base, duplicates in self._duplicate_clusters.items(): _SCREAMING_SNAKE_CASE =[base] + list(_a ) # reformat the cluster to be a list of dict _SCREAMING_SNAKE_CASE =[{'base_index': el[0], 'repo_name': el[1], 'path': el[2]} for el in cluster] duplicate_clusters.append(_a ) return duplicate_clusters def A ( self : Union[str, Any] , _a : Optional[Any] ) -> None: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.get_duplicate_clusters() with open(_a , 'w' ) as f: json.dump(_a , _a ) def _lowerCAmelCase ( _UpperCamelCase : Tuple ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =element _SCREAMING_SNAKE_CASE =get_min_hash([t for t in NON_ALPHA.split(data['content'] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def _lowerCAmelCase ( _UpperCamelCase : Type[Dataset] ) -> List[Any]: """simple docstring""" with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(_UpperCamelCase , max_queue_size=1_00_00 ) , chunksize=1_00 , ): if data is not None: yield data def _lowerCAmelCase ( _UpperCamelCase : Type[Dataset] , _UpperCamelCase : float ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =DuplicationIndex(duplication_jaccard_threshold=_UpperCamelCase ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(_UpperCamelCase ) ) , max_queue_size=1_00 ) ): di.add(_UpperCamelCase , _UpperCamelCase ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def _lowerCAmelCase ( _UpperCamelCase : str , _UpperCamelCase : str ) -> float: """simple docstring""" _SCREAMING_SNAKE_CASE =get_tokens(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =get_tokens(_UpperCamelCase ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) lowerCamelCase : Union[str, Any] = None def _lowerCAmelCase ( _UpperCamelCase : List[Any] , _UpperCamelCase : Tuple ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =[] for elementa in cluster: _SCREAMING_SNAKE_CASE =_shared_dataset[elementa['base_index']]['content'] for elementa in extremes: _SCREAMING_SNAKE_CASE =_shared_dataset[elementa['base_index']]['content'] if jaccard_similarity(_UpperCamelCase , _UpperCamelCase ) >= jaccard_threshold: elementa["copies"] += 1 break else: _SCREAMING_SNAKE_CASE =1 extremes.append(_UpperCamelCase ) return extremes def _lowerCAmelCase ( _UpperCamelCase : int , _UpperCamelCase : str , _UpperCamelCase : Any ) -> Optional[Any]: """simple docstring""" global _shared_dataset _SCREAMING_SNAKE_CASE =dataset _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =partial(_find_cluster_extremes_shared , jaccard_threshold=_UpperCamelCase ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( _UpperCamelCase , _UpperCamelCase , ) , total=len(_UpperCamelCase ) , ): extremes_list.append(_UpperCamelCase ) return extremes_list def _lowerCAmelCase ( _UpperCamelCase : Type[Dataset] , _UpperCamelCase : float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: """simple docstring""" _SCREAMING_SNAKE_CASE =make_duplicate_clusters(_UpperCamelCase , _UpperCamelCase ) _SCREAMING_SNAKE_CASE ={x['base_index'] for cluster in duplicate_clusters for x in cluster} _SCREAMING_SNAKE_CASE ={} _SCREAMING_SNAKE_CASE =find_extremes(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) for extremes in extremes_clusters: for element in extremes: _SCREAMING_SNAKE_CASE =element _SCREAMING_SNAKE_CASE =duplicate_indices - set(extreme_dict.keys() ) _SCREAMING_SNAKE_CASE =dataset.filter(lambda _UpperCamelCase , _UpperCamelCase : idx not in remove_indices , with_indices=_UpperCamelCase ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: _SCREAMING_SNAKE_CASE =element['base_index'] in extreme_dict if element["is_extreme"]: _SCREAMING_SNAKE_CASE =extreme_dict[element['base_index']]['copies'] print(f"Original dataset size: {len(_UpperCamelCase )}" ) print(f"Number of duplicate clusters: {len(_UpperCamelCase )}" ) print(f"Files in duplicate cluster: {len(_UpperCamelCase )}" ) print(f"Unique files in duplicate cluster: {len(_UpperCamelCase )}" ) print(f"Filtered dataset size: {len(_UpperCamelCase )}" ) return ds_filter, duplicate_clusters
47
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowerCamelCase : List[str] = logging.get_logger(__name__) lowerCamelCase : List[Any] = { "facebook/convnextv2-tiny-1k-224": "https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json", } class A__ ( A__ , A__ ): A__ = 'convnextv2' def __init__( self : Tuple , _a : Optional[int]=3 , _a : Any=4 , _a : int=4 , _a : Union[str, Any]=None , _a : List[str]=None , _a : Optional[Any]="gelu" , _a : Any=0.02 , _a : Any=1e-12 , _a : Tuple=0.0 , _a : int=224 , _a : Any=None , _a : Optional[int]=None , **_a : List[str] , ) -> Optional[Any]: '''simple docstring''' super().__init__(**_a ) _SCREAMING_SNAKE_CASE =num_channels _SCREAMING_SNAKE_CASE =patch_size _SCREAMING_SNAKE_CASE =num_stages _SCREAMING_SNAKE_CASE =[96, 192, 384, 768] if hidden_sizes is None else hidden_sizes _SCREAMING_SNAKE_CASE =[3, 3, 9, 3] if depths is None else depths _SCREAMING_SNAKE_CASE =hidden_act _SCREAMING_SNAKE_CASE =initializer_range _SCREAMING_SNAKE_CASE =layer_norm_eps _SCREAMING_SNAKE_CASE =drop_path_rate _SCREAMING_SNAKE_CASE =image_size _SCREAMING_SNAKE_CASE =['stem'] + [f"stage{idx}" for idx in range(1 , len(self.depths ) + 1 )] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =get_aligned_output_features_output_indices( out_features=_a , out_indices=_a , stage_names=self.stage_names )
47
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase : Any = { "configuration_funnel": ["FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP", "FunnelConfig"], "convert_funnel_original_tf_checkpoint_to_pytorch": [], "tokenization_funnel": ["FunnelTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[Any] = ["FunnelTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[str] = [ "FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST", "FunnelBaseModel", "FunnelForMaskedLM", "FunnelForMultipleChoice", "FunnelForPreTraining", "FunnelForQuestionAnswering", "FunnelForSequenceClassification", "FunnelForTokenClassification", "FunnelModel", "FunnelPreTrainedModel", "load_tf_weights_in_funnel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Union[str, Any] = [ "TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST", "TFFunnelBaseModel", "TFFunnelForMaskedLM", "TFFunnelForMultipleChoice", "TFFunnelForPreTraining", "TFFunnelForQuestionAnswering", "TFFunnelForSequenceClassification", "TFFunnelForTokenClassification", "TFFunnelModel", "TFFunnelPreTrainedModel", ] if TYPE_CHECKING: from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig from .tokenization_funnel import FunnelTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_funnel_fast import FunnelTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_funnel import ( FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, FunnelBaseModel, FunnelForMaskedLM, FunnelForMultipleChoice, FunnelForPreTraining, FunnelForQuestionAnswering, FunnelForSequenceClassification, FunnelForTokenClassification, FunnelModel, FunnelPreTrainedModel, load_tf_weights_in_funnel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_funnel import ( TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, TFFunnelPreTrainedModel, ) else: import sys lowerCamelCase : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
47
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase : int = {"configuration_glpn": ["GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP", "GLPNConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : int = ["GLPNFeatureExtractor"] lowerCamelCase : Optional[int] = ["GLPNImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Union[str, Any] = [ "GLPN_PRETRAINED_MODEL_ARCHIVE_LIST", "GLPNForDepthEstimation", "GLPNLayer", "GLPNModel", "GLPNPreTrainedModel", ] if TYPE_CHECKING: from .configuration_glpn import GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP, GLPNConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_glpn import GLPNFeatureExtractor from .image_processing_glpn import GLPNImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_glpn import ( GLPN_PRETRAINED_MODEL_ARCHIVE_LIST, GLPNForDepthEstimation, GLPNLayer, GLPNModel, GLPNPreTrainedModel, ) else: import sys lowerCamelCase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
47
1
'''simple docstring''' from collections import defaultdict def _lowerCAmelCase ( _UpperCamelCase : str , _UpperCamelCase : str ) -> bool: """simple docstring""" _SCREAMING_SNAKE_CASE =first_str.lower().strip() _SCREAMING_SNAKE_CASE =second_str.lower().strip() # Remove whitespace _SCREAMING_SNAKE_CASE =first_str.replace(' ' , '' ) _SCREAMING_SNAKE_CASE =second_str.replace(' ' , '' ) # Strings of different lengths are not anagrams if len(_UpperCamelCase ) != len(_UpperCamelCase ): return False # Default values for count should be 0 _SCREAMING_SNAKE_CASE =defaultdict(_UpperCamelCase ) # For each character in input strings, # increment count in the corresponding for i in range(len(_UpperCamelCase ) ): count[first_str[i]] += 1 count[second_str[i]] -= 1 return all(_count == 0 for _count in count.values() ) if __name__ == "__main__": from doctest import testmod testmod() lowerCamelCase : Optional[int] = input("Enter the first string ").strip() lowerCamelCase : Optional[Any] = input("Enter the second string ").strip() lowerCamelCase : List[str] = check_anagrams(input_a, input_b) print(f'''{input_a} and {input_b} are {"" if status else "not "}anagrams.''')
47
'''simple docstring''' lowerCamelCase : Any = "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" lowerCamelCase : int = [{"type": "code", "content": INSTALL_CONTENT}] lowerCamelCase : str = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
47
1
'''simple docstring''' import dataclasses import re import string from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np from . import residue_constants lowerCamelCase : int = Mapping[str, np.ndarray] lowerCamelCase : Union[str, Any] = Mapping[str, Any] # Is a nested dict. lowerCamelCase : Dict = 0.0_1 @dataclasses.dataclass(frozen=A__ ) class A__ : A__ = 42 # [num_res, num_atom_type, 3] # Amino-acid type for each residue represented as an integer between 0 and # 20, where 20 is 'X'. A__ = 42 # [num_res] # Binary float mask to indicate presence of a particular atom. 1.0 if an atom # is present and 0.0 if not. This should be used for loss masking. A__ = 42 # [num_res, num_atom_type] # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. A__ = 42 # [num_res] # B-factors, or temperature factors, of each residue (in sq. angstroms units), # representing the displacement of the residue from its ground truth mean # value. A__ = 42 # [num_res, num_atom_type] # Chain indices for multi-chain predictions A__ = None # Optional remark about the protein. Included as a comment in output PDB # files A__ = None # Templates used to generate this protein (prediction-only) A__ = None # Chain corresponding to each parent A__ = None def _lowerCAmelCase ( _UpperCamelCase : str ) -> Protein: """simple docstring""" _SCREAMING_SNAKE_CASE =r'(\[[A-Z]+\]\n)' _SCREAMING_SNAKE_CASE =[tag.strip() for tag in re.split(_UpperCamelCase , _UpperCamelCase ) if len(_UpperCamelCase ) > 0] _SCREAMING_SNAKE_CASE =zip(tags[0::2] , [l.split('\n' ) for l in tags[1::2]] ) _SCREAMING_SNAKE_CASE =["N", "CA", "C"] _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =None for g in groups: if "[PRIMARY]" == g[0]: _SCREAMING_SNAKE_CASE =g[1][0].strip() for i in range(len(_UpperCamelCase ) ): if seq[i] not in residue_constants.restypes: _SCREAMING_SNAKE_CASE ='X' # FIXME: strings are immutable _SCREAMING_SNAKE_CASE =np.array( [residue_constants.restype_order.get(_UpperCamelCase , residue_constants.restype_num ) for res_symbol in seq] ) elif "[TERTIARY]" == g[0]: _SCREAMING_SNAKE_CASE =[] for axis in range(3 ): tertiary.append(list(map(_UpperCamelCase , g[1][axis].split() ) ) ) _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa ) for i, atom in enumerate(_UpperCamelCase ): _SCREAMING_SNAKE_CASE =np.transpose(tertiary_np[:, i::3] ) atom_positions *= PICO_TO_ANGSTROM elif "[MASK]" == g[0]: _SCREAMING_SNAKE_CASE =np.array(list(map({'-': 0, '+': 1}.get , g[1][0].strip() ) ) ) _SCREAMING_SNAKE_CASE =np.zeros( ( len(_UpperCamelCase ), residue_constants.atom_type_num, ) ).astype(np.floataa ) for i, atom in enumerate(_UpperCamelCase ): _SCREAMING_SNAKE_CASE =1 atom_mask *= mask[..., None] assert aatype is not None return Protein( atom_positions=_UpperCamelCase , atom_mask=_UpperCamelCase , aatype=_UpperCamelCase , residue_index=np.arange(len(_UpperCamelCase ) ) , b_factors=_UpperCamelCase , ) def _lowerCAmelCase ( _UpperCamelCase : Protein , _UpperCamelCase : int = 0 ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =prot.remark if remark is not None: pdb_headers.append(f"REMARK {remark}" ) _SCREAMING_SNAKE_CASE =prot.parents _SCREAMING_SNAKE_CASE =prot.parents_chain_index if parents is not None and parents_chain_index is not None: _SCREAMING_SNAKE_CASE =[p for i, p in zip(_UpperCamelCase , _UpperCamelCase ) if i == chain_id] if parents is None or len(_UpperCamelCase ) == 0: _SCREAMING_SNAKE_CASE =['N/A'] pdb_headers.append(f"PARENT {' '.join(_UpperCamelCase )}" ) return pdb_headers def _lowerCAmelCase ( _UpperCamelCase : Protein , _UpperCamelCase : str ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =pdb_str.split('\n' ) _SCREAMING_SNAKE_CASE =prot.remark if remark is not None: out_pdb_lines.append(f"REMARK {remark}" ) _SCREAMING_SNAKE_CASE =42 if prot.parents is not None and len(prot.parents ) > 0: _SCREAMING_SNAKE_CASE =[] if prot.parents_chain_index is not None: _SCREAMING_SNAKE_CASE ={} for p, i in zip(prot.parents , prot.parents_chain_index ): parent_dict.setdefault(str(_UpperCamelCase ) , [] ) parent_dict[str(_UpperCamelCase )].append(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =max([int(_UpperCamelCase ) for chain_idx in parent_dict] ) for i in range(max_idx + 1 ): _SCREAMING_SNAKE_CASE =parent_dict.get(str(_UpperCamelCase ) , ['N/A'] ) parents_per_chain.append(_UpperCamelCase ) else: parents_per_chain.append(list(prot.parents ) ) else: _SCREAMING_SNAKE_CASE =[['N/A']] def make_parent_line(_UpperCamelCase : Sequence[str] ) -> str: return f"PARENT {' '.join(_UpperCamelCase )}" out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) ) _SCREAMING_SNAKE_CASE =0 for i, l in enumerate(_UpperCamelCase ): if "PARENT" not in l and "REMARK" not in l: out_pdb_lines.append(_UpperCamelCase ) if "TER" in l and "END" not in lines[i + 1]: chain_counter += 1 if not chain_counter >= len(_UpperCamelCase ): _SCREAMING_SNAKE_CASE =parents_per_chain[chain_counter] else: _SCREAMING_SNAKE_CASE =['N/A'] out_pdb_lines.append(make_parent_line(_UpperCamelCase ) ) return "\n".join(_UpperCamelCase ) def _lowerCAmelCase ( _UpperCamelCase : Protein ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =residue_constants.restypes + ['X'] def res_atoa(_UpperCamelCase : int ) -> str: return residue_constants.restype_atoa.get(restypes[r] , 'UNK' ) _SCREAMING_SNAKE_CASE =residue_constants.atom_types _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =prot.atom_mask _SCREAMING_SNAKE_CASE =prot.aatype _SCREAMING_SNAKE_CASE =prot.atom_positions _SCREAMING_SNAKE_CASE =prot.residue_index.astype(np.intaa ) _SCREAMING_SNAKE_CASE =prot.b_factors _SCREAMING_SNAKE_CASE =prot.chain_index if np.any(aatype > residue_constants.restype_num ): raise ValueError('Invalid aatypes.' ) _SCREAMING_SNAKE_CASE =get_pdb_headers(_UpperCamelCase ) if len(_UpperCamelCase ) > 0: pdb_lines.extend(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =aatype.shape[0] _SCREAMING_SNAKE_CASE =1 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =string.ascii_uppercase _SCREAMING_SNAKE_CASE =None # Add all atom sites. for i in range(_UpperCamelCase ): _SCREAMING_SNAKE_CASE =res_atoa(aatype[i] ) for atom_name, pos, mask, b_factor in zip(_UpperCamelCase , atom_positions[i] , atom_mask[i] , b_factors[i] ): if mask < 0.5: continue _SCREAMING_SNAKE_CASE ='ATOM' _SCREAMING_SNAKE_CASE =atom_name if len(_UpperCamelCase ) == 4 else f" {atom_name}" _SCREAMING_SNAKE_CASE ='' _SCREAMING_SNAKE_CASE ='' _SCREAMING_SNAKE_CASE =1.00 _SCREAMING_SNAKE_CASE =atom_name[0] # Protein supports only C, N, O, S, this works. _SCREAMING_SNAKE_CASE ='' _SCREAMING_SNAKE_CASE ='A' if chain_index is not None: _SCREAMING_SNAKE_CASE =chain_tags[chain_index[i]] # PDB is a columnar format, every space matters here! _SCREAMING_SNAKE_CASE =( f"{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}" f"{res_name_a:>3} {chain_tag:>1}" f"{residue_index[i]:>4}{insertion_code:>1} " f"{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}" f"{occupancy:>6.2f}{b_factor:>6.2f} " f"{element:>2}{charge:>2}" ) pdb_lines.append(_UpperCamelCase ) atom_index += 1 _SCREAMING_SNAKE_CASE =i == n - 1 if chain_index is not None: if i != n - 1 and chain_index[i + 1] != prev_chain_index: _SCREAMING_SNAKE_CASE =True _SCREAMING_SNAKE_CASE =chain_index[i + 1] if should_terminate: # Close the chain. _SCREAMING_SNAKE_CASE ='TER' _SCREAMING_SNAKE_CASE =( f"{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}" ) pdb_lines.append(_UpperCamelCase ) atom_index += 1 if i != n - 1: # "prev" is a misnomer here. This happens at the beginning of # each new chain. pdb_lines.extend(get_pdb_headers(_UpperCamelCase , _UpperCamelCase ) ) pdb_lines.append('END' ) pdb_lines.append('' ) return "\n".join(_UpperCamelCase ) def _lowerCAmelCase ( _UpperCamelCase : Protein ) -> np.ndarray: """simple docstring""" return residue_constants.STANDARD_ATOM_MASK[prot.aatype] def _lowerCAmelCase ( _UpperCamelCase : FeatureDict , _UpperCamelCase : ModelOutput , _UpperCamelCase : Optional[np.ndarray] = None , _UpperCamelCase : Optional[np.ndarray] = None , _UpperCamelCase : Optional[str] = None , _UpperCamelCase : Optional[Sequence[str]] = None , _UpperCamelCase : Optional[Sequence[int]] = None , ) -> Protein: """simple docstring""" return Protein( aatype=features['aatype'] , atom_positions=result['final_atom_positions'] , atom_mask=result['final_atom_mask'] , residue_index=features['residue_index'] + 1 , b_factors=b_factors if b_factors is not None else np.zeros_like(result['final_atom_mask'] ) , chain_index=_UpperCamelCase , remark=_UpperCamelCase , parents=_UpperCamelCase , parents_chain_index=_UpperCamelCase , )
47
'''simple docstring''' import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device lowerCamelCase : Optional[int] = False class A__ ( unittest.TestCase ): pass @slow @require_torch_gpu class A__ ( unittest.TestCase ): def A ( self : Tuple ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =VersatileDiffusionImageVariationPipeline.from_pretrained('shi-labs/versatile-diffusion' ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) _SCREAMING_SNAKE_CASE =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg' ) _SCREAMING_SNAKE_CASE =torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE =pipe( image=_a , generator=_a , guidance_scale=7.5 , num_inference_steps=50 , output_type='numpy' , ).images _SCREAMING_SNAKE_CASE =image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) _SCREAMING_SNAKE_CASE =np.array([0.04_41, 0.04_69, 0.05_07, 0.05_75, 0.06_32, 0.06_50, 0.08_65, 0.09_09, 0.09_45] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
47
1
'''simple docstring''' import unittest from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowerCamelCase : Tuple = get_tests_dir("fixtures/spiece.model") @require_sentencepiece @require_tokenizers class A__ ( A__ , unittest.TestCase ): A__ = DebertaVaTokenizer A__ = DebertaVaTokenizerFast A__ = True A__ = True def A ( self : Optional[Any] ) -> Dict: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing _SCREAMING_SNAKE_CASE =DebertaVaTokenizer(_a , unk_token='<unk>' ) tokenizer.save_pretrained(self.tmpdirname ) def A ( self : List[str] , _a : int ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE ='this is a test' _SCREAMING_SNAKE_CASE ='this is a test' return input_text, output_text def A ( self : List[str] ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE ='<pad>' _SCREAMING_SNAKE_CASE =0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_a ) , _a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_a ) , _a ) def A ( self : Optional[Any] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '<unk>' ) self.assertEqual(vocab_keys[-1] , '[PAD]' ) self.assertEqual(len(_a ) , 3_0001 ) def A ( self : Tuple ) -> Any: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 3_0000 ) def A ( self : List[Any] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =' \tHeLLo!how \n Are yoU? ' _SCREAMING_SNAKE_CASE =['▁hello', '!', 'how', '▁are', '▁you', '?'] # fmt: on _SCREAMING_SNAKE_CASE =DebertaVaTokenizer(_a , do_lower_case=_a ) _SCREAMING_SNAKE_CASE =tokenizer.convert_ids_to_tokens(tokenizer.encode(_a , add_special_tokens=_a ) ) self.assertListEqual(_a , _a ) _SCREAMING_SNAKE_CASE =DebertaVaTokenizerFast(_a , do_lower_case=_a ) _SCREAMING_SNAKE_CASE =rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_a , add_special_tokens=_a ) ) self.assertListEqual(_a , _a ) @unittest.skip('There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.' ) def A ( self : Any ) -> Union[str, Any]: '''simple docstring''' pass @unittest.skip('There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.' ) def A ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' pass def A ( self : Any ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE ='I was born in 92000, and this is falsé.' _SCREAMING_SNAKE_CASE =['▁', '<unk>', '▁was', '▁born', '▁in', '▁9', '2000', '▁', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '▁', '.', ] # fmt: on _SCREAMING_SNAKE_CASE =DebertaVaTokenizer(_a , split_by_punct=_a ) _SCREAMING_SNAKE_CASE =tokenizer.convert_ids_to_tokens(tokenizer.encode(_a , add_special_tokens=_a ) ) self.assertListEqual(_a , _a ) _SCREAMING_SNAKE_CASE =DebertaVaTokenizerFast(_a , split_by_punct=_a ) _SCREAMING_SNAKE_CASE =rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_a , add_special_tokens=_a ) ) self.assertListEqual(_a , _a ) def A ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE ='I was born in 92000, and this is falsé.' _SCREAMING_SNAKE_CASE =['▁i', '▁was', '▁born', '▁in', '▁9', '2000', '▁', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '▁', '.', ] # fmt: on _SCREAMING_SNAKE_CASE =DebertaVaTokenizer(_a , do_lower_case=_a , split_by_punct=_a ) _SCREAMING_SNAKE_CASE =tokenizer.convert_ids_to_tokens(tokenizer.encode(_a , add_special_tokens=_a ) ) self.assertListEqual(_a , _a ) _SCREAMING_SNAKE_CASE =DebertaVaTokenizerFast(_a , do_lower_case=_a , split_by_punct=_a ) _SCREAMING_SNAKE_CASE =rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_a , add_special_tokens=_a ) ) self.assertListEqual(_a , _a ) def A ( self : Tuple ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE ='I was born in 92000, and this is falsé.' _SCREAMING_SNAKE_CASE =['▁i', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.', ] # fmt: on _SCREAMING_SNAKE_CASE =DebertaVaTokenizer(_a , do_lower_case=_a , split_by_punct=_a ) _SCREAMING_SNAKE_CASE =tokenizer.convert_ids_to_tokens(tokenizer.encode(_a , add_special_tokens=_a ) ) self.assertListEqual(_a , _a ) _SCREAMING_SNAKE_CASE =DebertaVaTokenizerFast(_a , do_lower_case=_a , split_by_punct=_a ) _SCREAMING_SNAKE_CASE =rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_a , add_special_tokens=_a ) ) self.assertListEqual(_a , _a ) def A ( self : Optional[int] ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE ='I was born in 92000, and this is falsé.' _SCREAMING_SNAKE_CASE =['▁', '<unk>', '▁was', '▁born', '▁in', '▁9', '2000', '▁', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '▁', '.', ] # fmt: on _SCREAMING_SNAKE_CASE =DebertaVaTokenizer(_a , do_lower_case=_a , split_by_punct=_a ) _SCREAMING_SNAKE_CASE =tokenizer.convert_ids_to_tokens(tokenizer.encode(_a , add_special_tokens=_a ) ) self.assertListEqual(_a , _a ) _SCREAMING_SNAKE_CASE =DebertaVaTokenizerFast(_a , do_lower_case=_a , split_by_punct=_a ) _SCREAMING_SNAKE_CASE =rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_a , add_special_tokens=_a ) ) self.assertListEqual(_a , _a ) def A ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =' \tHeLLo!how \n Are yoU? ' _SCREAMING_SNAKE_CASE =['▁', '<unk>', 'e', '<unk>', 'o', '!', 'how', '▁', '<unk>', 're', '▁yo', '<unk>', '?'] # fmt: on _SCREAMING_SNAKE_CASE =DebertaVaTokenizer(_a , do_lower_case=_a , split_by_punct=_a ) _SCREAMING_SNAKE_CASE =tokenizer.convert_ids_to_tokens(tokenizer.encode(_a , add_special_tokens=_a ) ) self.assertListEqual(_a , _a ) _SCREAMING_SNAKE_CASE =DebertaVaTokenizerFast(_a , do_lower_case=_a , split_by_punct=_a ) _SCREAMING_SNAKE_CASE =rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_a , add_special_tokens=_a ) ) self.assertListEqual(_a , _a ) def A ( self : Tuple ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.get_tokenizer() _SCREAMING_SNAKE_CASE =self.get_rust_tokenizer() _SCREAMING_SNAKE_CASE ='I was born in 92000, and this is falsé.' _SCREAMING_SNAKE_CASE =tokenizer.convert_ids_to_tokens(tokenizer.encode(_a , add_special_tokens=_a ) ) _SCREAMING_SNAKE_CASE =rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_a , add_special_tokens=_a ) ) self.assertListEqual(_a , _a ) _SCREAMING_SNAKE_CASE =tokenizer.encode(_a , add_special_tokens=_a ) _SCREAMING_SNAKE_CASE =rust_tokenizer.encode(_a , add_special_tokens=_a ) self.assertListEqual(_a , _a ) _SCREAMING_SNAKE_CASE =self.get_rust_tokenizer() _SCREAMING_SNAKE_CASE =tokenizer.encode(_a ) _SCREAMING_SNAKE_CASE =rust_tokenizer.encode(_a ) self.assertListEqual(_a , _a ) def A ( self : Optional[int] ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE ='This is a test' _SCREAMING_SNAKE_CASE =[13, 1, 4398, 25, 21, 1289] _SCREAMING_SNAKE_CASE =['▁', 'T', 'his', '▁is', '▁a', '▁test'] _SCREAMING_SNAKE_CASE =['▁', '<unk>', 'his', '▁is', '▁a', '▁test'] _SCREAMING_SNAKE_CASE =DebertaVaTokenizer(_a , keep_accents=_a ) _SCREAMING_SNAKE_CASE =DebertaVaTokenizerFast(_a , keep_accents=_a ) _SCREAMING_SNAKE_CASE =tokenizer.encode(_a , add_special_tokens=_a ) self.assertListEqual(_a , _a ) _SCREAMING_SNAKE_CASE =tokenizer.tokenize(_a ) self.assertListEqual(_a , _a ) _SCREAMING_SNAKE_CASE =tokenizer.convert_ids_to_tokens(_a ) self.assertListEqual(_a , _a ) _SCREAMING_SNAKE_CASE =rust_tokenizer.encode(_a , add_special_tokens=_a ) self.assertListEqual(_a , _a ) _SCREAMING_SNAKE_CASE =rust_tokenizer.tokenize(_a ) self.assertListEqual(_a , _a ) _SCREAMING_SNAKE_CASE =rust_tokenizer.convert_ids_to_tokens(_a ) self.assertListEqual(_a , _a ) # fmt: off _SCREAMING_SNAKE_CASE ='I was born in 92000, and this is falsé.' _SCREAMING_SNAKE_CASE =[13, 1, 23, 386, 19, 561, 3050, 15, 17, 48, 25, 8256, 18, 1, 9] _SCREAMING_SNAKE_CASE =['▁', 'I', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', 'é', '.', ] _SCREAMING_SNAKE_CASE =['▁', '<unk>', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.', ] # fmt: on _SCREAMING_SNAKE_CASE =tokenizer.encode(_a , add_special_tokens=_a ) self.assertListEqual(_a , _a ) _SCREAMING_SNAKE_CASE =tokenizer.tokenize(_a ) self.assertListEqual(_a , _a ) _SCREAMING_SNAKE_CASE =tokenizer.convert_ids_to_tokens(_a ) self.assertListEqual(_a , _a ) _SCREAMING_SNAKE_CASE =rust_tokenizer.encode(_a , add_special_tokens=_a ) self.assertListEqual(_a , _a ) _SCREAMING_SNAKE_CASE =rust_tokenizer.tokenize(_a ) self.assertListEqual(_a , _a ) _SCREAMING_SNAKE_CASE =rust_tokenizer.convert_ids_to_tokens(_a ) self.assertListEqual(_a , _a ) def A ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =DebertaVaTokenizer(_a ) _SCREAMING_SNAKE_CASE =tokenizer.encode('sequence builders' ) _SCREAMING_SNAKE_CASE =tokenizer.encode('multi-sequence build' ) _SCREAMING_SNAKE_CASE =tokenizer.build_inputs_with_special_tokens(_a ) _SCREAMING_SNAKE_CASE =tokenizer.build_inputs_with_special_tokens(_a , _a ) self.assertEqual([tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] , _a ) self.assertEqual( [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [tokenizer.sep_token_id] , _a , ) @slow def A ( self : int ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE ={'input_ids': [[1, 3_9867, 36, 1_9390, 486, 27, 3_5052, 8_1436, 18, 6_0685, 1225, 7, 3_5052, 8_1436, 18, 9367, 1_6899, 18, 1_5937, 53, 594, 773, 18, 1_6287, 3_0465, 36, 1_5937, 6, 4_1139, 38, 3_6979, 6_0763, 191, 6, 3_4132, 99, 6, 5_0538, 390, 4_3230, 6, 3_4132, 2779, 2_0850, 14, 699, 1072, 1194, 36, 382, 1_0901, 53, 7, 699, 1072, 2084, 36, 2_0422, 630, 53, 19, 105, 3049, 1896, 1053, 1_6899, 1506, 11, 3_7978, 4243, 7, 1237, 3_1869, 200, 1_6566, 654, 6, 3_5052, 8_1436, 7, 5_5630, 1_3593, 4, 2], [1, 26, 1_5011, 13, 667, 8, 1053, 18, 2_3611, 1237, 7_2356, 1_2820, 34, 10_4134, 1209, 35, 1_3313, 6627, 21, 202, 347, 7, 164, 2399, 11, 46, 4485, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 5, 1232, 2864, 1_5785, 1_4951, 105, 5, 8581, 1250, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_a , model_name='microsoft/deberta-v2-xlarge' , revision='ad6e42c1532ddf3a15c39246b63f5559d558b670' , )
47
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase : Any = { "configuration_funnel": ["FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP", "FunnelConfig"], "convert_funnel_original_tf_checkpoint_to_pytorch": [], "tokenization_funnel": ["FunnelTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[Any] = ["FunnelTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[str] = [ "FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST", "FunnelBaseModel", "FunnelForMaskedLM", "FunnelForMultipleChoice", "FunnelForPreTraining", "FunnelForQuestionAnswering", "FunnelForSequenceClassification", "FunnelForTokenClassification", "FunnelModel", "FunnelPreTrainedModel", "load_tf_weights_in_funnel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Union[str, Any] = [ "TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST", "TFFunnelBaseModel", "TFFunnelForMaskedLM", "TFFunnelForMultipleChoice", "TFFunnelForPreTraining", "TFFunnelForQuestionAnswering", "TFFunnelForSequenceClassification", "TFFunnelForTokenClassification", "TFFunnelModel", "TFFunnelPreTrainedModel", ] if TYPE_CHECKING: from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig from .tokenization_funnel import FunnelTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_funnel_fast import FunnelTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_funnel import ( FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, FunnelBaseModel, FunnelForMaskedLM, FunnelForMultipleChoice, FunnelForPreTraining, FunnelForQuestionAnswering, FunnelForSequenceClassification, FunnelForTokenClassification, FunnelModel, FunnelPreTrainedModel, load_tf_weights_in_funnel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_funnel import ( TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, TFFunnelPreTrainedModel, ) else: import sys lowerCamelCase : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
47
1
'''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 lowerCamelCase : Optional[Any] = "src/diffusers" lowerCamelCase : str = "." # This is to make sure the diffusers module imported is the one in the repo. lowerCamelCase : Optional[Any] = importlib.util.spec_from_file_location( "diffusers", os.path.join(DIFFUSERS_PATH, "__init__.py"), submodule_search_locations=[DIFFUSERS_PATH], ) lowerCamelCase : List[Any] = spec.loader.load_module() def _lowerCAmelCase ( _UpperCamelCase : str , _UpperCamelCase : Optional[int] ) -> str: """simple docstring""" return line.startswith(_UpperCamelCase ) or len(_UpperCamelCase ) <= 1 or re.search(r'^\s*\)(\s*->.*:|:)\s*$' , _UpperCamelCase ) is not None def _lowerCAmelCase ( _UpperCamelCase : int ) -> Optional[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =object_name.split('.' ) _SCREAMING_SNAKE_CASE =0 # First let's find the module where our object lives. _SCREAMING_SNAKE_CASE =parts[i] while i < len(_UpperCamelCase ) and not os.path.isfile(os.path.join(_UpperCamelCase , f"{module}.py" ) ): i += 1 if i < len(_UpperCamelCase ): _SCREAMING_SNAKE_CASE =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: _SCREAMING_SNAKE_CASE =f.readlines() # Now let's find the class / func in the code! _SCREAMING_SNAKE_CASE ='' _SCREAMING_SNAKE_CASE =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). _SCREAMING_SNAKE_CASE =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 _SCREAMING_SNAKE_CASE =lines[start_index:line_index] return "".join(_UpperCamelCase ) lowerCamelCase : Optional[int] = re.compile(r"^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)") lowerCamelCase : Any = re.compile(r"^\s*(\S+)->(\S+)(\s+.*|$)") lowerCamelCase : Any = re.compile(r"<FILL\s+[^>]*>") def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE =code.split('\n' ) _SCREAMING_SNAKE_CASE =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 : List[str] ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =len(get_indent(_UpperCamelCase ) ) > 0 if has_indent: _SCREAMING_SNAKE_CASE =f"class Bla:\n{code}" _SCREAMING_SNAKE_CASE =black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_19 , preview=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =black.format_str(_UpperCamelCase , mode=_UpperCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =style_docstrings_in_code(_UpperCamelCase ) return result[len('class Bla:\n' ) :] if has_indent else result def _lowerCAmelCase ( _UpperCamelCase : str , _UpperCamelCase : List[Any]=False ) -> Optional[Any]: """simple docstring""" with open(_UpperCamelCase , 'r' , encoding='utf-8' , newline='\n' ) as f: _SCREAMING_SNAKE_CASE =f.readlines() _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(_UpperCamelCase ): _SCREAMING_SNAKE_CASE =_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. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =search.groups() _SCREAMING_SNAKE_CASE =find_code_in_diffusers(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =get_indent(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =line_index + 1 if indent == theoretical_indent else line_index + 2 _SCREAMING_SNAKE_CASE =theoretical_indent _SCREAMING_SNAKE_CASE =start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. _SCREAMING_SNAKE_CASE =True while line_index < len(_UpperCamelCase ) and should_continue: line_index += 1 if line_index >= len(_UpperCamelCase ): break _SCREAMING_SNAKE_CASE =lines[line_index] _SCREAMING_SNAKE_CASE =_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 _SCREAMING_SNAKE_CASE =lines[start_index:line_index] _SCREAMING_SNAKE_CASE =''.join(_UpperCamelCase ) # Remove any nested `Copied from` comments to avoid circular copies _SCREAMING_SNAKE_CASE =[line for line in theoretical_code.split('\n' ) if _re_copy_warning.search(_UpperCamelCase ) is None] _SCREAMING_SNAKE_CASE ='\n'.join(_UpperCamelCase ) # Before comparing, use the `replace_pattern` on the original code. if len(_UpperCamelCase ) > 0: _SCREAMING_SNAKE_CASE =replace_pattern.replace('with' , '' ).split(',' ) _SCREAMING_SNAKE_CASE =[_re_replace_pattern.search(_UpperCamelCase ) for p in patterns] for pattern in patterns: if pattern is None: continue _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =pattern.groups() _SCREAMING_SNAKE_CASE =re.sub(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) if option.strip() == "all-casing": _SCREAMING_SNAKE_CASE =re.sub(obja.lower() , obja.lower() , _UpperCamelCase ) _SCREAMING_SNAKE_CASE =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 _SCREAMING_SNAKE_CASE =blackify(lines[start_index - 1] + theoretical_code ) _SCREAMING_SNAKE_CASE =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: _SCREAMING_SNAKE_CASE =lines[:start_index] + [theoretical_code] + lines[line_index:] _SCREAMING_SNAKE_CASE =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 ) -> List[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =glob.glob(os.path.join(_UpperCamelCase , '**/*.py' ) , recursive=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =[] for filename in all_files: _SCREAMING_SNAKE_CASE =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: _SCREAMING_SNAKE_CASE ='\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__": lowerCamelCase : Tuple = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") lowerCamelCase : Optional[Any] = parser.parse_args() check_copies(args.fix_and_overwrite)
47
'''simple docstring''' import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def _lowerCAmelCase ( _UpperCamelCase : Dict , _UpperCamelCase : Any=False ) -> Optional[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =OmegaConf.load(_UpperCamelCase ) if display: print(yaml.dump(OmegaConf.to_container(_UpperCamelCase ) ) ) return config def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : Optional[Any]=None , _UpperCamelCase : Union[str, Any]=None ) -> Optional[Any]: """simple docstring""" if conf_path is None: _SCREAMING_SNAKE_CASE ='./model_checkpoints/vqgan_only.yaml' _SCREAMING_SNAKE_CASE =load_config(_UpperCamelCase , display=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =VQModel(**config.model.params ) if ckpt_path is None: _SCREAMING_SNAKE_CASE ='./model_checkpoints/vqgan_only.pt' _SCREAMING_SNAKE_CASE =torch.load(_UpperCamelCase , map_location=_UpperCamelCase ) if ".ckpt" in ckpt_path: _SCREAMING_SNAKE_CASE =sd['state_dict'] model.load_state_dict(_UpperCamelCase , strict=_UpperCamelCase ) model.to(_UpperCamelCase ) del sd return model def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : int ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =model.encode(_UpperCamelCase ) print(f"VQGAN --- {model.__class__.__name__}: latent shape: {z.shape[2:]}" ) _SCREAMING_SNAKE_CASE =model.decode(_UpperCamelCase ) return xrec def _lowerCAmelCase ( _UpperCamelCase : Dict , _UpperCamelCase : List[str]=False ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =string.rsplit('.' , 1 ) if reload: _SCREAMING_SNAKE_CASE =importlib.import_module(_UpperCamelCase ) importlib.reload(_UpperCamelCase ) return getattr(importlib.import_module(_UpperCamelCase , package=_UpperCamelCase ) , cls ) def _lowerCAmelCase ( _UpperCamelCase : str ) -> List[str]: """simple docstring""" if "target" not in config: raise KeyError('Expected key `target` to instantiate.' ) return get_obj_from_str(config['target'] )(**config.get('params' , {} ) ) def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : List[Any] , _UpperCamelCase : List[str]=True , _UpperCamelCase : int=True ) -> Union[str, Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =instantiate_from_config(_UpperCamelCase ) if sd is not None: model.load_state_dict(_UpperCamelCase ) if gpu: model.cuda() if eval_mode: model.eval() return {"model": model} def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Optional[Any] , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Optional[int] ) -> List[Any]: """simple docstring""" if ckpt: _SCREAMING_SNAKE_CASE =torch.load(_UpperCamelCase , map_location='cpu' ) _SCREAMING_SNAKE_CASE =pl_sd['global_step'] print(f"loaded model from global step {global_step}." ) else: _SCREAMING_SNAKE_CASE ={'state_dict': None} _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =load_model_from_config(config.model , pl_sd['state_dict'] , gpu=_UpperCamelCase , eval_mode=_UpperCamelCase )['model'] return model, global_step
47
1
'''simple docstring''' import io import os import unicodedata from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCamelCase : Tuple = logging.get_logger(__name__) lowerCamelCase : int = "▁" lowerCamelCase : Dict = {"vocab_file": "vocab.txt", "sentencepiece_model_ckpt": "sentencepiece.bpe.model"} lowerCamelCase : Optional[int] = { "sentencepiece_model_file": "sentencepiece.bpe.model", "vocab_file": "vocab.txt", } lowerCamelCase : Dict = { "vocab_file": { "ernie-m-base": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt", "ernie-m-large": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt", }, "sentencepiece_model_file": { "ernie-m-base": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model", "ernie-m-large": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model", }, } lowerCamelCase : Tuple = { "ernie-m-base": 5_1_4, "ernie-m-large": 5_1_4, } lowerCamelCase : int = { "ernie-m-base": {"do_lower_case": False}, "ernie-m-large": {"do_lower_case": False}, } class A__ ( A__ ): A__ = ["input_ids"] A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_INIT_CONFIGURATION A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = RESOURCE_FILES_NAMES def __init__( self : Tuple , _a : List[Any] , _a : Dict=None , _a : Dict=False , _a : List[Any]="utf8" , _a : Dict="[UNK]" , _a : List[Any]="[SEP]" , _a : List[str]="[PAD]" , _a : int="[CLS]" , _a : Dict="[MASK]" , _a : Optional[Dict[str, Any]] = None , **_a : Tuple , ) -> None: '''simple docstring''' _SCREAMING_SNAKE_CASE ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , vocab_file=_a , encoding=_a , sp_model_kwargs=self.sp_model_kwargs , **_a , ) _SCREAMING_SNAKE_CASE =do_lower_case _SCREAMING_SNAKE_CASE =sentencepiece_model_ckpt _SCREAMING_SNAKE_CASE =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_a ) # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning if vocab_file is not None: _SCREAMING_SNAKE_CASE =self.load_vocab(filepath=_a ) else: _SCREAMING_SNAKE_CASE ={self.sp_model.id_to_piece(_a ): id for id in range(self.sp_model.get_piece_size() )} _SCREAMING_SNAKE_CASE ={v: k for k, v in self.vocab.items()} def A ( self : Optional[int] , _a : Any ) -> List[Any]: '''simple docstring''' if text is None: return None _SCREAMING_SNAKE_CASE =self.tokenize(_a ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ='', [] for i, ch in enumerate(_a ): if ch in self.SP_CHAR_MAPPING: _SCREAMING_SNAKE_CASE =self.SP_CHAR_MAPPING.get(_a ) else: _SCREAMING_SNAKE_CASE =unicodedata.normalize('NFKC' , _a ) if self.is_whitespace(_a ): continue normalized_text += ch char_mapping.extend([i] * len(_a ) ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =normalized_text, [], 0 if self.do_lower_case: _SCREAMING_SNAKE_CASE =text.lower() for token in split_tokens: if token[:1] == "▁": _SCREAMING_SNAKE_CASE =token[1:] _SCREAMING_SNAKE_CASE =text[offset:].index(_a ) + offset _SCREAMING_SNAKE_CASE =start + len(_a ) token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1) ) _SCREAMING_SNAKE_CASE =end return token_mapping @property def A ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' return len(self.vocab ) def A ( self : int ) -> Optional[Any]: '''simple docstring''' return dict(self.vocab , **self.added_tokens_encoder ) def __getstate__( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.__dict__.copy() _SCREAMING_SNAKE_CASE =None return state def __setstate__( self : Any , _a : List[Any] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): _SCREAMING_SNAKE_CASE ={} _SCREAMING_SNAKE_CASE =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.sentencepiece_model_ckpt ) def A ( self : Any , _a : int ) -> Optional[Any]: '''simple docstring''' return "".join((self.SP_CHAR_MAPPING.get(_a , _a ) for c in text) ) def A ( self : List[Any] , _a : int , _a : Optional[int]=False , _a : Any=64 , _a : List[str]=0.1 ) -> Optional[Any]: '''simple docstring''' if self.sp_model_kwargs.get('enable_sampling' ) is True: _SCREAMING_SNAKE_CASE =True if self.sp_model_kwargs.get('alpha' ) is not None: _SCREAMING_SNAKE_CASE =self.sp_model_kwargs.get('alpha' ) if self.sp_model_kwargs.get('nbest_size' ) is not None: _SCREAMING_SNAKE_CASE =self.sp_model_kwargs.get('nbest_size' ) if not enable_sampling: _SCREAMING_SNAKE_CASE =self.sp_model.EncodeAsPieces(_a ) else: _SCREAMING_SNAKE_CASE =self.sp_model.SampleEncodeAsPieces(_a , _a , _a ) _SCREAMING_SNAKE_CASE =[] for pi, piece in enumerate(_a ): if piece == SPIECE_UNDERLINE: if not pieces[pi + 1].startswith(_a ) and pi != 0: new_pieces.append(_a ) continue else: continue _SCREAMING_SNAKE_CASE =0 for i, chunk in enumerate(_a ): if chunk == SPIECE_UNDERLINE: continue if self.is_ch_char(_a ) or self.is_punct(_a ): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) new_pieces.append(_a ) _SCREAMING_SNAKE_CASE =i + 1 elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) _SCREAMING_SNAKE_CASE =i elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) _SCREAMING_SNAKE_CASE =i if len(_a ) > lst_i: new_pieces.append(piece[lst_i:] ) return new_pieces def A ( self : List[str] , _a : List[str] ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =''.join(_a ).replace(_a , ' ' ).strip() return out_string def A ( self : str , _a : int ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.convert_ids_to_tokens(_a ) _SCREAMING_SNAKE_CASE =''.join(_a ).replace(_a , ' ' ).strip() return out_string def A ( self : List[str] , _a : Optional[int] ) -> Union[str, Any]: '''simple docstring''' return self.vocab.get(_a , self.vocab.get(self.unk_token ) ) def A ( self : List[Any] , _a : Optional[Any] ) -> Any: '''simple docstring''' return self.reverse_vocab.get(_a , self.unk_token ) def A ( self : Optional[Any] , _a : Union[str, Any] , _a : Dict=None ) -> Optional[int]: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _SCREAMING_SNAKE_CASE =[self.cls_token_id] _SCREAMING_SNAKE_CASE =[self.sep_token_id] return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep def A ( self : List[Any] , _a : Dict , _a : Optional[Any]=None ) -> Optional[int]: '''simple docstring''' if offset_mapping_a is None: return [(0, 0)] + offset_mapping_a + [(0, 0)] return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)] def A ( self : int , _a : Tuple , _a : Optional[int]=None , _a : Tuple=False ) -> List[Any]: '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( 'You should not supply a second sequence if the provided sequence of ' 'ids is already formatted with special tokens for the model.' ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1] def A ( self : List[str] , _a : List[int] , _a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' if token_ids_a is None: # [CLS] X [SEP] return (len(_a ) + 2) * [0] # [CLS] A [SEP] [SEP] B [SEP] return [0] * (len(_a ) + 1) + [1] * (len(_a ) + 3) def A ( self : List[Any] , _a : str ) -> Optional[int]: '''simple docstring''' if "\u4e00" <= char <= "\u9fff": return True return False def A ( self : Tuple , _a : Tuple ) -> Optional[Any]: '''simple docstring''' if ("a" <= char <= "z") or ("A" <= char <= "Z"): return True return False def A ( self : Tuple , _a : Optional[int] ) -> Any: '''simple docstring''' if char in ",;:.?!~,;:。?!《》【】": return True return False def A ( self : str , _a : int ) -> List[Any]: '''simple docstring''' if char == " " or char == "\t" or char == "\n" or char == "\r": return True if len(_a ) == 1: _SCREAMING_SNAKE_CASE =unicodedata.category(_a ) if cat == "Zs": return True return False def A ( self : str , _a : List[Any] ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE ={} with io.open(_a , 'r' , encoding='utf-8' ) as f: for index, line in enumerate(_a ): _SCREAMING_SNAKE_CASE =line.rstrip('\n' ) _SCREAMING_SNAKE_CASE =int(_a ) return token_to_idx def A ( self : str , _a : str , _a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =0 if os.path.isdir(_a ): _SCREAMING_SNAKE_CASE =os.path.join( _a , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) else: _SCREAMING_SNAKE_CASE =(filename_prefix + '-' if filename_prefix else '') + save_directory with open(_a , 'w' , encoding='utf-8' ) as writer: for token, token_index in sorted(self.vocab.items() , key=lambda _a : kv[1] ): if index != token_index: logger.warning( f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive." ' Please check that the vocabulary is not corrupted!' ) _SCREAMING_SNAKE_CASE =token_index writer.write(token + '\n' ) index += 1 _SCREAMING_SNAKE_CASE =os.path.join(_a , 'sentencepiece.bpe.model' ) with open(_a , 'wb' ) as fi: _SCREAMING_SNAKE_CASE =self.sp_model.serialized_model_proto() fi.write(_a ) return (vocab_file,)
47
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase : int = {"configuration_mbart": ["MBART_PRETRAINED_CONFIG_ARCHIVE_MAP", "MBartConfig", "MBartOnnxConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[Any] = ["MBartTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Dict = ["MBartTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : int = [ "MBART_PRETRAINED_MODEL_ARCHIVE_LIST", "MBartForCausalLM", "MBartForConditionalGeneration", "MBartForQuestionAnswering", "MBartForSequenceClassification", "MBartModel", "MBartPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Union[str, Any] = [ "TFMBartForConditionalGeneration", "TFMBartModel", "TFMBartPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[Any] = [ "FlaxMBartForConditionalGeneration", "FlaxMBartForQuestionAnswering", "FlaxMBartForSequenceClassification", "FlaxMBartModel", "FlaxMBartPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys lowerCamelCase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
47
1
'''simple docstring''' from typing import List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : Optional[int] = logging.get_logger(__name__) lowerCamelCase : Tuple = { "huggingface/autoformer-tourism-monthly": "https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json", } class A__ ( A__ ): A__ = 'autoformer' A__ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self : Dict , _a : Optional[int] = None , _a : Optional[int] = None , _a : str = "student_t" , _a : str = "nll" , _a : int = 1 , _a : List[int] = [1, 2, 3, 4, 5, 6, 7] , _a : bool = True , _a : int = 0 , _a : int = 0 , _a : int = 0 , _a : int = 0 , _a : Optional[List[int]] = None , _a : Optional[List[int]] = None , _a : int = 64 , _a : int = 2 , _a : int = 2 , _a : int = 2 , _a : int = 2 , _a : int = 32 , _a : int = 32 , _a : str = "gelu" , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : int = 100 , _a : float = 0.02 , _a : bool = True , _a : Dict=True , _a : int = 10 , _a : int = 25 , _a : int = 3 , **_a : str , ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =prediction_length _SCREAMING_SNAKE_CASE =context_length if context_length is not None else prediction_length _SCREAMING_SNAKE_CASE =distribution_output _SCREAMING_SNAKE_CASE =loss _SCREAMING_SNAKE_CASE =input_size _SCREAMING_SNAKE_CASE =num_time_features _SCREAMING_SNAKE_CASE =lags_sequence _SCREAMING_SNAKE_CASE =scaling _SCREAMING_SNAKE_CASE =num_dynamic_real_features _SCREAMING_SNAKE_CASE =num_static_real_features _SCREAMING_SNAKE_CASE =num_static_categorical_features if cardinality is not None 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`' ) _SCREAMING_SNAKE_CASE =cardinality else: _SCREAMING_SNAKE_CASE =[0] if embedding_dimension is not None 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`' ) _SCREAMING_SNAKE_CASE =embedding_dimension else: _SCREAMING_SNAKE_CASE =[min(50 , (cat + 1) // 2 ) for cat in self.cardinality] _SCREAMING_SNAKE_CASE =num_parallel_samples # Transformer architecture configuration _SCREAMING_SNAKE_CASE =input_size * len(self.lags_sequence ) + self._number_of_features _SCREAMING_SNAKE_CASE =d_model _SCREAMING_SNAKE_CASE =encoder_attention_heads _SCREAMING_SNAKE_CASE =decoder_attention_heads _SCREAMING_SNAKE_CASE =encoder_ffn_dim _SCREAMING_SNAKE_CASE =decoder_ffn_dim _SCREAMING_SNAKE_CASE =encoder_layers _SCREAMING_SNAKE_CASE =decoder_layers _SCREAMING_SNAKE_CASE =dropout _SCREAMING_SNAKE_CASE =attention_dropout _SCREAMING_SNAKE_CASE =activation_dropout _SCREAMING_SNAKE_CASE =encoder_layerdrop _SCREAMING_SNAKE_CASE =decoder_layerdrop _SCREAMING_SNAKE_CASE =activation_function _SCREAMING_SNAKE_CASE =init_std _SCREAMING_SNAKE_CASE =use_cache # Autoformer _SCREAMING_SNAKE_CASE =label_length _SCREAMING_SNAKE_CASE =moving_average _SCREAMING_SNAKE_CASE =autocorrelation_factor super().__init__(is_encoder_decoder=_a , **_a ) @property def A ( self : Any ) -> int: '''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 )
47
'''simple docstring''' from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : List[Any] = logging.get_logger(__name__) lowerCamelCase : str = { "huggingface/time-series-transformer-tourism-monthly": ( "https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json" ), # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer } class A__ ( A__ ): A__ = 'time_series_transformer' A__ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self : Optional[int] , _a : Optional[int] = None , _a : Optional[int] = None , _a : str = "student_t" , _a : str = "nll" , _a : int = 1 , _a : List[int] = [1, 2, 3, 4, 5, 6, 7] , _a : Optional[Union[str, bool]] = "mean" , _a : int = 0 , _a : int = 0 , _a : int = 0 , _a : int = 0 , _a : Optional[List[int]] = None , _a : Optional[List[int]] = None , _a : int = 32 , _a : int = 32 , _a : int = 2 , _a : int = 2 , _a : int = 2 , _a : int = 2 , _a : bool = True , _a : str = "gelu" , _a : int = 64 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : int = 100 , _a : float = 0.02 , _a : Union[str, Any]=True , **_a : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =prediction_length _SCREAMING_SNAKE_CASE =context_length or prediction_length _SCREAMING_SNAKE_CASE =distribution_output _SCREAMING_SNAKE_CASE =loss _SCREAMING_SNAKE_CASE =input_size _SCREAMING_SNAKE_CASE =num_time_features _SCREAMING_SNAKE_CASE =lags_sequence _SCREAMING_SNAKE_CASE =scaling _SCREAMING_SNAKE_CASE =num_dynamic_real_features _SCREAMING_SNAKE_CASE =num_static_real_features _SCREAMING_SNAKE_CASE =num_static_categorical_features 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`' ) _SCREAMING_SNAKE_CASE =cardinality else: _SCREAMING_SNAKE_CASE =[0] 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`' ) _SCREAMING_SNAKE_CASE =embedding_dimension else: _SCREAMING_SNAKE_CASE =[min(50 , (cat + 1) // 2 ) for cat in self.cardinality] _SCREAMING_SNAKE_CASE =num_parallel_samples # Transformer architecture configuration _SCREAMING_SNAKE_CASE =input_size * len(_a ) + self._number_of_features _SCREAMING_SNAKE_CASE =d_model _SCREAMING_SNAKE_CASE =encoder_attention_heads _SCREAMING_SNAKE_CASE =decoder_attention_heads _SCREAMING_SNAKE_CASE =encoder_ffn_dim _SCREAMING_SNAKE_CASE =decoder_ffn_dim _SCREAMING_SNAKE_CASE =encoder_layers _SCREAMING_SNAKE_CASE =decoder_layers _SCREAMING_SNAKE_CASE =dropout _SCREAMING_SNAKE_CASE =attention_dropout _SCREAMING_SNAKE_CASE =activation_dropout _SCREAMING_SNAKE_CASE =encoder_layerdrop _SCREAMING_SNAKE_CASE =decoder_layerdrop _SCREAMING_SNAKE_CASE =activation_function _SCREAMING_SNAKE_CASE =init_std _SCREAMING_SNAKE_CASE =use_cache super().__init__(is_encoder_decoder=_a , **_a ) @property def A ( self : List[Any] ) -> int: '''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 )
47
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class A__ ( unittest.TestCase ): def A ( self : List[str] ) -> Any: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def A ( self : Any ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =1 _SCREAMING_SNAKE_CASE =3 _SCREAMING_SNAKE_CASE =(32, 32) _SCREAMING_SNAKE_CASE =floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(_a ) return image @property def A ( self : Union[str, Any] ) -> int: '''simple docstring''' torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE =UNetaDConditionModel( block_out_channels=(32, 32, 64) , layers_per_block=2 , sample_size=32 , in_channels=7 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=8 , use_linear_projection=_a , only_cross_attention=(True, True, False) , num_class_embeds=100 , ) return model @property def A ( self : str ) -> List[Any]: '''simple docstring''' torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE =AutoencoderKL( block_out_channels=[32, 32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , ) return model @property def A ( self : Dict ) -> Union[str, Any]: '''simple docstring''' torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE =CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) return CLIPTextModel(_a ) def A ( self : Tuple ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE ='cpu' # ensure determinism for the device-dependent torch.Generator _SCREAMING_SNAKE_CASE =self.dummy_cond_unet_upscale _SCREAMING_SNAKE_CASE =DDPMScheduler() _SCREAMING_SNAKE_CASE =DDIMScheduler(prediction_type='v_prediction' ) _SCREAMING_SNAKE_CASE =self.dummy_vae _SCREAMING_SNAKE_CASE =self.dummy_text_encoder _SCREAMING_SNAKE_CASE =CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) _SCREAMING_SNAKE_CASE =self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0] _SCREAMING_SNAKE_CASE =Image.fromarray(np.uinta(_a ) ).convert('RGB' ).resize((64, 64) ) # make sure here that pndm scheduler skips prk _SCREAMING_SNAKE_CASE =StableDiffusionUpscalePipeline( unet=_a , low_res_scheduler=_a , scheduler=_a , vae=_a , text_encoder=_a , tokenizer=_a , max_noise_level=350 , ) _SCREAMING_SNAKE_CASE =sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) _SCREAMING_SNAKE_CASE ='A painting of a squirrel eating a burger' _SCREAMING_SNAKE_CASE =torch.Generator(device=_a ).manual_seed(0 ) _SCREAMING_SNAKE_CASE =sd_pipe( [prompt] , image=_a , generator=_a , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type='np' , ) _SCREAMING_SNAKE_CASE =output.images _SCREAMING_SNAKE_CASE =torch.Generator(device=_a ).manual_seed(0 ) _SCREAMING_SNAKE_CASE =sd_pipe( [prompt] , image=_a , generator=_a , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type='np' , return_dict=_a , )[0] _SCREAMING_SNAKE_CASE =image[0, -3:, -3:, -1] _SCREAMING_SNAKE_CASE =image_from_tuple[0, -3:, -3:, -1] _SCREAMING_SNAKE_CASE =low_res_image.size[0] * 4 assert image.shape == (1, expected_height_width, expected_height_width, 3) _SCREAMING_SNAKE_CASE =np.array([0.31_13, 0.39_10, 0.42_72, 0.48_59, 0.50_61, 0.46_52, 0.53_62, 0.57_15, 0.56_61] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def A ( self : str ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE ='cpu' # ensure determinism for the device-dependent torch.Generator _SCREAMING_SNAKE_CASE =self.dummy_cond_unet_upscale _SCREAMING_SNAKE_CASE =DDPMScheduler() _SCREAMING_SNAKE_CASE =DDIMScheduler(prediction_type='v_prediction' ) _SCREAMING_SNAKE_CASE =self.dummy_vae _SCREAMING_SNAKE_CASE =self.dummy_text_encoder _SCREAMING_SNAKE_CASE =CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) _SCREAMING_SNAKE_CASE =self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0] _SCREAMING_SNAKE_CASE =Image.fromarray(np.uinta(_a ) ).convert('RGB' ).resize((64, 64) ) # make sure here that pndm scheduler skips prk _SCREAMING_SNAKE_CASE =StableDiffusionUpscalePipeline( unet=_a , low_res_scheduler=_a , scheduler=_a , vae=_a , text_encoder=_a , tokenizer=_a , max_noise_level=350 , ) _SCREAMING_SNAKE_CASE =sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) _SCREAMING_SNAKE_CASE ='A painting of a squirrel eating a burger' _SCREAMING_SNAKE_CASE =sd_pipe( 2 * [prompt] , image=2 * [low_res_image] , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type='np' , ) _SCREAMING_SNAKE_CASE =output.images assert image.shape[0] == 2 _SCREAMING_SNAKE_CASE =torch.Generator(device=_a ).manual_seed(0 ) _SCREAMING_SNAKE_CASE =sd_pipe( [prompt] , image=_a , generator=_a , num_images_per_prompt=2 , guidance_scale=6.0 , noise_level=20 , num_inference_steps=2 , output_type='np' , ) _SCREAMING_SNAKE_CASE =output.images assert image.shape[0] == 2 @unittest.skipIf(torch_device != 'cuda' , 'This test requires a GPU' ) def A ( self : Dict ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.dummy_cond_unet_upscale _SCREAMING_SNAKE_CASE =DDPMScheduler() _SCREAMING_SNAKE_CASE =DDIMScheduler(prediction_type='v_prediction' ) _SCREAMING_SNAKE_CASE =self.dummy_vae _SCREAMING_SNAKE_CASE =self.dummy_text_encoder _SCREAMING_SNAKE_CASE =CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) _SCREAMING_SNAKE_CASE =self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0] _SCREAMING_SNAKE_CASE =Image.fromarray(np.uinta(_a ) ).convert('RGB' ).resize((64, 64) ) # put models in fp16, except vae as it overflows in fp16 _SCREAMING_SNAKE_CASE =unet.half() _SCREAMING_SNAKE_CASE =text_encoder.half() # make sure here that pndm scheduler skips prk _SCREAMING_SNAKE_CASE =StableDiffusionUpscalePipeline( unet=_a , low_res_scheduler=_a , scheduler=_a , vae=_a , text_encoder=_a , tokenizer=_a , max_noise_level=350 , ) _SCREAMING_SNAKE_CASE =sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) _SCREAMING_SNAKE_CASE ='A painting of a squirrel eating a burger' _SCREAMING_SNAKE_CASE =torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE =sd_pipe( [prompt] , image=_a , generator=_a , num_inference_steps=2 , output_type='np' , ).images _SCREAMING_SNAKE_CASE =low_res_image.size[0] * 4 assert image.shape == (1, expected_height_width, expected_height_width, 3) @slow @require_torch_gpu class A__ ( unittest.TestCase ): def A ( self : int ) -> Tuple: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def A ( self : List[Any] ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-upscale/low_res_cat.png' ) _SCREAMING_SNAKE_CASE =load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale' '/upsampled_cat.npy' ) _SCREAMING_SNAKE_CASE ='stabilityai/stable-diffusion-x4-upscaler' _SCREAMING_SNAKE_CASE =StableDiffusionUpscalePipeline.from_pretrained(_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() _SCREAMING_SNAKE_CASE ='a cat sitting on a park bench' _SCREAMING_SNAKE_CASE =torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE =pipe( prompt=_a , image=_a , generator=_a , output_type='np' , ) _SCREAMING_SNAKE_CASE =output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1e-3 def A ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-upscale/low_res_cat.png' ) _SCREAMING_SNAKE_CASE =load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale' '/upsampled_cat_fp16.npy' ) _SCREAMING_SNAKE_CASE ='stabilityai/stable-diffusion-x4-upscaler' _SCREAMING_SNAKE_CASE =StableDiffusionUpscalePipeline.from_pretrained( _a , torch_dtype=torch.floataa , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() _SCREAMING_SNAKE_CASE ='a cat sitting on a park bench' _SCREAMING_SNAKE_CASE =torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE =pipe( prompt=_a , image=_a , generator=_a , output_type='np' , ) _SCREAMING_SNAKE_CASE =output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5e-1 def A ( self : Union[str, Any] ) -> Dict: '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _SCREAMING_SNAKE_CASE =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-upscale/low_res_cat.png' ) _SCREAMING_SNAKE_CASE ='stabilityai/stable-diffusion-x4-upscaler' _SCREAMING_SNAKE_CASE =StableDiffusionUpscalePipeline.from_pretrained( _a , torch_dtype=torch.floataa , ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() _SCREAMING_SNAKE_CASE ='a cat sitting on a park bench' _SCREAMING_SNAKE_CASE =torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE =pipe( prompt=_a , image=_a , generator=_a , num_inference_steps=5 , output_type='np' , ) _SCREAMING_SNAKE_CASE =torch.cuda.max_memory_allocated() # make sure that less than 2.9 GB is allocated assert mem_bytes < 2.9 * 10**9
47
'''simple docstring''' import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets lowerCamelCase : List[Any] = "\\n @inproceedings{kakwani2020indicnlpsuite,\n title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}},\n author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar},\n year={2020},\n booktitle={Findings of EMNLP},\n}\n" lowerCamelCase : Optional[Any] = "\\n IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide\n variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te.\n" lowerCamelCase : int = "\nCompute IndicGLUE evaluation metric associated to each IndicGLUE dataset.\nArgs:\n predictions: list of predictions to score (as int64),\n except for 'cvit-mkb-clsr' where each prediction is a vector (of float32).\n references: list of ground truth labels corresponding to the predictions (as int64),\n except for 'cvit-mkb-clsr' where each reference is a vector (of float32).\nReturns: depending on the IndicGLUE subset, one or several of:\n \"accuracy\": Accuracy\n \"f1\": F1 score\n \"precision\": Precision@10\nExamples:\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr')\n >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'precision@10': 1.0}\n\n" def _lowerCAmelCase ( _UpperCamelCase : List[str] , _UpperCamelCase : Tuple ) -> List[Any]: """simple docstring""" return float((preds == labels).mean() ) def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Any ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =simple_accuracy(_UpperCamelCase , _UpperCamelCase ) _SCREAMING_SNAKE_CASE =float(fa_score(y_true=_UpperCamelCase , y_pred=_UpperCamelCase ) ) return { "accuracy": acc, "f1": fa, } def _lowerCAmelCase ( _UpperCamelCase : Any , _UpperCamelCase : int ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =en_sentvecs.shape[0] # mean centering _SCREAMING_SNAKE_CASE =en_sentvecs - np.mean(_UpperCamelCase , axis=0 ) _SCREAMING_SNAKE_CASE =in_sentvecs - np.mean(_UpperCamelCase , axis=0 ) _SCREAMING_SNAKE_CASE =cdist(_UpperCamelCase , _UpperCamelCase , 'cosine' ) _SCREAMING_SNAKE_CASE =np.array(range(_UpperCamelCase ) ) _SCREAMING_SNAKE_CASE =sim.argsort(axis=1 )[:, :10] _SCREAMING_SNAKE_CASE =np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def A ( self : Any ) -> List[str]: '''simple docstring''' if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('int64' ) if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32' ) ), 'references': datasets.Value('int64' ) if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32' ) ), } ) , codebase_urls=[] , reference_urls=[] , format='numpy' if self.config_name != 'cvit-mkb-clsr' else None , ) def A ( self : List[str] , _a : Tuple , _a : Optional[int] ) -> int: '''simple docstring''' if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(_a , _a )} elif self.config_name in ["wiki-ner"]: return acc_and_fa(_a , _a ) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(_a , _a )} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]' )
47
1
'''simple docstring''' def _lowerCAmelCase ( _UpperCamelCase : str ) -> str: """simple docstring""" return "".join(chr(ord(_UpperCamelCase ) - 32 ) if 'a' <= char <= 'z' else char for char in word ) if __name__ == "__main__": from doctest import testmod testmod()
47
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase : Dict = logging.get_logger(__name__) lowerCamelCase : List[Any] = { "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json", } class A__ ( A__ ): A__ = 'deta' A__ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Tuple , _a : Optional[int]=None , _a : int=900 , _a : Optional[Any]=2048 , _a : int=6 , _a : Tuple=2048 , _a : Optional[int]=8 , _a : Any=6 , _a : str=1024 , _a : int=8 , _a : int=0.0 , _a : Optional[Any]=True , _a : Tuple="relu" , _a : Union[str, Any]=256 , _a : Tuple=0.1 , _a : str=0.0 , _a : Dict=0.0 , _a : Tuple=0.02 , _a : Union[str, Any]=1.0 , _a : Any=True , _a : Tuple=False , _a : List[Any]="sine" , _a : str=5 , _a : List[Any]=4 , _a : str=4 , _a : Union[str, Any]=True , _a : Optional[int]=300 , _a : Dict=True , _a : List[Any]=True , _a : List[Any]=1 , _a : List[str]=5 , _a : int=2 , _a : Dict=1 , _a : str=1 , _a : Optional[Any]=5 , _a : Union[str, Any]=2 , _a : List[str]=0.1 , _a : List[Any]=0.25 , **_a : Union[str, Any] , ) -> List[str]: '''simple docstring''' if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) _SCREAMING_SNAKE_CASE =CONFIG_MAPPING['resnet'](out_features=['stage2', 'stage3', 'stage4'] ) else: if isinstance(_a , _a ): _SCREAMING_SNAKE_CASE =backbone_config.pop('model_type' ) _SCREAMING_SNAKE_CASE =CONFIG_MAPPING[backbone_model_type] _SCREAMING_SNAKE_CASE =config_class.from_dict(_a ) _SCREAMING_SNAKE_CASE =backbone_config _SCREAMING_SNAKE_CASE =num_queries _SCREAMING_SNAKE_CASE =max_position_embeddings _SCREAMING_SNAKE_CASE =d_model _SCREAMING_SNAKE_CASE =encoder_ffn_dim _SCREAMING_SNAKE_CASE =encoder_layers _SCREAMING_SNAKE_CASE =encoder_attention_heads _SCREAMING_SNAKE_CASE =decoder_ffn_dim _SCREAMING_SNAKE_CASE =decoder_layers _SCREAMING_SNAKE_CASE =decoder_attention_heads _SCREAMING_SNAKE_CASE =dropout _SCREAMING_SNAKE_CASE =attention_dropout _SCREAMING_SNAKE_CASE =activation_dropout _SCREAMING_SNAKE_CASE =activation_function _SCREAMING_SNAKE_CASE =init_std _SCREAMING_SNAKE_CASE =init_xavier_std _SCREAMING_SNAKE_CASE =encoder_layerdrop _SCREAMING_SNAKE_CASE =auxiliary_loss _SCREAMING_SNAKE_CASE =position_embedding_type # deformable attributes _SCREAMING_SNAKE_CASE =num_feature_levels _SCREAMING_SNAKE_CASE =encoder_n_points _SCREAMING_SNAKE_CASE =decoder_n_points _SCREAMING_SNAKE_CASE =two_stage _SCREAMING_SNAKE_CASE =two_stage_num_proposals _SCREAMING_SNAKE_CASE =with_box_refine _SCREAMING_SNAKE_CASE =assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError('If two_stage is True, with_box_refine must be True.' ) # Hungarian matcher _SCREAMING_SNAKE_CASE =class_cost _SCREAMING_SNAKE_CASE =bbox_cost _SCREAMING_SNAKE_CASE =giou_cost # Loss coefficients _SCREAMING_SNAKE_CASE =mask_loss_coefficient _SCREAMING_SNAKE_CASE =dice_loss_coefficient _SCREAMING_SNAKE_CASE =bbox_loss_coefficient _SCREAMING_SNAKE_CASE =giou_loss_coefficient _SCREAMING_SNAKE_CASE =eos_coefficient _SCREAMING_SNAKE_CASE =focal_alpha super().__init__(is_encoder_decoder=_a , **_a ) @property def A ( self : Dict ) -> int: '''simple docstring''' return self.encoder_attention_heads @property def A ( self : List[Any] ) -> int: '''simple docstring''' return self.d_model def A ( self : Optional[int] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =copy.deepcopy(self.__dict__ ) _SCREAMING_SNAKE_CASE =self.backbone_config.to_dict() _SCREAMING_SNAKE_CASE =self.__class__.model_type return output
47
1
'''simple docstring''' import os import time import numpy as np import onnxruntime as ort lowerCamelCase : Tuple = "1" lowerCamelCase : Optional[Any] = "0" lowerCamelCase : Dict = "1" lowerCamelCase : List[str] = ort.SessionOptions() lowerCamelCase : str = ort.GraphOptimizationLevel.ORT_DISABLE_ALL print("Create inference session...") lowerCamelCase : Optional[Any] = ["TensorrtExecutionProvider", "CUDAExecutionProvider"] lowerCamelCase : Optional[int] = ort.InferenceSession("model.onnx", sess_options=sess_opt, providers=execution_provider) lowerCamelCase : Dict = ort.RunOptions() lowerCamelCase : Dict = 1_2_8 lowerCamelCase : Optional[int] = 1 lowerCamelCase : List[str] = np.ones((batch, sequence), dtype=np.intaa) lowerCamelCase : List[str] = np.ones((batch, sequence), dtype=np.intaa) lowerCamelCase : List[str] = np.ones((batch, sequence), dtype=np.intaa) print("Warm up phase...") sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print("Start inference...") lowerCamelCase : List[str] = time.time() lowerCamelCase : Tuple = 2_0_0_0 lowerCamelCase : List[Any] = {} for iter in range(max_iters): lowerCamelCase : List[str] = sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print("Average Inference Time = {:.3f} ms".format((time.time() - start_time) * 1_0_0_0 / max_iters))
47
'''simple docstring''' import numpy as np from PIL import Image def _lowerCAmelCase ( _UpperCamelCase : np.ndarray , _UpperCamelCase : int , _UpperCamelCase : int ) -> np.ndarray: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 # compute the shape of the output matrix _SCREAMING_SNAKE_CASE =(arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape _SCREAMING_SNAKE_CASE =np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix _SCREAMING_SNAKE_CASE =np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 return updated_arr def _lowerCAmelCase ( _UpperCamelCase : np.ndarray , _UpperCamelCase : int , _UpperCamelCase : int ) -> np.ndarray: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 # compute the shape of the output matrix _SCREAMING_SNAKE_CASE =(arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape _SCREAMING_SNAKE_CASE =np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix _SCREAMING_SNAKE_CASE =int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name="avgpooling", verbose=True) # Loading the image lowerCamelCase : Optional[Any] = Image.open("path_to_image") # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
47
1
'''simple docstring''' lowerCamelCase : Tuple = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def _lowerCAmelCase ( ) -> None: """simple docstring""" _SCREAMING_SNAKE_CASE =input('Enter message: ' ) _SCREAMING_SNAKE_CASE =input('Enter key [alphanumeric]: ' ) _SCREAMING_SNAKE_CASE =input('Encrypt/Decrypt [e/d]: ' ) if mode.lower().startswith('e' ): _SCREAMING_SNAKE_CASE ='encrypt' _SCREAMING_SNAKE_CASE =encrypt_message(_UpperCamelCase , _UpperCamelCase ) elif mode.lower().startswith('d' ): _SCREAMING_SNAKE_CASE ='decrypt' _SCREAMING_SNAKE_CASE =decrypt_message(_UpperCamelCase , _UpperCamelCase ) print(f"\n{mode.title()}ed message:" ) print(_UpperCamelCase ) def _lowerCAmelCase ( _UpperCamelCase : str , _UpperCamelCase : str ) -> str: """simple docstring""" return translate_message(_UpperCamelCase , _UpperCamelCase , 'encrypt' ) def _lowerCAmelCase ( _UpperCamelCase : str , _UpperCamelCase : str ) -> str: """simple docstring""" return translate_message(_UpperCamelCase , _UpperCamelCase , 'decrypt' ) def _lowerCAmelCase ( _UpperCamelCase : str , _UpperCamelCase : str , _UpperCamelCase : str ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =key.upper() for symbol in message: _SCREAMING_SNAKE_CASE =LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(_UpperCamelCase ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(_UpperCamelCase ): _SCREAMING_SNAKE_CASE =0 else: translated.append(_UpperCamelCase ) return "".join(_UpperCamelCase ) if __name__ == "__main__": main()
47
'''simple docstring''' import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _lowerCAmelCase ( ) -> Any: """simple docstring""" _SCREAMING_SNAKE_CASE =ArgumentParser( description=( 'PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes' ) ) # Optional arguments for the launch helper parser.add_argument('--num_cores' , type=_UpperCamelCase , default=1 , help='Number of TPU cores to use (1 or 8).' ) # positional parser.add_argument( 'training_script' , type=_UpperCamelCase , help=( 'The full path to the single TPU training ' 'program/script to be launched in parallel, ' 'followed by all the arguments for the ' 'training script' ) , ) # rest from the training program parser.add_argument('training_script_args' , nargs=_UpperCamelCase ) return parser.parse_args() def _lowerCAmelCase ( ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =parse_args() # Import training_script as a module. _SCREAMING_SNAKE_CASE =Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) _SCREAMING_SNAKE_CASE =script_fpath.stem _SCREAMING_SNAKE_CASE =importlib.import_module(_UpperCamelCase ) # Patch sys.argv _SCREAMING_SNAKE_CASE =[args.training_script] + args.training_script_args + ['--tpu_num_cores', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
47
1
'''simple docstring''' import argparse import re import numpy as np import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SamConfig, SamImageProcessor, SamModel, SamProcessor, SamVisionConfig, ) lowerCamelCase : Optional[int] = { "iou_prediction_head.layers.0": "iou_prediction_head.proj_in", "iou_prediction_head.layers.1": "iou_prediction_head.layers.0", "iou_prediction_head.layers.2": "iou_prediction_head.proj_out", "mask_decoder.output_upscaling.0": "mask_decoder.upscale_conv1", "mask_decoder.output_upscaling.1": "mask_decoder.upscale_layer_norm", "mask_decoder.output_upscaling.3": "mask_decoder.upscale_conv2", "mask_downscaling.0": "mask_embed.conv1", "mask_downscaling.1": "mask_embed.layer_norm1", "mask_downscaling.3": "mask_embed.conv2", "mask_downscaling.4": "mask_embed.layer_norm2", "mask_downscaling.6": "mask_embed.conv3", "point_embeddings": "point_embed", "pe_layer.positional_encoding_gaussian_matrix": "shared_embedding.positional_embedding", "image_encoder": "vision_encoder", "neck.0": "neck.conv1", "neck.1": "neck.layer_norm1", "neck.2": "neck.conv2", "neck.3": "neck.layer_norm2", "patch_embed.proj": "patch_embed.projection", ".norm": ".layer_norm", "blocks": "layers", } def _lowerCAmelCase ( _UpperCamelCase : Tuple ) -> Optional[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE ={} state_dict.pop('pixel_mean' , _UpperCamelCase ) state_dict.pop('pixel_std' , _UpperCamelCase ) _SCREAMING_SNAKE_CASE =r'.*.output_hypernetworks_mlps.(\d+).layers.(\d+).*' for key, value in state_dict.items(): for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: _SCREAMING_SNAKE_CASE =key.replace(_UpperCamelCase , _UpperCamelCase ) if re.match(_UpperCamelCase , _UpperCamelCase ): _SCREAMING_SNAKE_CASE =int(re.match(_UpperCamelCase , _UpperCamelCase ).group(2 ) ) if layer_nb == 0: _SCREAMING_SNAKE_CASE =key.replace('layers.0' , 'proj_in' ) elif layer_nb == 1: _SCREAMING_SNAKE_CASE =key.replace('layers.1' , 'layers.0' ) elif layer_nb == 2: _SCREAMING_SNAKE_CASE =key.replace('layers.2' , 'proj_out' ) _SCREAMING_SNAKE_CASE =value _SCREAMING_SNAKE_CASE =model_state_dict[ 'prompt_encoder.shared_embedding.positional_embedding' ] return model_state_dict def _lowerCAmelCase ( _UpperCamelCase : List[Any] , _UpperCamelCase : Dict , _UpperCamelCase : str , _UpperCamelCase : Dict="ybelkada/segment-anything" ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE =hf_hub_download(_UpperCamelCase , f"checkpoints/{model_name}.pth" ) if "sam_vit_b" in model_name: _SCREAMING_SNAKE_CASE =SamConfig() elif "sam_vit_l" in model_name: _SCREAMING_SNAKE_CASE =SamVisionConfig( hidden_size=10_24 , num_hidden_layers=24 , num_attention_heads=16 , global_attn_indexes=[5, 11, 17, 23] , ) _SCREAMING_SNAKE_CASE =SamConfig( vision_config=_UpperCamelCase , ) elif "sam_vit_h" in model_name: _SCREAMING_SNAKE_CASE =SamVisionConfig( hidden_size=12_80 , num_hidden_layers=32 , num_attention_heads=16 , global_attn_indexes=[7, 15, 23, 31] , ) _SCREAMING_SNAKE_CASE =SamConfig( vision_config=_UpperCamelCase , ) _SCREAMING_SNAKE_CASE =torch.load(_UpperCamelCase , map_location='cpu' ) _SCREAMING_SNAKE_CASE =replace_keys(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =SamImageProcessor() _SCREAMING_SNAKE_CASE =SamProcessor(image_processor=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =SamModel(_UpperCamelCase ) hf_model.load_state_dict(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =hf_model.to('cuda' ) _SCREAMING_SNAKE_CASE ='https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png' _SCREAMING_SNAKE_CASE =Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ).convert('RGB' ) _SCREAMING_SNAKE_CASE =[[[4_00, 6_50]]] _SCREAMING_SNAKE_CASE =[[1]] _SCREAMING_SNAKE_CASE =processor(images=np.array(_UpperCamelCase ) , return_tensors='pt' ).to('cuda' ) with torch.no_grad(): _SCREAMING_SNAKE_CASE =hf_model(**_UpperCamelCase ) _SCREAMING_SNAKE_CASE =output.iou_scores.squeeze() if model_name == "sam_vit_h_4b8939": assert scores[-1].item() == 0.5_79_89_02_51_15_96_68 _SCREAMING_SNAKE_CASE =processor( images=np.array(_UpperCamelCase ) , input_points=_UpperCamelCase , input_labels=_UpperCamelCase , return_tensors='pt' ).to('cuda' ) with torch.no_grad(): _SCREAMING_SNAKE_CASE =hf_model(**_UpperCamelCase ) _SCREAMING_SNAKE_CASE =output.iou_scores.squeeze() assert scores[-1].item() == 0.97_12_60_30_92_19_36_04 _SCREAMING_SNAKE_CASE =((75, 2_75, 17_25, 8_50),) _SCREAMING_SNAKE_CASE =processor(images=np.array(_UpperCamelCase ) , input_boxes=_UpperCamelCase , return_tensors='pt' ).to('cuda' ) with torch.no_grad(): _SCREAMING_SNAKE_CASE =hf_model(**_UpperCamelCase ) _SCREAMING_SNAKE_CASE =output.iou_scores.squeeze() assert scores[-1].item() == 0.86_86_01_56_05_92_65_14 # Test with 2 points and 1 image. _SCREAMING_SNAKE_CASE =[[[4_00, 6_50], [8_00, 6_50]]] _SCREAMING_SNAKE_CASE =[[1, 1]] _SCREAMING_SNAKE_CASE =processor( images=np.array(_UpperCamelCase ) , input_points=_UpperCamelCase , input_labels=_UpperCamelCase , return_tensors='pt' ).to('cuda' ) with torch.no_grad(): _SCREAMING_SNAKE_CASE =hf_model(**_UpperCamelCase ) _SCREAMING_SNAKE_CASE =output.iou_scores.squeeze() assert scores[-1].item() == 0.99_36_04_77_92_43_46_92 if __name__ == "__main__": lowerCamelCase : Optional[Any] = argparse.ArgumentParser() lowerCamelCase : int = ["sam_vit_b_01ec64", "sam_vit_h_4b8939", "sam_vit_l_0b3195"] parser.add_argument( "--model_name", default="sam_vit_h_4b8939", choices=choices, type=str, help="Path to hf config.json of model to convert", ) parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument( "--push_to_hub", action="store_true", help="Whether to push the model and processor to the hub after converting", ) parser.add_argument( "--model_hub_id", default="ybelkada/segment-anything", choices=choices, type=str, help="Path to hf config.json of model to convert", ) lowerCamelCase : Optional[Any] = parser.parse_args() convert_sam_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub, args.model_hub_id)
47
'''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. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class A__ ( A__ ): A__ = ( 'This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.' 'It takes two arguments named `image` which should be the original image, and `label` which should be a text ' 'describing the elements what should be identified in the segmentation mask. The tool returns the mask.' ) A__ = 'CIDAS/clipseg-rd64-refined' A__ = 'image_segmenter' A__ = CLIPSegForImageSegmentation A__ = ['image', 'text'] A__ = ['image'] def __init__( self : Any , *_a : Dict , **_a : str ) -> Any: '''simple docstring''' requires_backends(self , ['vision'] ) super().__init__(*_a , **_a ) def A ( self : int , _a : "Image" , _a : str ) -> Optional[Any]: '''simple docstring''' return self.pre_processor(text=[label] , images=[image] , padding=_a , return_tensors='pt' ) def A ( self : Dict , _a : Dict ) -> str: '''simple docstring''' with torch.no_grad(): _SCREAMING_SNAKE_CASE =self.model(**_a ).logits return logits def A ( self : Any , _a : str ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =outputs.cpu().detach().numpy() _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =1 return Image.fromarray((array * 255).astype(np.uinta ) )
47
1
'''simple docstring''' from math import factorial def _lowerCAmelCase ( _UpperCamelCase : int = 1_00 ) -> int: """simple docstring""" return sum(int(_UpperCamelCase ) for x in str(factorial(_UpperCamelCase ) ) ) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
47
'''simple docstring''' from __future__ import annotations import math def _lowerCAmelCase ( _UpperCamelCase : int ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_UpperCamelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowerCAmelCase ( _UpperCamelCase : int ) -> list[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =str(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =[n] for i in range(1 , len(_UpperCamelCase ) ): list_nums.append(int(str_num[i:] ) ) list_nums.append(int(str_num[:-i] ) ) return list_nums def _lowerCAmelCase ( _UpperCamelCase : int ) -> bool: """simple docstring""" if len(str(_UpperCamelCase ) ) > 3: if not is_prime(int(str(_UpperCamelCase )[-3:] ) ) or not is_prime(int(str(_UpperCamelCase )[:3] ) ): return False return True def _lowerCAmelCase ( _UpperCamelCase : int = 11 ) -> list[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =13 while len(_UpperCamelCase ) != count: if validate(_UpperCamelCase ): _SCREAMING_SNAKE_CASE =list_truncated_nums(_UpperCamelCase ) if all(is_prime(_UpperCamelCase ) for i in list_nums ): list_truncated_primes.append(_UpperCamelCase ) num += 2 return list_truncated_primes def _lowerCAmelCase ( ) -> int: """simple docstring""" return sum(compute_truncated_primes(11 ) ) if __name__ == "__main__": print(f'''{sum(compute_truncated_primes(1_1)) = }''')
47
1
'''simple docstring''' from __future__ import annotations from statistics import mean def _lowerCAmelCase ( _UpperCamelCase : list[int] , _UpperCamelCase : list[int] , _UpperCamelCase : int ) -> list[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =[0] * no_of_processes _SCREAMING_SNAKE_CASE =[0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(_UpperCamelCase ): _SCREAMING_SNAKE_CASE =burst_time[i] _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =-1 for i in range(_UpperCamelCase ): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(_UpperCamelCase ) if len(_UpperCamelCase ) > 0: _SCREAMING_SNAKE_CASE =ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: _SCREAMING_SNAKE_CASE =i total_time += burst_time[target_process] completed += 1 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def _lowerCAmelCase ( _UpperCamelCase : list[int] , _UpperCamelCase : int , _UpperCamelCase : list[int] ) -> list[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =[0] * no_of_processes for i in range(_UpperCamelCase ): _SCREAMING_SNAKE_CASE =burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print("[TEST CASE 01]") lowerCamelCase : Optional[Any] = 4 lowerCamelCase : List[str] = [2, 5, 3, 7] lowerCamelCase : int = [0, 0, 0, 0] lowerCamelCase : Optional[int] = calculate_waitingtime(arrival_time, burst_time, no_of_processes) lowerCamelCase : int = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print("PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time") for i, process_id in enumerate(list(range(1, 5))): print( f'''{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t''' f'''{waiting_time[i]}\t\t\t\t{turn_around_time[i]}''' ) print(f'''\nAverage waiting time = {mean(waiting_time):.5f}''') print(f'''Average turnaround time = {mean(turn_around_time):.5f}''')
47
'''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: lowerCamelCase : int = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class A__ ( unittest.TestCase ): def __init__( self : List[str] , _a : List[Any] , _a : List[str]=7 , _a : List[str]=3 , _a : Tuple=18 , _a : Tuple=30 , _a : str=400 , _a : Tuple=None , _a : Union[str, Any]=True , _a : List[str]=True , _a : Optional[int]=None , ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =size if size is not None else {'height': 20, 'width': 20} _SCREAMING_SNAKE_CASE =parent _SCREAMING_SNAKE_CASE =batch_size _SCREAMING_SNAKE_CASE =num_channels _SCREAMING_SNAKE_CASE =image_size _SCREAMING_SNAKE_CASE =min_resolution _SCREAMING_SNAKE_CASE =max_resolution _SCREAMING_SNAKE_CASE =size _SCREAMING_SNAKE_CASE =do_normalize _SCREAMING_SNAKE_CASE =do_convert_rgb _SCREAMING_SNAKE_CASE =[512, 1024, 2048, 4096] _SCREAMING_SNAKE_CASE =patch_size if patch_size is not None else {'height': 16, 'width': 16} def A ( self : Any ) -> List[str]: '''simple docstring''' return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def A ( self : int ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE ='https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg' _SCREAMING_SNAKE_CASE =Image.open(requests.get(_a , stream=_a ).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 A__ ( A__ , unittest.TestCase ): A__ = PixaStructImageProcessor if is_vision_available() else None def A ( self : Dict ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =PixaStructImageProcessingTester(self ) @property def A ( self : Optional[Any] ) -> int: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def A ( self : Any ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_a , 'do_normalize' ) ) self.assertTrue(hasattr(_a , 'do_convert_rgb' ) ) def A ( self : Any ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processor_tester.prepare_dummy_image() _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) _SCREAMING_SNAKE_CASE =2048 _SCREAMING_SNAKE_CASE =image_processor(_a , return_tensors='pt' , max_patches=_a ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.06_06 ) , atol=1e-3 , rtol=1e-3 ) ) def A ( self : Any ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PIL images _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input _SCREAMING_SNAKE_CASE =( (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 _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def A ( self : List[str] ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PIL images _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input _SCREAMING_SNAKE_CASE =( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 _SCREAMING_SNAKE_CASE =True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(_a ): _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches _SCREAMING_SNAKE_CASE ='Hello' _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a , header_text=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a , header_text=_a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def A ( self : List[Any] ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , numpify=_a ) for image in image_inputs: self.assertIsInstance(_a , np.ndarray ) _SCREAMING_SNAKE_CASE =( (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 _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def A ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , torchify=_a ) for image in image_inputs: self.assertIsInstance(_a , torch.Tensor ) # Test not batched input _SCREAMING_SNAKE_CASE =( (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 _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a ).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 A__ ( A__ , unittest.TestCase ): A__ = PixaStructImageProcessor if is_vision_available() else None def A ( self : str ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =PixaStructImageProcessingTester(self , num_channels=4 ) _SCREAMING_SNAKE_CASE =3 @property def A ( self : List[str] ) -> Optional[Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def A ( self : List[str] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_a , 'do_normalize' ) ) self.assertTrue(hasattr(_a , 'do_convert_rgb' ) ) def A ( self : Dict ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PIL images _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input _SCREAMING_SNAKE_CASE =( (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 _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
47
1
'''simple docstring''' import os from collections import deque import torch from torch.utils.data import Dataset class A__ ( A__ ): def __init__( self : List[str] , _a : Optional[Any]="" , _a : Any="train" ) -> int: '''simple docstring''' assert os.path.isdir(_a ) _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =os.listdir(_a ) for story_filename in story_filenames_list: if "summary" in story_filename: continue _SCREAMING_SNAKE_CASE =os.path.join(_a , _a ) if not os.path.isfile(_a ): continue self.documents.append(_a ) def __len__( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' return len(self.documents ) def __getitem__( self : Optional[int] , _a : Dict ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.documents[idx] _SCREAMING_SNAKE_CASE =document_path.split('/' )[-1] with open(_a , encoding='utf-8' ) as source: _SCREAMING_SNAKE_CASE =source.read() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =process_story(_a ) return document_name, story_lines, summary_lines def _lowerCAmelCase ( _UpperCamelCase : Optional[int] ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =list(filter(lambda _UpperCamelCase : len(_UpperCamelCase ) != 0 , [line.strip() for line in raw_story.split('\n' )] ) ) # for some unknown reason some lines miss a period, add it _SCREAMING_SNAKE_CASE =[_add_missing_period(_UpperCamelCase ) for line in nonempty_lines] # gather article lines _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =deque(_UpperCamelCase ) while True: try: _SCREAMING_SNAKE_CASE =lines.popleft() if element.startswith('@highlight' ): break story_lines.append(_UpperCamelCase ) except IndexError: # if "@highlight" is absent from the file we pop # all elements until there is None, raising an exception. return story_lines, [] # gather summary lines _SCREAMING_SNAKE_CASE =list(filter(lambda _UpperCamelCase : not t.startswith('@highlight' ) , _UpperCamelCase ) ) return story_lines, summary_lines def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE =['.', '!', '?', '...', '\'', '`', '"', '\u2019', '\u2019', ')'] if line.startswith('@highlight' ): return line if line[-1] in END_TOKENS: return line return line + "." def _lowerCAmelCase ( _UpperCamelCase : List[Any] , _UpperCamelCase : int , _UpperCamelCase : str ) -> Optional[Any]: """simple docstring""" if len(_UpperCamelCase ) > block_size: return sequence[:block_size] else: sequence.extend([pad_token_id] * (block_size - len(_UpperCamelCase )) ) return sequence def _lowerCAmelCase ( _UpperCamelCase : List[str] , _UpperCamelCase : str ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE =torch.ones_like(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =sequence == pad_token_id _SCREAMING_SNAKE_CASE =0 return mask def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Dict , _UpperCamelCase : List[Any] ) -> Union[str, Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =[tokenizer.encode(_UpperCamelCase ) for line in story_lines] _SCREAMING_SNAKE_CASE =[token for sentence in story_lines_token_ids for token in sentence] _SCREAMING_SNAKE_CASE =[tokenizer.encode(_UpperCamelCase ) for line in summary_lines] _SCREAMING_SNAKE_CASE =[token for sentence in summary_lines_token_ids for token in sentence] return story_token_ids, summary_token_ids def _lowerCAmelCase ( _UpperCamelCase : Optional[int] , _UpperCamelCase : Tuple ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =[] for sequence in batch: _SCREAMING_SNAKE_CASE =-1 _SCREAMING_SNAKE_CASE =[] for s in sequence: if s == separator_token_id: sentence_num += 1 embeddings.append(sentence_num % 2 ) batch_embeddings.append(_UpperCamelCase ) return torch.tensor(_UpperCamelCase )
47
'''simple docstring''' import copy import re class A__ : A__ = 'hp' A__ = {} A__ = None @classmethod def A ( cls : Optional[Any] , _a : Optional[Any] , _a : Any ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =prefix _SCREAMING_SNAKE_CASE =defaults cls.build_naming_info() @staticmethod def A ( _a : Optional[Any] , _a : List[Any] ) -> Any: '''simple docstring''' if len(_a ) == 0: return "" _SCREAMING_SNAKE_CASE =None if any(char.isdigit() for char in word ): raise Exception(f"Parameters should not contain numbers: '{word}' contains a number" ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(_a ) + 1 ): _SCREAMING_SNAKE_CASE =word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: _SCREAMING_SNAKE_CASE =prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(_a : str ): _SCREAMING_SNAKE_CASE ='' while integer != 0: _SCREAMING_SNAKE_CASE =chr(ord('A' ) + integer % 10 ) + s integer //= 10 return s _SCREAMING_SNAKE_CASE =0 while True: _SCREAMING_SNAKE_CASE =word + '#' + int_to_alphabetic(_a ) if sword in info["reverse_short_word"]: continue else: _SCREAMING_SNAKE_CASE =sword break _SCREAMING_SNAKE_CASE =short_word _SCREAMING_SNAKE_CASE =word return short_word @staticmethod def A ( _a : Optional[Any] , _a : int ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =param_name.split('_' ) _SCREAMING_SNAKE_CASE =[TrialShortNamer.shortname_for_word(_a , _a ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name _SCREAMING_SNAKE_CASE =['', '_'] for separator in separators: _SCREAMING_SNAKE_CASE =separator.join(_a ) if shortname not in info["reverse_short_param"]: _SCREAMING_SNAKE_CASE =shortname _SCREAMING_SNAKE_CASE =param_name return shortname return param_name @staticmethod def A ( _a : Dict , _a : int ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =TrialShortNamer.shortname_for_key(_a , _a ) _SCREAMING_SNAKE_CASE =short_name _SCREAMING_SNAKE_CASE =param_name @classmethod def A ( cls : Optional[int] ) -> Tuple: '''simple docstring''' if cls.NAMING_INFO is not None: return _SCREAMING_SNAKE_CASE ={ 'short_word': {}, 'reverse_short_word': {}, 'short_param': {}, 'reverse_short_param': {}, } _SCREAMING_SNAKE_CASE =list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(_a , _a ) _SCREAMING_SNAKE_CASE =info @classmethod def A ( cls : List[Any] , _a : int ) -> int: '''simple docstring''' cls.build_naming_info() assert cls.PREFIX is not None _SCREAMING_SNAKE_CASE =[copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(f"You should provide a default value for the param name {k} with value {v}" ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue _SCREAMING_SNAKE_CASE =cls.NAMING_INFO['short_param'][k] if isinstance(_a , _a ): _SCREAMING_SNAKE_CASE =1 if v else 0 _SCREAMING_SNAKE_CASE ='' if isinstance(_a , (int, float) ) else '-' _SCREAMING_SNAKE_CASE =f"{key}{sep}{v}" name.append(_a ) return "_".join(_a ) @classmethod def A ( cls : Optional[Any] , _a : List[Any] ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =repr[len(cls.PREFIX ) + 1 :] if repr == "": _SCREAMING_SNAKE_CASE =[] else: _SCREAMING_SNAKE_CASE =repr.split('_' ) _SCREAMING_SNAKE_CASE ={} for value in values: if "-" in value: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =value.split('-' ) else: _SCREAMING_SNAKE_CASE =re.sub('[0-9.]' , '' , _a ) _SCREAMING_SNAKE_CASE =float(re.sub('[^0-9.]' , '' , _a ) ) _SCREAMING_SNAKE_CASE =cls.NAMING_INFO['reverse_short_param'][p_k] _SCREAMING_SNAKE_CASE =p_v for k in cls.DEFAULTS: if k not in parameters: _SCREAMING_SNAKE_CASE =cls.DEFAULTS[k] return parameters
47
1
'''simple docstring''' from __future__ import annotations lowerCamelCase : List[str] = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] def _lowerCAmelCase ( _UpperCamelCase : list[list[int]] , _UpperCamelCase : list[int] , _UpperCamelCase : list[int] , _UpperCamelCase : int , _UpperCamelCase : list[list[int]] , ) -> tuple[list[list[int]], list[list[int]]]: """simple docstring""" _SCREAMING_SNAKE_CASE =[ [0 for col in range(len(grid[0] ) )] for row in range(len(_UpperCamelCase ) ) ] # the reference grid _SCREAMING_SNAKE_CASE =1 _SCREAMING_SNAKE_CASE =[ [0 for col in range(len(grid[0] ) )] for row in range(len(_UpperCamelCase ) ) ] # the action grid _SCREAMING_SNAKE_CASE =init[0] _SCREAMING_SNAKE_CASE =init[1] _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =g + heuristic[x][y] # cost from starting cell to destination cell _SCREAMING_SNAKE_CASE =[[f, g, x, y]] _SCREAMING_SNAKE_CASE =False # flag that is set when search is complete _SCREAMING_SNAKE_CASE =False # flag set if we can't find expand while not found and not resign: if len(_UpperCamelCase ) == 0: raise ValueError('Algorithm is unable to find solution' ) else: # to choose the least costliest action so as to move closer to the goal cell.sort() cell.reverse() _SCREAMING_SNAKE_CASE =cell.pop() _SCREAMING_SNAKE_CASE =next_cell[2] _SCREAMING_SNAKE_CASE =next_cell[3] _SCREAMING_SNAKE_CASE =next_cell[1] if x == goal[0] and y == goal[1]: _SCREAMING_SNAKE_CASE =True else: for i in range(len(_UpperCamelCase ) ): # to try out different valid actions _SCREAMING_SNAKE_CASE =x + DIRECTIONS[i][0] _SCREAMING_SNAKE_CASE =y + DIRECTIONS[i][1] if xa >= 0 and xa < len(_UpperCamelCase ) and ya >= 0 and ya < len(grid[0] ): if closed[xa][ya] == 0 and grid[xa][ya] == 0: _SCREAMING_SNAKE_CASE =g + cost _SCREAMING_SNAKE_CASE =ga + heuristic[xa][ya] cell.append([fa, ga, xa, ya] ) _SCREAMING_SNAKE_CASE =1 _SCREAMING_SNAKE_CASE =i _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =goal[0] _SCREAMING_SNAKE_CASE =goal[1] invpath.append([x, y] ) # we get the reverse path from here while x != init[0] or y != init[1]: _SCREAMING_SNAKE_CASE =x - DIRECTIONS[action[x][y]][0] _SCREAMING_SNAKE_CASE =y - DIRECTIONS[action[x][y]][1] _SCREAMING_SNAKE_CASE =xa _SCREAMING_SNAKE_CASE =ya invpath.append([x, y] ) _SCREAMING_SNAKE_CASE =[] for i in range(len(_UpperCamelCase ) ): path.append(invpath[len(_UpperCamelCase ) - 1 - i] ) return path, action if __name__ == "__main__": lowerCamelCase : Optional[Any] = [ [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0], ] lowerCamelCase : Any = [0, 0] # all coordinates are given in format [y,x] lowerCamelCase : Union[str, Any] = [len(grid) - 1, len(grid[0]) - 1] lowerCamelCase : List[Any] = 1 # the cost map which pushes the path closer to the goal lowerCamelCase : Any = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): lowerCamelCase : Optional[Any] = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: # added extra penalty in the heuristic map lowerCamelCase : List[Any] = 9_9 lowerCamelCase , lowerCamelCase : str = search(grid, init, goal, cost, heuristic) print("ACTION MAP") for i in range(len(action)): print(action[i]) for i in range(len(path)): print(path[i])
47
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version lowerCamelCase : Optional[int] = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt") @dataclass class A__ : A__ = field( default='cifar10' , metadata={'help': 'Name of a dataset from the datasets package'} ) A__ = field( default=A__ , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) A__ = field( default=A__ , metadata={'help': 'The column name of the images in the files.'} ) A__ = field(default=A__ , metadata={'help': 'A folder containing the training data.'} ) A__ = field(default=A__ , metadata={'help': 'A folder containing the validation data.'} ) A__ = field( default=0.15 , metadata={'help': 'Percent to split off of train for validation.'} ) A__ = field( default=A__ , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) A__ = field( default=A__ , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of evaluation examples to this ' 'value if set.' ) } , ) def A ( self : Union[str, Any] ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE ={} if self.train_dir is not None: _SCREAMING_SNAKE_CASE =self.train_dir if self.validation_dir is not None: _SCREAMING_SNAKE_CASE =self.validation_dir _SCREAMING_SNAKE_CASE =data_files if data_files else None @dataclass class A__ : A__ = field( default=A__ , metadata={ 'help': ( 'The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.' ) } , ) A__ = field( default=A__ , metadata={'help': 'Pretrained config name or path if not the same as model_name_or_path'} ) A__ = field( default=A__ , metadata={ 'help': ( 'Override some existing default config settings when a model is trained from scratch. Example: ' 'n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index' ) } , ) A__ = field( default=A__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from s3'} ) A__ = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) A__ = field(default=A__ , metadata={'help': 'Name or path of preprocessor config.'} ) A__ = field( default=A__ , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) A__ = field( default=0.75 , metadata={'help': 'The ratio of the number of masked tokens in the input sequence.'} ) A__ = field( default=A__ , metadata={'help': 'Whether or not to train with normalized pixel values as target.'} ) @dataclass class A__ ( A__ ): A__ = field( default=1E-3 , metadata={'help': 'Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'} ) def _lowerCAmelCase ( _UpperCamelCase : int ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE =torch.stack([example['pixel_values'] for example in examples] ) return {"pixel_values": pixel_values} def _lowerCAmelCase ( ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE =HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) 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. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('run_mae' , _UpperCamelCase , _UpperCamelCase ) # 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 )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _SCREAMING_SNAKE_CASE =training_args.get_process_log_level() logger.setLevel(_UpperCamelCase ) transformers.utils.logging.set_verbosity(_UpperCamelCase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # 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}" ) logger.info(f"Training/evaluation parameters {training_args}" ) # Detecting last checkpoint. _SCREAMING_SNAKE_CASE =None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _SCREAMING_SNAKE_CASE =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 and training_args.resume_from_checkpoint is 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.' ) # Initialize our dataset. _SCREAMING_SNAKE_CASE =load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. _SCREAMING_SNAKE_CASE =None if 'validation' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , _UpperCamelCase ) and data_args.train_val_split > 0.0: _SCREAMING_SNAKE_CASE =ds['train'].train_test_split(data_args.train_val_split ) _SCREAMING_SNAKE_CASE =split['train'] _SCREAMING_SNAKE_CASE =split['test'] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _SCREAMING_SNAKE_CASE ={ 'cache_dir': model_args.cache_dir, 'revision': model_args.model_revision, 'use_auth_token': True if model_args.use_auth_token else None, } if model_args.config_name: _SCREAMING_SNAKE_CASE =ViTMAEConfig.from_pretrained(model_args.config_name , **_UpperCamelCase ) elif model_args.model_name_or_path: _SCREAMING_SNAKE_CASE =ViTMAEConfig.from_pretrained(model_args.model_name_or_path , **_UpperCamelCase ) else: _SCREAMING_SNAKE_CASE =ViTMAEConfig() logger.warning('You are instantiating a new config instance from scratch.' ) if model_args.config_overrides is not None: logger.info(f"Overriding config: {model_args.config_overrides}" ) config.update_from_string(model_args.config_overrides ) logger.info(f"New config: {config}" ) # adapt config config.update( { 'mask_ratio': model_args.mask_ratio, 'norm_pix_loss': model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: _SCREAMING_SNAKE_CASE =ViTImageProcessor.from_pretrained(model_args.image_processor_name , **_UpperCamelCase ) elif model_args.model_name_or_path: _SCREAMING_SNAKE_CASE =ViTImageProcessor.from_pretrained(model_args.model_name_or_path , **_UpperCamelCase ) else: _SCREAMING_SNAKE_CASE =ViTImageProcessor() # create model if model_args.model_name_or_path: _SCREAMING_SNAKE_CASE =ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=_UpperCamelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('Training new model from scratch' ) _SCREAMING_SNAKE_CASE =ViTMAEForPreTraining(_UpperCamelCase ) if training_args.do_train: _SCREAMING_SNAKE_CASE =ds['train'].column_names else: _SCREAMING_SNAKE_CASE =ds['validation'].column_names if data_args.image_column_name is not None: _SCREAMING_SNAKE_CASE =data_args.image_column_name elif "image" in column_names: _SCREAMING_SNAKE_CASE ='image' elif "img" in column_names: _SCREAMING_SNAKE_CASE ='img' else: _SCREAMING_SNAKE_CASE =column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: _SCREAMING_SNAKE_CASE =image_processor.size['shortest_edge'] else: _SCREAMING_SNAKE_CASE =(image_processor.size['height'], image_processor.size['width']) _SCREAMING_SNAKE_CASE =Compose( [ Lambda(lambda _UpperCamelCase : img.convert('RGB' ) if img.mode != "RGB" else img ), RandomResizedCrop(_UpperCamelCase , scale=(0.2, 1.0) , interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) def preprocess_images(_UpperCamelCase : Dict ): _SCREAMING_SNAKE_CASE =[transforms(_UpperCamelCase ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError('--do_train requires a train dataset' ) if data_args.max_train_samples is not None: _SCREAMING_SNAKE_CASE =ds['train'].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(_UpperCamelCase ) if training_args.do_eval: if "validation" not in ds: raise ValueError('--do_eval requires a validation dataset' ) if data_args.max_eval_samples is not None: _SCREAMING_SNAKE_CASE =( ds['validation'].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(_UpperCamelCase ) # Compute absolute learning rate _SCREAMING_SNAKE_CASE =( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: _SCREAMING_SNAKE_CASE =training_args.base_learning_rate * total_train_batch_size / 2_56 # Initialize our trainer _SCREAMING_SNAKE_CASE =Trainer( model=_UpperCamelCase , args=_UpperCamelCase , train_dataset=ds['train'] if training_args.do_train else None , eval_dataset=ds['validation'] if training_args.do_eval else None , tokenizer=_UpperCamelCase , data_collator=_UpperCamelCase , ) # Training if training_args.do_train: _SCREAMING_SNAKE_CASE =None if training_args.resume_from_checkpoint is not None: _SCREAMING_SNAKE_CASE =training_args.resume_from_checkpoint elif last_checkpoint is not None: _SCREAMING_SNAKE_CASE =last_checkpoint _SCREAMING_SNAKE_CASE =trainer.train(resume_from_checkpoint=_UpperCamelCase ) trainer.save_model() trainer.log_metrics('train' , train_result.metrics ) trainer.save_metrics('train' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _SCREAMING_SNAKE_CASE =trainer.evaluate() trainer.log_metrics('eval' , _UpperCamelCase ) trainer.save_metrics('eval' , _UpperCamelCase ) # Write model card and (optionally) push to hub _SCREAMING_SNAKE_CASE ={ 'tasks': 'masked-auto-encoding', 'dataset': data_args.dataset_name, 'tags': ['masked-auto-encoding'], } if training_args.push_to_hub: trainer.push_to_hub(**_UpperCamelCase ) else: trainer.create_model_card(**_UpperCamelCase ) def _lowerCAmelCase ( _UpperCamelCase : List[str] ) -> Optional[int]: """simple docstring""" main() if __name__ == "__main__": main()
47
1
'''simple docstring''' import os from pathlib import Path def _lowerCAmelCase ( ) -> Tuple: """simple docstring""" from torch.utils.cpp_extension import load _SCREAMING_SNAKE_CASE =Path(_UpperCamelCase ).resolve().parent.parent.parent / 'kernels' / 'deformable_detr' _SCREAMING_SNAKE_CASE =[ root / filename for filename in [ 'vision.cpp', os.path.join('cpu' , 'ms_deform_attn_cpu.cpp' ), os.path.join('cuda' , 'ms_deform_attn_cuda.cu' ), ] ] load( 'MultiScaleDeformableAttention' , _UpperCamelCase , with_cuda=_UpperCamelCase , extra_include_paths=[str(_UpperCamelCase )] , extra_cflags=['-DWITH_CUDA=1'] , extra_cuda_cflags=[ '-DCUDA_HAS_FP16=1', '-D__CUDA_NO_HALF_OPERATORS__', '-D__CUDA_NO_HALF_CONVERSIONS__', '-D__CUDA_NO_HALF2_OPERATORS__', ] , ) import MultiScaleDeformableAttention as MSDA return MSDA
47
'''simple docstring''' from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class A__ ( A__ , A__ ): @register_to_config def __init__( self : Dict , _a : int = 768 , ) -> Union[str, Any]: '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =nn.Parameter(torch.zeros(1 , _a ) ) _SCREAMING_SNAKE_CASE =nn.Parameter(torch.ones(1 , _a ) ) def A ( self : Tuple , _a : Optional[Union[str, torch.device]] = None , _a : Optional[torch.dtype] = None , ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =nn.Parameter(self.mean.to(_a ).to(_a ) ) _SCREAMING_SNAKE_CASE =nn.Parameter(self.std.to(_a ).to(_a ) ) return self def A ( self : Tuple , _a : str ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =(embeds - self.mean) * 1.0 / self.std return embeds def A ( self : List[str] , _a : Optional[Any] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =(embeds * self.std) + self.mean return embeds
47
1
'''simple docstring''' lowerCamelCase : Any = "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" lowerCamelCase : int = [{"type": "code", "content": INSTALL_CONTENT}] lowerCamelCase : str = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
47
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def _lowerCAmelCase ( _UpperCamelCase : Optional[int] ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =botoa.client('iam' ) _SCREAMING_SNAKE_CASE ={ 'Version': '2012-10-17', 'Statement': [ {'Effect': 'Allow', 'Principal': {'Service': 'sagemaker.amazonaws.com'}, 'Action': 'sts:AssumeRole'} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=_UpperCamelCase , AssumeRolePolicyDocument=json.dumps(_UpperCamelCase , indent=2 ) ) _SCREAMING_SNAKE_CASE ={ 'Version': '2012-10-17', 'Statement': [ { 'Effect': 'Allow', 'Action': [ 'sagemaker:*', 'ecr:GetDownloadUrlForLayer', 'ecr:BatchGetImage', 'ecr:BatchCheckLayerAvailability', 'ecr:GetAuthorizationToken', 'cloudwatch:PutMetricData', 'cloudwatch:GetMetricData', 'cloudwatch:GetMetricStatistics', 'cloudwatch:ListMetrics', 'logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:DescribeLogStreams', 'logs:PutLogEvents', 'logs:GetLogEvents', 's3:CreateBucket', 's3:ListBucket', 's3:GetBucketLocation', 's3:GetObject', 's3:PutObject', ], 'Resource': '*', } ], } # attach policy to role iam_client.put_role_policy( RoleName=_UpperCamelCase , PolicyName=f"{role_name}_policy_permission" , PolicyDocument=json.dumps(_UpperCamelCase , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(f"role {role_name} already exists. Using existing one" ) def _lowerCAmelCase ( _UpperCamelCase : List[str] ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =botoa.client('iam' ) return iam_client.get_role(RoleName=_UpperCamelCase )["Role"]["Arn"] def _lowerCAmelCase ( ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =_ask_options( 'How do you want to authorize?' , ['AWS Profile', 'Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) '] , _UpperCamelCase , ) _SCREAMING_SNAKE_CASE =None if credentials_configuration == 0: _SCREAMING_SNAKE_CASE =_ask_field('Enter your AWS Profile name: [default] ' , default='default' ) _SCREAMING_SNAKE_CASE =aws_profile else: print( 'Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,' '`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`' ) _SCREAMING_SNAKE_CASE =_ask_field('AWS Access Key ID: ' ) _SCREAMING_SNAKE_CASE =aws_access_key_id _SCREAMING_SNAKE_CASE =_ask_field('AWS Secret Access Key: ' ) _SCREAMING_SNAKE_CASE =aws_secret_access_key _SCREAMING_SNAKE_CASE =_ask_field('Enter your AWS Region: [us-east-1]' , default='us-east-1' ) _SCREAMING_SNAKE_CASE =aws_region _SCREAMING_SNAKE_CASE =_ask_options( 'Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?' , ['Provide IAM Role name', 'Create new IAM role using credentials'] , _UpperCamelCase , ) if role_management == 0: _SCREAMING_SNAKE_CASE =_ask_field('Enter your IAM role name: ' ) else: _SCREAMING_SNAKE_CASE ='accelerate_sagemaker_execution_role' print(f"Accelerate will create an iam role \"{iam_role_name}\" using the provided credentials" ) _create_iam_role_for_sagemaker(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to use custom Docker image? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE =None if is_custom_docker_image: _SCREAMING_SNAKE_CASE =_ask_field('Enter your Docker image: ' , lambda _UpperCamelCase : str(_UpperCamelCase ).lower() ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to provide SageMaker input channels with data locations? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE =None if is_sagemaker_inputs_enabled: _SCREAMING_SNAKE_CASE =_ask_field( 'Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): ' , lambda _UpperCamelCase : str(_UpperCamelCase ).lower() , ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to enable SageMaker metrics? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE =None if is_sagemaker_metrics_enabled: _SCREAMING_SNAKE_CASE =_ask_field( 'Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): ' , lambda _UpperCamelCase : str(_UpperCamelCase ).lower() , ) _SCREAMING_SNAKE_CASE =_ask_options( 'What is the distributed mode?' , ['No distributed training', 'Data parallelism'] , _convert_sagemaker_distributed_mode , ) _SCREAMING_SNAKE_CASE ={} _SCREAMING_SNAKE_CASE =_ask_field( 'Do you wish to optimize your script with torch dynamo?[yes/NO]:' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) if use_dynamo: _SCREAMING_SNAKE_CASE ='dynamo_' _SCREAMING_SNAKE_CASE =_ask_options( 'Which dynamo backend would you like to use?' , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to customize the defaults sent to torch.compile? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) if use_custom_options: _SCREAMING_SNAKE_CASE =_ask_options( 'Which mode do you want to use?' , _UpperCamelCase , lambda _UpperCamelCase : TORCH_DYNAMO_MODES[int(_UpperCamelCase )] , default='default' , ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to enable dynamic shape tracing? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE ='Which EC2 instance type you want to use for your training?' if distributed_type != SageMakerDistributedType.NO: _SCREAMING_SNAKE_CASE =_ask_options( _UpperCamelCase , _UpperCamelCase , lambda _UpperCamelCase : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(_UpperCamelCase )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" _SCREAMING_SNAKE_CASE =_ask_field(_UpperCamelCase , lambda _UpperCamelCase : str(_UpperCamelCase ).lower() , default='ml.p3.2xlarge' ) _SCREAMING_SNAKE_CASE =1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): _SCREAMING_SNAKE_CASE =_ask_field( 'How many machines do you want use? [1]: ' , _UpperCamelCase , default=1 , ) _SCREAMING_SNAKE_CASE =_ask_options( 'Do you wish to use FP16 or BF16 (mixed precision)?' , ['no', 'fp16', 'bf16', 'fp8'] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( 'Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.' ) return SageMakerConfig( image_uri=_UpperCamelCase , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=_UpperCamelCase , use_cpu=_UpperCamelCase , dynamo_config=_UpperCamelCase , eca_instance_type=_UpperCamelCase , profile=_UpperCamelCase , region=_UpperCamelCase , iam_role_name=_UpperCamelCase , mixed_precision=_UpperCamelCase , num_machines=_UpperCamelCase , sagemaker_inputs_file=_UpperCamelCase , sagemaker_metrics_file=_UpperCamelCase , )
47
1
'''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 A__ : def __init__( self : str , _a : List[Any] , _a : Optional[Any]=13 , _a : Tuple=7 , _a : int=True , _a : Tuple=True , _a : Any=False , _a : Tuple=True , _a : Optional[int]=99 , _a : List[Any]=32 , _a : Dict=5 , _a : List[str]=4 , _a : str=37 , _a : Dict="gelu" , _a : Optional[int]=0.1 , _a : int=0.1 , _a : List[Any]=512 , _a : int=16 , _a : List[str]=2 , _a : Union[str, Any]=0.02 , _a : Any=3 , _a : str=4 , _a : str=None , ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =parent _SCREAMING_SNAKE_CASE =batch_size _SCREAMING_SNAKE_CASE =seq_length _SCREAMING_SNAKE_CASE =is_training _SCREAMING_SNAKE_CASE =use_input_mask _SCREAMING_SNAKE_CASE =use_token_type_ids _SCREAMING_SNAKE_CASE =use_labels _SCREAMING_SNAKE_CASE =vocab_size _SCREAMING_SNAKE_CASE =hidden_size _SCREAMING_SNAKE_CASE =num_hidden_layers _SCREAMING_SNAKE_CASE =num_attention_heads _SCREAMING_SNAKE_CASE =intermediate_size _SCREAMING_SNAKE_CASE =hidden_act _SCREAMING_SNAKE_CASE =hidden_dropout_prob _SCREAMING_SNAKE_CASE =attention_probs_dropout_prob _SCREAMING_SNAKE_CASE =max_position_embeddings _SCREAMING_SNAKE_CASE =type_vocab_size _SCREAMING_SNAKE_CASE =type_sequence_label_size _SCREAMING_SNAKE_CASE =initializer_range _SCREAMING_SNAKE_CASE =num_labels _SCREAMING_SNAKE_CASE =num_choices _SCREAMING_SNAKE_CASE =scope def A ( self : Optional[Any] ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE =None if self.use_input_mask: _SCREAMING_SNAKE_CASE =random_attention_mask([self.batch_size, self.seq_length] ) _SCREAMING_SNAKE_CASE =None if self.use_token_type_ids: _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =None if self.use_labels: _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] , self.num_choices ) _SCREAMING_SNAKE_CASE =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def A ( self : Optional[int] ) -> Any: '''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=_a , initializer_range=self.initializer_range , ) def A ( self : Tuple , _a : str , _a : str , _a : Optional[int] , _a : List[str] , _a : Dict , _a : Union[str, Any] , _a : int ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =BioGptModel(config=_a ) model.to(_a ) model.eval() _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a ) _SCREAMING_SNAKE_CASE =model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def A ( self : Union[str, Any] , _a : List[str] , _a : Optional[Any] , _a : str , _a : Optional[int] , _a : Optional[Any] , _a : Dict , _a : Optional[int] , _a : List[Any] , _a : str , ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =BioGptForCausalLM(config=_a ) model.to(_a ) model.eval() _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def A ( self : int , _a : Dict , _a : Tuple , _a : List[str] , _a : str , _a : Optional[int] , *_a : str ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =BioGptModel(config=_a ) model.to(_a ) model.eval() # create attention mask _SCREAMING_SNAKE_CASE =torch.ones(input_ids.shape , dtype=torch.long , device=_a ) _SCREAMING_SNAKE_CASE =self.seq_length // 2 _SCREAMING_SNAKE_CASE =0 # first forward pass _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a ).to_tuple() # create hypothetical next token and extent to next_input_ids _SCREAMING_SNAKE_CASE =ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids _SCREAMING_SNAKE_CASE =ids_tensor((1,) , _a ).item() + 1 _SCREAMING_SNAKE_CASE =ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) _SCREAMING_SNAKE_CASE =random_other_next_tokens # append to next input_ids and attn_mask _SCREAMING_SNAKE_CASE =torch.cat([input_ids, next_tokens] , dim=-1 ) _SCREAMING_SNAKE_CASE =torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=_a )] , dim=1 , ) # get two different outputs _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a )['last_hidden_state'] _SCREAMING_SNAKE_CASE =model(_a , past_key_values=_a , attention_mask=_a )['last_hidden_state'] # select random slice _SCREAMING_SNAKE_CASE =ids_tensor((1,) , output_from_past.shape[-1] ).item() _SCREAMING_SNAKE_CASE =output_from_no_past[:, -1, random_slice_idx].detach() _SCREAMING_SNAKE_CASE =output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_a , _a , atol=1e-3 ) ) def A ( self : Any , _a : Dict , _a : List[Any] , _a : str , _a : List[str] , _a : Any , *_a : List[str] ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =BioGptModel(config=_a ).to(_a ).eval() _SCREAMING_SNAKE_CASE =torch.ones(input_ids.shape , dtype=torch.long , device=_a ) # first forward pass _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a , use_cache=_a ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids _SCREAMING_SNAKE_CASE =ids_tensor((self.batch_size, 3) , config.vocab_size ) _SCREAMING_SNAKE_CASE =ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and _SCREAMING_SNAKE_CASE =torch.cat([input_ids, next_tokens] , dim=-1 ) _SCREAMING_SNAKE_CASE =torch.cat([attention_mask, next_attn_mask] , dim=-1 ) _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a )['last_hidden_state'] _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a , past_key_values=_a )[ 'last_hidden_state' ] # select random slice _SCREAMING_SNAKE_CASE =ids_tensor((1,) , output_from_past.shape[-1] ).item() _SCREAMING_SNAKE_CASE =output_from_no_past[:, -3:, random_slice_idx].detach() _SCREAMING_SNAKE_CASE =output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_a , _a , atol=1e-3 ) ) def A ( self : Optional[int] , _a : Dict , _a : Any , _a : List[Any] , _a : Tuple , _a : Dict , *_a : Optional[Any] , _a : int=False ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =BioGptForCausalLM(_a ) model.to(_a ) if gradient_checkpointing: model.gradient_checkpointing_enable() _SCREAMING_SNAKE_CASE =model(_a , labels=_a ) 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 A ( self : int , _a : Dict , *_a : str ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =BioGptModel(_a ) _SCREAMING_SNAKE_CASE =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.0_01 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def A ( self : Optional[int] , _a : Dict , _a : int , _a : Tuple , _a : Union[str, Any] , _a : Optional[int] , *_a : int ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.num_labels _SCREAMING_SNAKE_CASE =BioGptForTokenClassification(_a ) model.to(_a ) model.eval() _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a , token_type_ids=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def A ( self : int ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() ( ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ) =config_and_inputs _SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class A__ ( A__ , A__ , A__ , unittest.TestCase ): A__ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) A__ = (BioGptForCausalLM,) if is_torch_available() else () A__ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) A__ = False def A ( self : Optional[int] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =BioGptModelTester(self ) _SCREAMING_SNAKE_CASE =ConfigTester(self , config_class=_a , hidden_size=37 ) def A ( self : str ) -> Tuple: '''simple docstring''' self.config_tester.run_common_tests() def A ( self : Optional[int] ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def A ( self : Tuple ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _SCREAMING_SNAKE_CASE =type self.model_tester.create_and_check_model(*_a ) def A ( self : Dict ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*_a ) def A ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*_a , gradient_checkpointing=_a ) def A ( self : Any ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*_a ) def A ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*_a ) def A ( self : Any ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*_a ) @slow def A ( self : List[str] ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(_a ) _SCREAMING_SNAKE_CASE =BioGptTokenizer.from_pretrained('microsoft/biogpt' ) _SCREAMING_SNAKE_CASE ='left' # Define PAD Token = EOS Token = 50256 _SCREAMING_SNAKE_CASE =tokenizer.eos_token _SCREAMING_SNAKE_CASE =model.config.eos_token_id # use different length sentences to test batching _SCREAMING_SNAKE_CASE =[ 'Hello, my dog is a little', 'Today, I', ] _SCREAMING_SNAKE_CASE =tokenizer(_a , return_tensors='pt' , padding=_a ) _SCREAMING_SNAKE_CASE =inputs['input_ids'].to(_a ) _SCREAMING_SNAKE_CASE =model.generate( input_ids=_a , attention_mask=inputs['attention_mask'].to(_a ) , ) _SCREAMING_SNAKE_CASE =tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(_a ) _SCREAMING_SNAKE_CASE =model.generate(input_ids=_a ) _SCREAMING_SNAKE_CASE =inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() _SCREAMING_SNAKE_CASE =tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(_a ) _SCREAMING_SNAKE_CASE =model.generate(input_ids=_a , max_length=model.config.max_length - num_paddings ) _SCREAMING_SNAKE_CASE =tokenizer.batch_decode(_a , skip_special_tokens=_a ) _SCREAMING_SNAKE_CASE =tokenizer.decode(output_non_padded[0] , skip_special_tokens=_a ) _SCREAMING_SNAKE_CASE =tokenizer.decode(output_padded[0] , skip_special_tokens=_a ) _SCREAMING_SNAKE_CASE =[ '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(_a , _a ) self.assertListEqual(_a , [non_padded_sentence, padded_sentence] ) @slow def A ( self : str ) -> Any: '''simple docstring''' for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _SCREAMING_SNAKE_CASE =BioGptModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def A ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE =3 _SCREAMING_SNAKE_CASE =input_dict['input_ids'] _SCREAMING_SNAKE_CASE =input_ids.ne(1 ).to(_a ) _SCREAMING_SNAKE_CASE =ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) _SCREAMING_SNAKE_CASE =BioGptForSequenceClassification(_a ) model.to(_a ) model.eval() _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a , labels=_a ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def A ( self : Tuple ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE =3 _SCREAMING_SNAKE_CASE ='multi_label_classification' _SCREAMING_SNAKE_CASE =input_dict['input_ids'] _SCREAMING_SNAKE_CASE =input_ids.ne(1 ).to(_a ) _SCREAMING_SNAKE_CASE =ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) _SCREAMING_SNAKE_CASE =BioGptForSequenceClassification(_a ) model.to(_a ) model.eval() _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a , labels=_a ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class A__ ( unittest.TestCase ): @slow def A ( self : Any ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) _SCREAMING_SNAKE_CASE =torch.tensor([[2, 4805, 9, 656, 21]] ) _SCREAMING_SNAKE_CASE =model(_a )[0] _SCREAMING_SNAKE_CASE =4_2384 _SCREAMING_SNAKE_CASE =torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , _a ) _SCREAMING_SNAKE_CASE =torch.tensor( [[[-9.52_36, -9.89_18, 10.45_57], [-11.04_69, -9.64_23, 8.10_22], [-8.86_64, -7.88_26, 5.53_25]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1e-4 ) ) @slow def A ( self : Any ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =BioGptTokenizer.from_pretrained('microsoft/biogpt' ) _SCREAMING_SNAKE_CASE =BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(_a ) torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE =tokenizer('COVID-19 is' , return_tensors='pt' ).to(_a ) _SCREAMING_SNAKE_CASE =model.generate( **_a , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=_a , ) _SCREAMING_SNAKE_CASE =tokenizer.decode(output_ids[0] , skip_special_tokens=_a ) _SCREAMING_SNAKE_CASE =( '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(_a , _a )
47
'''simple docstring''' class A__ : def __init__( self : Union[str, Any] , _a : int ) -> None: '''simple docstring''' _SCREAMING_SNAKE_CASE =size _SCREAMING_SNAKE_CASE =[0] * size _SCREAMING_SNAKE_CASE =[0] * size @staticmethod def A ( _a : int ) -> int: '''simple docstring''' return index | (index + 1) @staticmethod def A ( _a : int ) -> int: '''simple docstring''' return (index & (index + 1)) - 1 def A ( self : Tuple , _a : int , _a : int ) -> None: '''simple docstring''' _SCREAMING_SNAKE_CASE =value while index < self.size: _SCREAMING_SNAKE_CASE =self.get_prev(_a ) + 1 if current_left_border == index: _SCREAMING_SNAKE_CASE =value else: _SCREAMING_SNAKE_CASE =max(_a , _a , _a ) _SCREAMING_SNAKE_CASE =self.get_next(_a ) def A ( self : int , _a : int , _a : int ) -> int: '''simple docstring''' right -= 1 # Because of right is exclusive _SCREAMING_SNAKE_CASE =0 while left <= right: _SCREAMING_SNAKE_CASE =self.get_prev(_a ) if left <= current_left: _SCREAMING_SNAKE_CASE =max(_a , self.tree[right] ) _SCREAMING_SNAKE_CASE =current_left else: _SCREAMING_SNAKE_CASE =max(_a , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
47
1
'''simple docstring''' lowerCamelCase : Optional[Any] = 2_5_6 # Modulus to hash a string lowerCamelCase : int = 1_0_0_0_0_0_3 def _lowerCAmelCase ( _UpperCamelCase : str , _UpperCamelCase : str ) -> bool: """simple docstring""" _SCREAMING_SNAKE_CASE =len(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =len(_UpperCamelCase ) if p_len > t_len: return False _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =1 # Calculating the hash of pattern and substring of text for i in range(_UpperCamelCase ): _SCREAMING_SNAKE_CASE =(ord(pattern[i] ) + p_hash * alphabet_size) % modulus _SCREAMING_SNAKE_CASE =(ord(text[i] ) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue _SCREAMING_SNAKE_CASE =(modulus_power * alphabet_size) % modulus for i in range(0 , t_len - p_len + 1 ): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash _SCREAMING_SNAKE_CASE =( (text_hash - ord(text[i] ) * modulus_power) * alphabet_size + ord(text[i + p_len] ) ) % modulus return False def _lowerCAmelCase ( ) -> None: """simple docstring""" _SCREAMING_SNAKE_CASE ='abc1abc12' _SCREAMING_SNAKE_CASE ='alskfjaldsabc1abc1abc12k23adsfabcabc' _SCREAMING_SNAKE_CASE ='alskfjaldsk23adsfabcabc' assert rabin_karp(_UpperCamelCase , _UpperCamelCase ) and not rabin_karp(_UpperCamelCase , _UpperCamelCase ) # Test 2) _SCREAMING_SNAKE_CASE ='ABABX' _SCREAMING_SNAKE_CASE ='ABABZABABYABABX' assert rabin_karp(_UpperCamelCase , _UpperCamelCase ) # Test 3) _SCREAMING_SNAKE_CASE ='AAAB' _SCREAMING_SNAKE_CASE ='ABAAAAAB' assert rabin_karp(_UpperCamelCase , _UpperCamelCase ) # Test 4) _SCREAMING_SNAKE_CASE ='abcdabcy' _SCREAMING_SNAKE_CASE ='abcxabcdabxabcdabcdabcy' assert rabin_karp(_UpperCamelCase , _UpperCamelCase ) # Test 5) _SCREAMING_SNAKE_CASE ='Lü' _SCREAMING_SNAKE_CASE ='Lüsai' assert rabin_karp(_UpperCamelCase , _UpperCamelCase ) _SCREAMING_SNAKE_CASE ='Lue' assert not rabin_karp(_UpperCamelCase , _UpperCamelCase ) print('Success.' ) if __name__ == "__main__": test_rabin_karp()
47
'''simple docstring''' from __future__ import annotations from random import random from typing import Generic, TypeVar lowerCamelCase : Union[str, Any] = TypeVar("KT") lowerCamelCase : Dict = TypeVar("VT") class A__ ( Generic[KT, VT] ): def __init__( self : str , _a : KT | str = "root" , _a : VT | None = None ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =key _SCREAMING_SNAKE_CASE =value _SCREAMING_SNAKE_CASE =[] def __repr__( self : Union[str, Any] ) -> str: '''simple docstring''' return f"Node({self.key}: {self.value})" @property def A ( self : int ) -> int: '''simple docstring''' return len(self.forward ) class A__ ( Generic[KT, VT] ): def __init__( self : Optional[Any] , _a : float = 0.5 , _a : int = 16 ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =Node[KT, VT]() _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =p _SCREAMING_SNAKE_CASE =max_level def __str__( self : Tuple ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =list(self ) if len(_a ) == 0: return f"SkipList(level={self.level})" _SCREAMING_SNAKE_CASE =max((len(str(_a ) ) for item in items) , default=4 ) _SCREAMING_SNAKE_CASE =max(_a , 4 ) + 4 _SCREAMING_SNAKE_CASE =self.head _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =node.forward.copy() lines.append(f"[{node.key}]".ljust(_a , '-' ) + '* ' * len(_a ) ) lines.append(' ' * label_size + '| ' * len(_a ) ) while len(node.forward ) != 0: _SCREAMING_SNAKE_CASE =node.forward[0] lines.append( f"[{node.key}]".ljust(_a , '-' ) + ' '.join(str(n.key ) if n.key == node.key else '|' for n in forwards ) ) lines.append(' ' * label_size + '| ' * len(_a ) ) _SCREAMING_SNAKE_CASE =node.forward lines.append('None'.ljust(_a ) + '* ' * len(_a ) ) return f"SkipList(level={self.level})\n" + "\n".join(_a ) def __iter__( self : Dict ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.head while len(node.forward ) != 0: yield node.forward[0].key _SCREAMING_SNAKE_CASE =node.forward[0] def A ( self : List[Any] ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =1 while random() < self.p and level < self.max_level: level += 1 return level def A ( self : Any , _a : Any ) -> tuple[Node[KT, VT] | None, list[Node[KT, VT]]]: '''simple docstring''' _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =self.head for i in reversed(range(self.level ) ): # i < node.level - When node level is lesser than `i` decrement `i`. # node.forward[i].key < key - Jumping to node with key value higher # or equal to searched key would result # in skipping searched key. while i < node.level and node.forward[i].key < key: _SCREAMING_SNAKE_CASE =node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(_a ) update_vector.reverse() # Note that we were inserting values in reverse order. # len(node.forward) != 0 - If current node doesn't contain any further # references then searched key is not present. # node.forward[0].key == key - Next node key should be equal to search key # if key is present. if len(node.forward ) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def A ( self : Union[str, Any] , _a : KT ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self._locate_node(_a ) if node is not None: for i, update_node in enumerate(_a ): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: _SCREAMING_SNAKE_CASE =node.forward[i] else: _SCREAMING_SNAKE_CASE =update_node.forward[:i] def A ( self : Optional[Any] , _a : KT , _a : VT ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self._locate_node(_a ) if node is not None: _SCREAMING_SNAKE_CASE =value else: _SCREAMING_SNAKE_CASE =self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for _ in range(self.level - 1 , _a ): update_vector.append(self.head ) _SCREAMING_SNAKE_CASE =level _SCREAMING_SNAKE_CASE =Node(_a , _a ) for i, update_node in enumerate(update_vector[:level] ): # Change references to pass through new node. if update_node.level > i: new_node.forward.append(update_node.forward[i] ) if update_node.level < i + 1: update_node.forward.append(_a ) else: _SCREAMING_SNAKE_CASE =new_node def A ( self : List[str] , _a : VT ) -> VT | None: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self._locate_node(_a ) if node is not None: return node.value return None def _lowerCAmelCase ( ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key1' , 3 ) skip_list.insert('Key2' , 12 ) skip_list.insert('Key3' , 41 ) skip_list.insert('Key4' , -19 ) _SCREAMING_SNAKE_CASE =skip_list.head _SCREAMING_SNAKE_CASE ={} while node.level != 0: _SCREAMING_SNAKE_CASE =node.forward[0] _SCREAMING_SNAKE_CASE =node.value assert len(_UpperCamelCase ) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def _lowerCAmelCase ( ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key1' , 10 ) skip_list.insert('Key1' , 12 ) skip_list.insert('Key5' , 7 ) skip_list.insert('Key7' , 10 ) skip_list.insert('Key10' , 5 ) skip_list.insert('Key7' , 7 ) skip_list.insert('Key5' , 5 ) skip_list.insert('Key10' , 10 ) _SCREAMING_SNAKE_CASE =skip_list.head _SCREAMING_SNAKE_CASE ={} while node.level != 0: _SCREAMING_SNAKE_CASE =node.forward[0] _SCREAMING_SNAKE_CASE =node.value if len(_UpperCamelCase ) != 4: print() assert len(_UpperCamelCase ) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def _lowerCAmelCase ( ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() assert skip_list.find('Some key' ) is None def _lowerCAmelCase ( ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key2' , 20 ) assert skip_list.find('Key2' ) == 20 skip_list.insert('Some Key' , 10 ) skip_list.insert('Key2' , 8 ) skip_list.insert('V' , 13 ) assert skip_list.find('Y' ) is None assert skip_list.find('Key2' ) == 8 assert skip_list.find('Some Key' ) == 10 assert skip_list.find('V' ) == 13 def _lowerCAmelCase ( ) -> List[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.delete('Some key' ) assert len(skip_list.head.forward ) == 0 def _lowerCAmelCase ( ) -> Optional[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key1' , 12 ) skip_list.insert('V' , 13 ) skip_list.insert('X' , 14 ) skip_list.insert('Key2' , 15 ) skip_list.delete('V' ) skip_list.delete('Key2' ) assert skip_list.find('V' ) is None assert skip_list.find('Key2' ) is None def _lowerCAmelCase ( ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key1' , 12 ) skip_list.insert('V' , 13 ) skip_list.insert('X' , 14 ) skip_list.insert('Key2' , 15 ) skip_list.delete('V' ) assert skip_list.find('V' ) is None assert skip_list.find('X' ) == 14 assert skip_list.find('Key1' ) == 12 assert skip_list.find('Key2' ) == 15 skip_list.delete('X' ) assert skip_list.find('V' ) is None assert skip_list.find('X' ) is None assert skip_list.find('Key1' ) == 12 assert skip_list.find('Key2' ) == 15 skip_list.delete('Key1' ) assert skip_list.find('V' ) is None assert skip_list.find('X' ) is None assert skip_list.find('Key1' ) is None assert skip_list.find('Key2' ) == 15 skip_list.delete('Key2' ) assert skip_list.find('V' ) is None assert skip_list.find('X' ) is None assert skip_list.find('Key1' ) is None assert skip_list.find('Key2' ) is None def _lowerCAmelCase ( ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert('Key1' , 12 ) skip_list.insert('V' , 13 ) skip_list.insert('X' , 1_42 ) skip_list.insert('Key2' , 15 ) skip_list.delete('X' ) def traverse_keys(_UpperCamelCase : Dict ): yield node.key for forward_node in node.forward: yield from traverse_keys(_UpperCamelCase ) assert len(set(traverse_keys(skip_list.head ) ) ) == 4 def _lowerCAmelCase ( ) -> Union[str, Any]: """simple docstring""" def is_sorted(_UpperCamelCase : str ): return all(next_item >= item for item, next_item in zip(_UpperCamelCase , lst[1:] ) ) _SCREAMING_SNAKE_CASE =SkipList() for i in range(10 ): skip_list.insert(_UpperCamelCase , _UpperCamelCase ) assert is_sorted(list(_UpperCamelCase ) ) skip_list.delete(5 ) skip_list.delete(8 ) skip_list.delete(2 ) assert is_sorted(list(_UpperCamelCase ) ) skip_list.insert(-12 , -12 ) skip_list.insert(77 , 77 ) assert is_sorted(list(_UpperCamelCase ) ) def _lowerCAmelCase ( ) -> List[str]: """simple docstring""" for _ in range(1_00 ): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def _lowerCAmelCase ( ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE =SkipList() skip_list.insert(2 , '2' ) skip_list.insert(4 , '4' ) skip_list.insert(6 , '4' ) skip_list.insert(4 , '5' ) skip_list.insert(8 , '4' ) skip_list.insert(9 , '4' ) skip_list.delete(4 ) print(_UpperCamelCase ) if __name__ == "__main__": import doctest doctest.testmod() main()
47
1
'''simple docstring''' # Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar lowerCamelCase : List[str] = TypeVar("T") class A__ ( Generic[T] ): def __init__( self : List[Any] , _a : bool = True ) -> None: '''simple docstring''' _SCREAMING_SNAKE_CASE ={} # dictionary of lists _SCREAMING_SNAKE_CASE =directed def A ( self : str , _a : T , _a : T ) -> GraphAdjacencyList[T]: '''simple docstring''' if not self.directed: # For undirected graphs # if both source vertex and destination vertex are both present in the # adjacency list, add destination vertex to source vertex list of adjacent # vertices and add source vertex to destination vertex list of adjacent # vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(_a ) self.adj_list[destination_vertex].append(_a ) # if only source vertex is present in adjacency list, add destination vertex # to source vertex list of adjacent vertices, then create a new vertex with # destination vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(_a ) _SCREAMING_SNAKE_CASE =[source_vertex] # if only destination vertex is present in adjacency list, add source vertex # to destination vertex list of adjacent vertices, then create a new vertex # with source vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif destination_vertex in self.adj_list: self.adj_list[destination_vertex].append(_a ) _SCREAMING_SNAKE_CASE =[destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and assign a list # containing the destination vertex as it's first adjacent vertex also # create a new vertex with destination vertex as key and assign a list # containing the source vertex as it's first adjacent vertex. else: _SCREAMING_SNAKE_CASE =[destination_vertex] _SCREAMING_SNAKE_CASE =[source_vertex] else: # For directed graphs # if both source vertex and destination vertex are present in adjacency # list, add destination vertex to source vertex list of adjacent vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(_a ) # if only source vertex is present in adjacency list, add destination # vertex to source vertex list of adjacent vertices and create a new vertex # with destination vertex as key, which has no adjacent vertex elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(_a ) _SCREAMING_SNAKE_CASE =[] # if only destination vertex is present in adjacency list, create a new # vertex with source vertex as key and assign a list containing destination # vertex as first adjacent vertex elif destination_vertex in self.adj_list: _SCREAMING_SNAKE_CASE =[destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and a list containing # destination vertex as it's first adjacent vertex. Then create a new vertex # with destination vertex as key, which has no adjacent vertex else: _SCREAMING_SNAKE_CASE =[destination_vertex] _SCREAMING_SNAKE_CASE =[] return self def __repr__( self : Optional[int] ) -> str: '''simple docstring''' return pformat(self.adj_list )
47
'''simple docstring''' import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version lowerCamelCase : List[Any] = version.parse(importlib_metadata.version("nltk")) if NLTK_VERSION >= version.Version("3.6.4"): from nltk import word_tokenize lowerCamelCase : Any = "\\n@inproceedings{banarjee2005,\n title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n author = {Banerjee, Satanjeev and Lavie, Alon},\n booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n month = jun,\n year = {2005},\n address = {Ann Arbor, Michigan},\n publisher = {Association for Computational Linguistics},\n url = {https://www.aclweb.org/anthology/W05-0909},\n pages = {65--72},\n}\n" lowerCamelCase : Optional[Any] = "\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n" lowerCamelCase : Optional[Any] = "\nComputes METEOR score of translated segments against one or more references.\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n 'meteor': meteor score.\nExamples:\n\n >>> meteor = datasets.load_metric('meteor')\n >>> predictions = [\"It is a guide to action which ensures that the military always obeys the commands of the party\"]\n >>> references = [\"It is a guide to action that ensures that the military will forever heed Party commands\"]\n >>> results = meteor.compute(predictions=predictions, references=references)\n >>> print(round(results[\"meteor\"], 4))\n 0.6944\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def A ( self : Tuple ) -> str: '''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/nltk/nltk/blob/develop/nltk/translate/meteor_score.py'] , reference_urls=[ 'https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score', 'https://en.wikipedia.org/wiki/METEOR', ] , ) def A ( self : Union[str, Any] , _a : Union[str, Any] ) -> Optional[int]: '''simple docstring''' import nltk nltk.download('wordnet' ) if NLTK_VERSION >= version.Version('3.6.5' ): nltk.download('punkt' ) if NLTK_VERSION >= version.Version('3.6.6' ): nltk.download('omw-1.4' ) def A ( self : int , _a : Tuple , _a : List[str] , _a : List[str]=0.9 , _a : Dict=3 , _a : Optional[int]=0.5 ) -> Optional[int]: '''simple docstring''' if NLTK_VERSION >= version.Version('3.6.5' ): _SCREAMING_SNAKE_CASE =[ meteor_score.single_meteor_score( word_tokenize(_a ) , word_tokenize(_a ) , alpha=_a , beta=_a , gamma=_a ) for ref, pred in zip(_a , _a ) ] else: _SCREAMING_SNAKE_CASE =[ meteor_score.single_meteor_score(_a , _a , alpha=_a , beta=_a , gamma=_a ) for ref, pred in zip(_a , _a ) ] return {"meteor": np.mean(_a )}
47
1
'''simple docstring''' from random import randint from tempfile import TemporaryFile import numpy as np def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : Optional[Any] , _UpperCamelCase : Dict ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE =0 if start < end: _SCREAMING_SNAKE_CASE =randint(_UpperCamelCase , _UpperCamelCase ) _SCREAMING_SNAKE_CASE =a[end] _SCREAMING_SNAKE_CASE =a[pivot] _SCREAMING_SNAKE_CASE =temp _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =_in_place_partition(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) count += _in_place_quick_sort(_UpperCamelCase , _UpperCamelCase , p - 1 ) count += _in_place_quick_sort(_UpperCamelCase , p + 1 , _UpperCamelCase ) return count def _lowerCAmelCase ( _UpperCamelCase : List[str] , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Tuple ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =randint(_UpperCamelCase , _UpperCamelCase ) _SCREAMING_SNAKE_CASE =a[end] _SCREAMING_SNAKE_CASE =a[pivot] _SCREAMING_SNAKE_CASE =temp _SCREAMING_SNAKE_CASE =start - 1 for index in range(_UpperCamelCase , _UpperCamelCase ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value _SCREAMING_SNAKE_CASE =new_pivot_index + 1 _SCREAMING_SNAKE_CASE =a[new_pivot_index] _SCREAMING_SNAKE_CASE =a[index] _SCREAMING_SNAKE_CASE =temp _SCREAMING_SNAKE_CASE =a[new_pivot_index + 1] _SCREAMING_SNAKE_CASE =a[end] _SCREAMING_SNAKE_CASE =temp return new_pivot_index + 1, count lowerCamelCase : str = TemporaryFile() lowerCamelCase : Dict = 1_0_0 # 1000 elements are to be sorted lowerCamelCase , lowerCamelCase : int = 0, 1 # mean and standard deviation lowerCamelCase : List[str] = np.random.normal(mu, sigma, p) np.save(outfile, X) print("The array is") print(X) outfile.seek(0) # using the same array lowerCamelCase : Tuple = np.load(outfile) lowerCamelCase : Dict = len(M) - 1 lowerCamelCase : Tuple = _in_place_quick_sort(M, 0, r) print( "No of Comparisons for 100 elements selected from a standard normal distribution" "is :" ) print(z)
47
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowerCamelCase : List[str] = logging.get_logger(__name__) lowerCamelCase : List[Any] = { "facebook/convnextv2-tiny-1k-224": "https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json", } class A__ ( A__ , A__ ): A__ = 'convnextv2' def __init__( self : Tuple , _a : Optional[int]=3 , _a : Any=4 , _a : int=4 , _a : Union[str, Any]=None , _a : List[str]=None , _a : Optional[Any]="gelu" , _a : Any=0.02 , _a : Any=1e-12 , _a : Tuple=0.0 , _a : int=224 , _a : Any=None , _a : Optional[int]=None , **_a : List[str] , ) -> Optional[Any]: '''simple docstring''' super().__init__(**_a ) _SCREAMING_SNAKE_CASE =num_channels _SCREAMING_SNAKE_CASE =patch_size _SCREAMING_SNAKE_CASE =num_stages _SCREAMING_SNAKE_CASE =[96, 192, 384, 768] if hidden_sizes is None else hidden_sizes _SCREAMING_SNAKE_CASE =[3, 3, 9, 3] if depths is None else depths _SCREAMING_SNAKE_CASE =hidden_act _SCREAMING_SNAKE_CASE =initializer_range _SCREAMING_SNAKE_CASE =layer_norm_eps _SCREAMING_SNAKE_CASE =drop_path_rate _SCREAMING_SNAKE_CASE =image_size _SCREAMING_SNAKE_CASE =['stem'] + [f"stage{idx}" for idx in range(1 , len(self.depths ) + 1 )] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =get_aligned_output_features_output_indices( out_features=_a , out_indices=_a , stage_names=self.stage_names )
47
1
'''simple docstring''' from __future__ import annotations def _lowerCAmelCase ( _UpperCamelCase : float , _UpperCamelCase : float , _UpperCamelCase : float , ) -> tuple[str, float]: """simple docstring""" if (stress, tangential_force, area).count(0 ) != 1: raise ValueError('You cannot supply more or less than 2 values' ) elif stress < 0: raise ValueError('Stress cannot be negative' ) elif tangential_force < 0: raise ValueError('Tangential Force cannot be negative' ) elif area < 0: raise ValueError('Area cannot be negative' ) elif stress == 0: return ( "stress", tangential_force / area, ) elif tangential_force == 0: return ( "tangential_force", stress * area, ) else: return ( "area", tangential_force / stress, ) if __name__ == "__main__": import doctest doctest.testmod()
47
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase : int = {"configuration_glpn": ["GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP", "GLPNConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : int = ["GLPNFeatureExtractor"] lowerCamelCase : Optional[int] = ["GLPNImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Union[str, Any] = [ "GLPN_PRETRAINED_MODEL_ARCHIVE_LIST", "GLPNForDepthEstimation", "GLPNLayer", "GLPNModel", "GLPNPreTrainedModel", ] if TYPE_CHECKING: from .configuration_glpn import GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP, GLPNConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_glpn import GLPNFeatureExtractor from .image_processing_glpn import GLPNImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_glpn import ( GLPN_PRETRAINED_MODEL_ARCHIVE_LIST, GLPNForDepthEstimation, GLPNLayer, GLPNModel, GLPNPreTrainedModel, ) else: import sys lowerCamelCase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
47
1
'''simple docstring''' def _lowerCAmelCase ( ) -> list[list[int]]: """simple docstring""" return [list(range(10_00 - i , -10_00 - i , -1 ) ) for i in range(10_00 )] lowerCamelCase : Optional[Any] = generate_large_matrix() lowerCamelCase : Optional[int] = ( [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]], [[3, 2], [1, 0]], [[7, 7, 6]], [[7, 7, 6], [-1, -2, -3]], grid, ) def _lowerCAmelCase ( _UpperCamelCase : list[list[int]] ) -> None: """simple docstring""" assert all(row == sorted(_UpperCamelCase , reverse=_UpperCamelCase ) for row in grid ) assert all(list(_UpperCamelCase ) == sorted(_UpperCamelCase , reverse=_UpperCamelCase ) for col in zip(*_UpperCamelCase ) ) def _lowerCAmelCase ( _UpperCamelCase : list[int] ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =len(_UpperCamelCase ) - 1 # Edge cases such as no values or all numbers are negative. if not array or array[0] < 0: return 0 while right + 1 > left: _SCREAMING_SNAKE_CASE =(left + right) // 2 _SCREAMING_SNAKE_CASE =array[mid] # Num must be negative and the index must be greater than or equal to 0. if num < 0 and array[mid - 1] >= 0: return mid if num >= 0: _SCREAMING_SNAKE_CASE =mid + 1 else: _SCREAMING_SNAKE_CASE =mid - 1 # No negative numbers so return the last index of the array + 1 which is the length. return len(_UpperCamelCase ) def _lowerCAmelCase ( _UpperCamelCase : list[list[int]] ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =len(grid[0] ) for i in range(len(_UpperCamelCase ) ): _SCREAMING_SNAKE_CASE =find_negative_index(grid[i][:bound] ) total += bound return (len(_UpperCamelCase ) * len(grid[0] )) - total def _lowerCAmelCase ( _UpperCamelCase : list[list[int]] ) -> int: """simple docstring""" return len([number for row in grid for number in row if number < 0] ) def _lowerCAmelCase ( _UpperCamelCase : list[list[int]] ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE =0 for row in grid: for i, number in enumerate(_UpperCamelCase ): if number < 0: total += len(_UpperCamelCase ) - i break return total def _lowerCAmelCase ( ) -> None: """simple docstring""" from timeit import timeit print('Running benchmarks' ) _SCREAMING_SNAKE_CASE =( 'from __main__ import count_negatives_binary_search, ' 'count_negatives_brute_force, count_negatives_brute_force_with_break, grid' ) for func in ( "count_negatives_binary_search", # took 0.7727 seconds "count_negatives_brute_force_with_break", # took 4.6505 seconds "count_negatives_brute_force", # took 12.8160 seconds ): _SCREAMING_SNAKE_CASE =timeit(f"{func}(grid=grid)" , setup=_UpperCamelCase , number=5_00 ) print(f"{func}() took {time:0.4f} seconds" ) if __name__ == "__main__": import doctest doctest.testmod() benchmark()
47
'''simple docstring''' lowerCamelCase : Any = "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" lowerCamelCase : int = [{"type": "code", "content": INSTALL_CONTENT}] lowerCamelCase : str = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
47
1
'''simple docstring''' import unittest from transformers import MPNetConfig, 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 ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) class A__ : def __init__( self : int , _a : Optional[int] , _a : Optional[Any]=13 , _a : List[Any]=7 , _a : List[Any]=True , _a : str=True , _a : Dict=False , _a : str=True , _a : List[str]=99 , _a : str=64 , _a : Union[str, Any]=5 , _a : List[Any]=4 , _a : Optional[Any]=64 , _a : Tuple="gelu" , _a : List[str]=0.1 , _a : str=0.1 , _a : int=512 , _a : Dict=16 , _a : List[str]=2 , _a : int=0.02 , _a : Union[str, Any]=3 , _a : str=4 , _a : Tuple=None , ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =parent _SCREAMING_SNAKE_CASE =batch_size _SCREAMING_SNAKE_CASE =seq_length _SCREAMING_SNAKE_CASE =is_training _SCREAMING_SNAKE_CASE =use_input_mask _SCREAMING_SNAKE_CASE =use_token_type_ids _SCREAMING_SNAKE_CASE =use_labels _SCREAMING_SNAKE_CASE =vocab_size _SCREAMING_SNAKE_CASE =hidden_size _SCREAMING_SNAKE_CASE =num_hidden_layers _SCREAMING_SNAKE_CASE =num_attention_heads _SCREAMING_SNAKE_CASE =intermediate_size _SCREAMING_SNAKE_CASE =hidden_act _SCREAMING_SNAKE_CASE =hidden_dropout_prob _SCREAMING_SNAKE_CASE =attention_probs_dropout_prob _SCREAMING_SNAKE_CASE =max_position_embeddings _SCREAMING_SNAKE_CASE =type_vocab_size _SCREAMING_SNAKE_CASE =type_sequence_label_size _SCREAMING_SNAKE_CASE =initializer_range _SCREAMING_SNAKE_CASE =num_labels _SCREAMING_SNAKE_CASE =num_choices _SCREAMING_SNAKE_CASE =scope def A ( self : str ) -> Tuple: '''simple docstring''' return MPNetConfig.from_pretrained('microsoft/mpnet-base' ) def A ( self : int ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _SCREAMING_SNAKE_CASE =None if self.use_input_mask: _SCREAMING_SNAKE_CASE =random_attention_mask([self.batch_size, self.seq_length] ) _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =None if self.use_labels: _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _SCREAMING_SNAKE_CASE =ids_tensor([self.batch_size] , self.num_choices ) _SCREAMING_SNAKE_CASE =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def A ( self : Dict ) -> Dict: '''simple docstring''' return MPNetConfig( 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 , initializer_range=self.initializer_range , ) def A ( self : Tuple , _a : Dict , _a : Dict , _a : Dict , _a : int , _a : Optional[int] , _a : Any ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =MPNetModel(config=_a ) model.to(_a ) model.eval() _SCREAMING_SNAKE_CASE =model(_a , _a ) _SCREAMING_SNAKE_CASE =model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def A ( self : Union[str, Any] , _a : List[Any] , _a : Dict , _a : List[Any] , _a : Any , _a : List[Any] , _a : Dict ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =MPNetForQuestionAnswering(config=_a ) model.to(_a ) model.eval() _SCREAMING_SNAKE_CASE =model( _a , attention_mask=_a , start_positions=_a , end_positions=_a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def A ( self : Tuple , _a : Any , _a : List[Any] , _a : List[Any] , _a : Dict , _a : List[str] , _a : List[Any] ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.num_labels _SCREAMING_SNAKE_CASE =MPNetForSequenceClassification(_a ) model.to(_a ) model.eval() _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def A ( self : Any , _a : int , _a : Optional[Any] , _a : List[Any] , _a : Tuple , _a : Tuple , _a : int ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.num_choices _SCREAMING_SNAKE_CASE =MPNetForMultipleChoice(config=_a ) model.to(_a ) model.eval() _SCREAMING_SNAKE_CASE =input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _SCREAMING_SNAKE_CASE =input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _SCREAMING_SNAKE_CASE =model( _a , attention_mask=_a , labels=_a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def A ( self : Any , _a : int , _a : Optional[Any] , _a : Optional[Any] , _a : str , _a : List[Any] , _a : Any ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.num_labels _SCREAMING_SNAKE_CASE =MPNetForTokenClassification(config=_a ) model.to(_a ) model.eval() _SCREAMING_SNAKE_CASE =model(_a , attention_mask=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def A ( self : Any ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() ((_SCREAMING_SNAKE_CASE) , (_SCREAMING_SNAKE_CASE) , (_SCREAMING_SNAKE_CASE) , (_SCREAMING_SNAKE_CASE) , (_SCREAMING_SNAKE_CASE) , (_SCREAMING_SNAKE_CASE)) =config_and_inputs _SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class A__ ( A__ , A__ , unittest.TestCase ): A__ = ( ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) if is_torch_available() else () ) A__ = ( { 'feature-extraction': MPNetModel, 'fill-mask': MPNetForMaskedLM, 'question-answering': MPNetForQuestionAnswering, 'text-classification': MPNetForSequenceClassification, 'token-classification': MPNetForTokenClassification, 'zero-shot': MPNetForSequenceClassification, } if is_torch_available() else {} ) A__ = False A__ = True def A ( self : int ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =MPNetModelTester(self ) _SCREAMING_SNAKE_CASE =ConfigTester(self , config_class=_a , hidden_size=37 ) def A ( self : List[Any] ) -> int: '''simple docstring''' self.config_tester.run_common_tests() def A ( self : Any ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_model(*_a ) def A ( self : List[Any] ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_sequence_classification(*_a ) def A ( self : Optional[int] ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_multiple_choice(*_a ) def A ( self : Any ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_token_classification(*_a ) def A ( self : str ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_question_answering(*_a ) @require_torch class A__ ( unittest.TestCase ): @slow def A ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =MPNetModel.from_pretrained('microsoft/mpnet-base' ) _SCREAMING_SNAKE_CASE =torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) _SCREAMING_SNAKE_CASE =model(_a )[0] _SCREAMING_SNAKE_CASE =torch.Size((1, 11, 768) ) self.assertEqual(output.shape , _a ) _SCREAMING_SNAKE_CASE =torch.tensor( [[[-0.05_50, 0.19_43, -0.07_40], [-0.05_62, 0.22_11, -0.05_79], [-0.04_37, 0.33_37, -0.06_41]]] ) # compare the actual values for a slice. self.assertTrue(torch.allclose(output[:, :3, :3] , _a , atol=1e-4 ) )
47
'''simple docstring''' import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device lowerCamelCase : Optional[int] = False class A__ ( unittest.TestCase ): pass @slow @require_torch_gpu class A__ ( unittest.TestCase ): def A ( self : Tuple ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =VersatileDiffusionImageVariationPipeline.from_pretrained('shi-labs/versatile-diffusion' ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) _SCREAMING_SNAKE_CASE =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg' ) _SCREAMING_SNAKE_CASE =torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE =pipe( image=_a , generator=_a , guidance_scale=7.5 , num_inference_steps=50 , output_type='numpy' , ).images _SCREAMING_SNAKE_CASE =image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) _SCREAMING_SNAKE_CASE =np.array([0.04_41, 0.04_69, 0.05_07, 0.05_75, 0.06_32, 0.06_50, 0.08_65, 0.09_09, 0.09_45] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
47
1
'''simple docstring''' import logging import math from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union import torch from .tensor_utils import tensor_tree_map, tree_map def _lowerCAmelCase ( _UpperCamelCase : Union[dict, list, tuple, torch.Tensor] ) -> List[Tuple[int, ...]]: """simple docstring""" _SCREAMING_SNAKE_CASE =[] if isinstance(_UpperCamelCase , _UpperCamelCase ): for v in tree.values(): shapes.extend(_fetch_dims(_UpperCamelCase ) ) elif isinstance(_UpperCamelCase , (list, tuple) ): for t in tree: shapes.extend(_fetch_dims(_UpperCamelCase ) ) elif isinstance(_UpperCamelCase , torch.Tensor ): shapes.append(tree.shape ) else: raise ValueError('Not supported' ) return shapes @torch.jit.ignore def _lowerCAmelCase ( _UpperCamelCase : int , _UpperCamelCase : Tuple[int, ...] ) -> Tuple[int, ...]: """simple docstring""" _SCREAMING_SNAKE_CASE =[] for d in reversed(_UpperCamelCase ): idx.append(flat_idx % d ) _SCREAMING_SNAKE_CASE =flat_idx // d return tuple(reversed(_UpperCamelCase ) ) @torch.jit.ignore def _lowerCAmelCase ( _UpperCamelCase : Sequence[int] , _UpperCamelCase : Sequence[int] , _UpperCamelCase : Sequence[int] , _UpperCamelCase : Optional[Sequence[bool]] = None , _UpperCamelCase : Optional[Sequence[bool]] = None , ) -> List[Tuple[slice, ...]]: """simple docstring""" def reduce_edge_list(_UpperCamelCase : List[bool] ) -> None: _SCREAMING_SNAKE_CASE =True for i in range(len(_UpperCamelCase ) ): _SCREAMING_SNAKE_CASE =-1 * (i + 1) l[reversed_idx] &= tally _SCREAMING_SNAKE_CASE =l[reversed_idx] if start_edges is None: _SCREAMING_SNAKE_CASE =[s == 0 for s in start] reduce_edge_list(_UpperCamelCase ) if end_edges is None: _SCREAMING_SNAKE_CASE =[e == (d - 1) for e, d in zip(_UpperCamelCase , _UpperCamelCase )] reduce_edge_list(_UpperCamelCase ) # Base cases. Either start/end are empty and we're done, or the final, # one-dimensional tensor can be simply sliced if len(_UpperCamelCase ) == 0: return [()] elif len(_UpperCamelCase ) == 1: return [(slice(start[0] , end[0] + 1 ),)] _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =[] # Dimensions common to start and end can be selected directly for s, e in zip(_UpperCamelCase , _UpperCamelCase ): if s == e: path_list.append(slice(_UpperCamelCase , s + 1 ) ) else: break _SCREAMING_SNAKE_CASE =tuple(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =len(_UpperCamelCase ) # start == end, and we're done if divergence_idx == len(_UpperCamelCase ): return [path] def upper() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None _SCREAMING_SNAKE_CASE =start[divergence_idx] return tuple( path + (slice(_UpperCamelCase , sdi + 1 ),) + s for s in _get_minimal_slice_set( start[divergence_idx + 1 :] , [d - 1 for d in dims[divergence_idx + 1 :]] , dims[divergence_idx + 1 :] , start_edges=start_edges[divergence_idx + 1 :] , end_edges=[True for _ in end_edges[divergence_idx + 1 :]] , ) ) def lower() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None _SCREAMING_SNAKE_CASE =end[divergence_idx] return tuple( path + (slice(_UpperCamelCase , edi + 1 ),) + s for s in _get_minimal_slice_set( [0 for _ in start[divergence_idx + 1 :]] , end[divergence_idx + 1 :] , dims[divergence_idx + 1 :] , start_edges=[True for _ in start_edges[divergence_idx + 1 :]] , end_edges=end_edges[divergence_idx + 1 :] , ) ) # If both start and end are at the edges of the subtree rooted at # divergence_idx, we can just select the whole subtree at once if start_edges[divergence_idx] and end_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] + 1 ),) ) # If just start is at the edge, we can grab almost all of the subtree, # treating only the ragged bottom edge as an edge case elif start_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] ),) ) slices.extend(lower() ) # Analogous to the previous case, but the top is ragged this time elif end_edges[divergence_idx]: slices.extend(upper() ) slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] + 1 ),) ) # If both sides of the range are ragged, we need to handle both sides # separately. If there's contiguous meat in between them, we can index it # in one big chunk else: slices.extend(upper() ) _SCREAMING_SNAKE_CASE =end[divergence_idx] - start[divergence_idx] if middle_ground > 1: slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] ),) ) slices.extend(lower() ) return slices @torch.jit.ignore def _lowerCAmelCase ( _UpperCamelCase : torch.Tensor , _UpperCamelCase : int , _UpperCamelCase : int , _UpperCamelCase : int ) -> torch.Tensor: """simple docstring""" _SCREAMING_SNAKE_CASE =t.shape[:no_batch_dims] _SCREAMING_SNAKE_CASE =list(_flat_idx_to_idx(_UpperCamelCase , _UpperCamelCase ) ) # _get_minimal_slice_set is inclusive _SCREAMING_SNAKE_CASE =list(_flat_idx_to_idx(flat_end - 1 , _UpperCamelCase ) ) # Get an ordered list of slices to perform _SCREAMING_SNAKE_CASE =_get_minimal_slice_set( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , ) _SCREAMING_SNAKE_CASE =[t[s] for s in slices] return torch.cat([s.view((-1,) + t.shape[no_batch_dims:] ) for s in sliced_tensors] ) def _lowerCAmelCase ( _UpperCamelCase : Callable , _UpperCamelCase : Dict[str, Any] , _UpperCamelCase : int , _UpperCamelCase : int , _UpperCamelCase : bool = False , _UpperCamelCase : Any = None , _UpperCamelCase : bool = False , ) -> Any: """simple docstring""" if not (len(_UpperCamelCase ) > 0): raise ValueError('Must provide at least one input' ) _SCREAMING_SNAKE_CASE =[shape[:no_batch_dims] for shape in _fetch_dims(_UpperCamelCase )] _SCREAMING_SNAKE_CASE =tuple([max(_UpperCamelCase ) for s in zip(*_UpperCamelCase )] ) def _prep_inputs(_UpperCamelCase : torch.Tensor ) -> torch.Tensor: if not low_mem: if not sum(t.shape[:no_batch_dims] ) == no_batch_dims: _SCREAMING_SNAKE_CASE =t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) _SCREAMING_SNAKE_CASE =t.reshape(-1 , *t.shape[no_batch_dims:] ) else: _SCREAMING_SNAKE_CASE =t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) return t _SCREAMING_SNAKE_CASE =tensor_tree_map(_prep_inputs , _UpperCamelCase ) _SCREAMING_SNAKE_CASE =None if _out is not None: _SCREAMING_SNAKE_CASE =tensor_tree_map(lambda _UpperCamelCase : t.view([-1] + list(t.shape[no_batch_dims:] ) ) , _out ) _SCREAMING_SNAKE_CASE =1 for d in orig_batch_dims: flat_batch_dim *= d _SCREAMING_SNAKE_CASE =flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0) def _select_chunk(_UpperCamelCase : torch.Tensor ) -> torch.Tensor: return t[i : i + chunk_size] if t.shape[0] != 1 else t _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =prepped_outputs for _ in range(_UpperCamelCase ): # Chunk the input if not low_mem: _SCREAMING_SNAKE_CASE =_select_chunk else: _SCREAMING_SNAKE_CASE =partial( _chunk_slice , flat_start=_UpperCamelCase , flat_end=min(_UpperCamelCase , i + chunk_size ) , no_batch_dims=len(_UpperCamelCase ) , ) _SCREAMING_SNAKE_CASE =tensor_tree_map(_UpperCamelCase , _UpperCamelCase ) # Run the layer on the chunk _SCREAMING_SNAKE_CASE =layer(**_UpperCamelCase ) # Allocate space for the output if out is None: _SCREAMING_SNAKE_CASE =tensor_tree_map(lambda _UpperCamelCase : t.new_zeros((flat_batch_dim,) + t.shape[1:] ) , _UpperCamelCase ) # Put the chunk in its pre-allocated space if isinstance(_UpperCamelCase , _UpperCamelCase ): def assign(_UpperCamelCase : dict , _UpperCamelCase : dict ) -> None: for k, v in da.items(): if isinstance(_UpperCamelCase , _UpperCamelCase ): assign(_UpperCamelCase , da[k] ) else: if _add_into_out: v[i : i + chunk_size] += da[k] else: _SCREAMING_SNAKE_CASE =da[k] assign(_UpperCamelCase , _UpperCamelCase ) elif isinstance(_UpperCamelCase , _UpperCamelCase ): for xa, xa in zip(_UpperCamelCase , _UpperCamelCase ): if _add_into_out: xa[i : i + chunk_size] += xa else: _SCREAMING_SNAKE_CASE =xa elif isinstance(_UpperCamelCase , torch.Tensor ): if _add_into_out: out[i : i + chunk_size] += output_chunk else: _SCREAMING_SNAKE_CASE =output_chunk else: raise ValueError('Not supported' ) i += chunk_size _SCREAMING_SNAKE_CASE =tensor_tree_map(lambda _UpperCamelCase : t.view(orig_batch_dims + t.shape[1:] ) , _UpperCamelCase ) return out class A__ : def __init__( self : str , _a : int = 512 , ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =max_chunk_size _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =None def A ( self : Optional[Any] , _a : Callable , _a : tuple , _a : int ) -> int: '''simple docstring''' logging.info('Tuning chunk size...' ) if min_chunk_size >= self.max_chunk_size: return min_chunk_size _SCREAMING_SNAKE_CASE =[2**l for l in range(int(math.log(self.max_chunk_size , 2 ) ) + 1 )] _SCREAMING_SNAKE_CASE =[c for c in candidates if c > min_chunk_size] _SCREAMING_SNAKE_CASE =[min_chunk_size] + candidates candidates[-1] += 4 def test_chunk_size(_a : int ) -> bool: try: with torch.no_grad(): fn(*_a , chunk_size=_a ) return True except RuntimeError: return False _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =len(_a ) - 1 while i > min_viable_chunk_size_index: _SCREAMING_SNAKE_CASE =test_chunk_size(candidates[i] ) if not viable: _SCREAMING_SNAKE_CASE =(min_viable_chunk_size_index + i) // 2 else: _SCREAMING_SNAKE_CASE =i _SCREAMING_SNAKE_CASE =(i + len(_a ) - 1) // 2 return candidates[min_viable_chunk_size_index] def A ( self : Dict , _a : Iterable , _a : Iterable ) -> bool: '''simple docstring''' _SCREAMING_SNAKE_CASE =True for aa, aa in zip(_a , _a ): assert type(_a ) == type(_a ) if isinstance(_a , (list, tuple) ): consistent &= self._compare_arg_caches(_a , _a ) elif isinstance(_a , _a ): _SCREAMING_SNAKE_CASE =[v for _, v in sorted(aa.items() , key=lambda _a : x[0] )] _SCREAMING_SNAKE_CASE =[v for _, v in sorted(aa.items() , key=lambda _a : x[0] )] consistent &= self._compare_arg_caches(_a , _a ) else: consistent &= aa == aa return consistent def A ( self : List[str] , _a : Callable , _a : tuple , _a : int , ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =True _SCREAMING_SNAKE_CASE =tree_map(lambda _a : a.shape if isinstance(_a , torch.Tensor ) else a , _a , _a ) if self.cached_arg_data is not None: # If args have changed shape/value, we need to re-tune assert len(self.cached_arg_data ) == len(_a ) _SCREAMING_SNAKE_CASE =self._compare_arg_caches(self.cached_arg_data , _a ) else: # Otherwise, we can reuse the precomputed value _SCREAMING_SNAKE_CASE =False if not consistent: _SCREAMING_SNAKE_CASE =self._determine_favorable_chunk_size( _a , _a , _a , ) _SCREAMING_SNAKE_CASE =arg_data assert self.cached_chunk_size is not None return self.cached_chunk_size
47
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase : Any = { "configuration_funnel": ["FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP", "FunnelConfig"], "convert_funnel_original_tf_checkpoint_to_pytorch": [], "tokenization_funnel": ["FunnelTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[Any] = ["FunnelTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[str] = [ "FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST", "FunnelBaseModel", "FunnelForMaskedLM", "FunnelForMultipleChoice", "FunnelForPreTraining", "FunnelForQuestionAnswering", "FunnelForSequenceClassification", "FunnelForTokenClassification", "FunnelModel", "FunnelPreTrainedModel", "load_tf_weights_in_funnel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Union[str, Any] = [ "TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST", "TFFunnelBaseModel", "TFFunnelForMaskedLM", "TFFunnelForMultipleChoice", "TFFunnelForPreTraining", "TFFunnelForQuestionAnswering", "TFFunnelForSequenceClassification", "TFFunnelForTokenClassification", "TFFunnelModel", "TFFunnelPreTrainedModel", ] if TYPE_CHECKING: from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig from .tokenization_funnel import FunnelTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_funnel_fast import FunnelTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_funnel import ( FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, FunnelBaseModel, FunnelForMaskedLM, FunnelForMultipleChoice, FunnelForPreTraining, FunnelForQuestionAnswering, FunnelForSequenceClassification, FunnelForTokenClassification, FunnelModel, FunnelPreTrainedModel, load_tf_weights_in_funnel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_funnel import ( TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, TFFunnelPreTrainedModel, ) else: import sys lowerCamelCase : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
47
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase : int = {"configuration_mbart": ["MBART_PRETRAINED_CONFIG_ARCHIVE_MAP", "MBartConfig", "MBartOnnxConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[Any] = ["MBartTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Dict = ["MBartTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : int = [ "MBART_PRETRAINED_MODEL_ARCHIVE_LIST", "MBartForCausalLM", "MBartForConditionalGeneration", "MBartForQuestionAnswering", "MBartForSequenceClassification", "MBartModel", "MBartPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Union[str, Any] = [ "TFMBartForConditionalGeneration", "TFMBartModel", "TFMBartPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[Any] = [ "FlaxMBartForConditionalGeneration", "FlaxMBartForQuestionAnswering", "FlaxMBartForSequenceClassification", "FlaxMBartModel", "FlaxMBartPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys lowerCamelCase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
47
'''simple docstring''' import importlib import torch import yaml from omegaconf import OmegaConf from taming.models.vqgan import VQModel def _lowerCAmelCase ( _UpperCamelCase : Dict , _UpperCamelCase : Any=False ) -> Optional[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =OmegaConf.load(_UpperCamelCase ) if display: print(yaml.dump(OmegaConf.to_container(_UpperCamelCase ) ) ) return config def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : Optional[Any]=None , _UpperCamelCase : Union[str, Any]=None ) -> Optional[Any]: """simple docstring""" if conf_path is None: _SCREAMING_SNAKE_CASE ='./model_checkpoints/vqgan_only.yaml' _SCREAMING_SNAKE_CASE =load_config(_UpperCamelCase , display=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =VQModel(**config.model.params ) if ckpt_path is None: _SCREAMING_SNAKE_CASE ='./model_checkpoints/vqgan_only.pt' _SCREAMING_SNAKE_CASE =torch.load(_UpperCamelCase , map_location=_UpperCamelCase ) if ".ckpt" in ckpt_path: _SCREAMING_SNAKE_CASE =sd['state_dict'] model.load_state_dict(_UpperCamelCase , strict=_UpperCamelCase ) model.to(_UpperCamelCase ) del sd return model def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : int ) -> Dict: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =model.encode(_UpperCamelCase ) print(f"VQGAN --- {model.__class__.__name__}: latent shape: {z.shape[2:]}" ) _SCREAMING_SNAKE_CASE =model.decode(_UpperCamelCase ) return xrec def _lowerCAmelCase ( _UpperCamelCase : Dict , _UpperCamelCase : List[str]=False ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =string.rsplit('.' , 1 ) if reload: _SCREAMING_SNAKE_CASE =importlib.import_module(_UpperCamelCase ) importlib.reload(_UpperCamelCase ) return getattr(importlib.import_module(_UpperCamelCase , package=_UpperCamelCase ) , cls ) def _lowerCAmelCase ( _UpperCamelCase : str ) -> List[str]: """simple docstring""" if "target" not in config: raise KeyError('Expected key `target` to instantiate.' ) return get_obj_from_str(config['target'] )(**config.get('params' , {} ) ) def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : List[Any] , _UpperCamelCase : List[str]=True , _UpperCamelCase : int=True ) -> Union[str, Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =instantiate_from_config(_UpperCamelCase ) if sd is not None: model.load_state_dict(_UpperCamelCase ) if gpu: model.cuda() if eval_mode: model.eval() return {"model": model} def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Optional[Any] , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Optional[int] ) -> List[Any]: """simple docstring""" if ckpt: _SCREAMING_SNAKE_CASE =torch.load(_UpperCamelCase , map_location='cpu' ) _SCREAMING_SNAKE_CASE =pl_sd['global_step'] print(f"loaded model from global step {global_step}." ) else: _SCREAMING_SNAKE_CASE ={'state_dict': None} _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =load_model_from_config(config.model , pl_sd['state_dict'] , gpu=_UpperCamelCase , eval_mode=_UpperCamelCase )['model'] return model, global_step
47
1
'''simple docstring''' from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class A__ ( nn.Module ): def __init__( self : int , _a : int = 16 , _a : int = 88 , _a : Optional[int] = None , _a : int = 1 , _a : float = 0.0 , _a : int = 32 , _a : Optional[int] = None , _a : bool = False , _a : Optional[int] = None , _a : Optional[int] = None , _a : str = "geglu" , _a : Optional[int] = None , ) -> Any: '''simple docstring''' super().__init__() _SCREAMING_SNAKE_CASE =nn.ModuleList( [ TransformeraDModel( num_attention_heads=_a , attention_head_dim=_a , in_channels=_a , num_layers=_a , dropout=_a , norm_num_groups=_a , cross_attention_dim=_a , attention_bias=_a , sample_size=_a , num_vector_embeds=_a , activation_fn=_a , num_embeds_ada_norm=_a , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference _SCREAMING_SNAKE_CASE =0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` _SCREAMING_SNAKE_CASE =[77, 257] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` _SCREAMING_SNAKE_CASE =[1, 0] def A ( self : Any , _a : List[Any] , _a : Union[str, Any] , _a : Tuple=None , _a : Any=None , _a : List[Any]=None , _a : bool = True , ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =hidden_states _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens _SCREAMING_SNAKE_CASE =encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] _SCREAMING_SNAKE_CASE =self.transformer_index_for_condition[i] _SCREAMING_SNAKE_CASE =self.transformers[transformer_index]( _a , encoder_hidden_states=_a , timestep=_a , cross_attention_kwargs=_a , return_dict=_a , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] _SCREAMING_SNAKE_CASE =encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) _SCREAMING_SNAKE_CASE =output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=_a )
47
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase : int = {"configuration_mbart": ["MBART_PRETRAINED_CONFIG_ARCHIVE_MAP", "MBartConfig", "MBartOnnxConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[Any] = ["MBartTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Dict = ["MBartTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : int = [ "MBART_PRETRAINED_MODEL_ARCHIVE_LIST", "MBartForCausalLM", "MBartForConditionalGeneration", "MBartForQuestionAnswering", "MBartForSequenceClassification", "MBartModel", "MBartPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Union[str, Any] = [ "TFMBartForConditionalGeneration", "TFMBartModel", "TFMBartPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[Any] = [ "FlaxMBartForConditionalGeneration", "FlaxMBartForQuestionAnswering", "FlaxMBartForSequenceClassification", "FlaxMBartModel", "FlaxMBartPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys lowerCamelCase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
47
1
'''simple docstring''' import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class A__ ( ctypes.Structure ): # _fields is a specific attr expected by ctypes A__ = [('size', ctypes.c_int), ('visible', ctypes.c_byte)] def _lowerCAmelCase ( ) -> Optional[Any]: """simple docstring""" if os.name == "nt": _SCREAMING_SNAKE_CASE =CursorInfo() _SCREAMING_SNAKE_CASE =ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(_UpperCamelCase , ctypes.byref(_UpperCamelCase ) ) _SCREAMING_SNAKE_CASE =False ctypes.windll.kernelaa.SetConsoleCursorInfo(_UpperCamelCase , ctypes.byref(_UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('\033[?25l' ) sys.stdout.flush() def _lowerCAmelCase ( ) -> List[str]: """simple docstring""" if os.name == "nt": _SCREAMING_SNAKE_CASE =CursorInfo() _SCREAMING_SNAKE_CASE =ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(_UpperCamelCase , ctypes.byref(_UpperCamelCase ) ) _SCREAMING_SNAKE_CASE =True ctypes.windll.kernelaa.SetConsoleCursorInfo(_UpperCamelCase , ctypes.byref(_UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('\033[?25h' ) sys.stdout.flush() @contextmanager def _lowerCAmelCase ( ) -> Optional[int]: """simple docstring""" try: hide_cursor() yield finally: show_cursor()
47
'''simple docstring''' from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : List[Any] = logging.get_logger(__name__) lowerCamelCase : str = { "huggingface/time-series-transformer-tourism-monthly": ( "https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json" ), # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer } class A__ ( A__ ): A__ = 'time_series_transformer' A__ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self : Optional[int] , _a : Optional[int] = None , _a : Optional[int] = None , _a : str = "student_t" , _a : str = "nll" , _a : int = 1 , _a : List[int] = [1, 2, 3, 4, 5, 6, 7] , _a : Optional[Union[str, bool]] = "mean" , _a : int = 0 , _a : int = 0 , _a : int = 0 , _a : int = 0 , _a : Optional[List[int]] = None , _a : Optional[List[int]] = None , _a : int = 32 , _a : int = 32 , _a : int = 2 , _a : int = 2 , _a : int = 2 , _a : int = 2 , _a : bool = True , _a : str = "gelu" , _a : int = 64 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : int = 100 , _a : float = 0.02 , _a : Union[str, Any]=True , **_a : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =prediction_length _SCREAMING_SNAKE_CASE =context_length or prediction_length _SCREAMING_SNAKE_CASE =distribution_output _SCREAMING_SNAKE_CASE =loss _SCREAMING_SNAKE_CASE =input_size _SCREAMING_SNAKE_CASE =num_time_features _SCREAMING_SNAKE_CASE =lags_sequence _SCREAMING_SNAKE_CASE =scaling _SCREAMING_SNAKE_CASE =num_dynamic_real_features _SCREAMING_SNAKE_CASE =num_static_real_features _SCREAMING_SNAKE_CASE =num_static_categorical_features 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`' ) _SCREAMING_SNAKE_CASE =cardinality else: _SCREAMING_SNAKE_CASE =[0] 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`' ) _SCREAMING_SNAKE_CASE =embedding_dimension else: _SCREAMING_SNAKE_CASE =[min(50 , (cat + 1) // 2 ) for cat in self.cardinality] _SCREAMING_SNAKE_CASE =num_parallel_samples # Transformer architecture configuration _SCREAMING_SNAKE_CASE =input_size * len(_a ) + self._number_of_features _SCREAMING_SNAKE_CASE =d_model _SCREAMING_SNAKE_CASE =encoder_attention_heads _SCREAMING_SNAKE_CASE =decoder_attention_heads _SCREAMING_SNAKE_CASE =encoder_ffn_dim _SCREAMING_SNAKE_CASE =decoder_ffn_dim _SCREAMING_SNAKE_CASE =encoder_layers _SCREAMING_SNAKE_CASE =decoder_layers _SCREAMING_SNAKE_CASE =dropout _SCREAMING_SNAKE_CASE =attention_dropout _SCREAMING_SNAKE_CASE =activation_dropout _SCREAMING_SNAKE_CASE =encoder_layerdrop _SCREAMING_SNAKE_CASE =decoder_layerdrop _SCREAMING_SNAKE_CASE =activation_function _SCREAMING_SNAKE_CASE =init_std _SCREAMING_SNAKE_CASE =use_cache super().__init__(is_encoder_decoder=_a , **_a ) @property def A ( self : List[Any] ) -> int: '''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 )
47
1
'''simple docstring''' import gc import inspect import unittest import torch from parameterized import parameterized from diffusers import PriorTransformer from diffusers.utils import floats_tensor, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin enable_full_determinism() class A__ ( A__ , unittest.TestCase ): A__ = PriorTransformer A__ = 'hidden_states' @property def A ( self : Any ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =4 _SCREAMING_SNAKE_CASE =8 _SCREAMING_SNAKE_CASE =7 _SCREAMING_SNAKE_CASE =floats_tensor((batch_size, embedding_dim) ).to(_a ) _SCREAMING_SNAKE_CASE =floats_tensor((batch_size, embedding_dim) ).to(_a ) _SCREAMING_SNAKE_CASE =floats_tensor((batch_size, num_embeddings, embedding_dim) ).to(_a ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } def A ( self : List[str] , _a : List[str]=0 ) -> Union[str, Any]: '''simple docstring''' torch.manual_seed(_a ) _SCREAMING_SNAKE_CASE =4 _SCREAMING_SNAKE_CASE =8 _SCREAMING_SNAKE_CASE =7 _SCREAMING_SNAKE_CASE =torch.randn((batch_size, embedding_dim) ).to(_a ) _SCREAMING_SNAKE_CASE =torch.randn((batch_size, embedding_dim) ).to(_a ) _SCREAMING_SNAKE_CASE =torch.randn((batch_size, num_embeddings, embedding_dim) ).to(_a ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } @property def A ( self : Optional[int] ) -> List[Any]: '''simple docstring''' return (4, 8) @property def A ( self : Dict ) -> Optional[Any]: '''simple docstring''' return (4, 8) def A ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE ={ 'num_attention_heads': 2, 'attention_head_dim': 4, 'num_layers': 2, 'embedding_dim': 8, 'num_embeddings': 7, 'additional_embeddings': 4, } _SCREAMING_SNAKE_CASE =self.dummy_input return init_dict, inputs_dict def A ( self : Any ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =PriorTransformer.from_pretrained( 'hf-internal-testing/prior-dummy' , output_loading_info=_a ) self.assertIsNotNone(_a ) self.assertEqual(len(loading_info['missing_keys'] ) , 0 ) model.to(_a ) _SCREAMING_SNAKE_CASE =model(**self.dummy_input )[0] assert hidden_states is not None, "Make sure output is not None" def A ( self : int ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =self.prepare_init_args_and_inputs_for_common() _SCREAMING_SNAKE_CASE =self.model_class(**_a ) _SCREAMING_SNAKE_CASE =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _SCREAMING_SNAKE_CASE =[*signature.parameters.keys()] _SCREAMING_SNAKE_CASE =['hidden_states', 'timestep'] self.assertListEqual(arg_names[:2] , _a ) def A ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =PriorTransformer.from_pretrained('hf-internal-testing/prior-dummy' ) _SCREAMING_SNAKE_CASE =model.to(_a ) if hasattr(_a , 'set_default_attn_processor' ): model.set_default_attn_processor() _SCREAMING_SNAKE_CASE =self.get_dummy_seed_input() with torch.no_grad(): _SCREAMING_SNAKE_CASE =model(**_a )[0] _SCREAMING_SNAKE_CASE =output[0, :5].flatten().cpu() print(_a ) # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. _SCREAMING_SNAKE_CASE =torch.tensor([-1.34_36, -0.28_70, 0.75_38, 0.43_68, -0.02_39] ) self.assertTrue(torch_all_close(_a , _a , rtol=1e-2 ) ) @slow class A__ ( unittest.TestCase ): def A ( self : Union[str, Any] , _a : Dict=1 , _a : Union[str, Any]=768 , _a : Dict=77 , _a : Optional[Any]=0 ) -> List[Any]: '''simple docstring''' torch.manual_seed(_a ) _SCREAMING_SNAKE_CASE =batch_size _SCREAMING_SNAKE_CASE =embedding_dim _SCREAMING_SNAKE_CASE =num_embeddings _SCREAMING_SNAKE_CASE =torch.randn((batch_size, embedding_dim) ).to(_a ) _SCREAMING_SNAKE_CASE =torch.randn((batch_size, embedding_dim) ).to(_a ) _SCREAMING_SNAKE_CASE =torch.randn((batch_size, num_embeddings, embedding_dim) ).to(_a ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } def A ( self : str ) -> Optional[int]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @parameterized.expand( [ # fmt: off [13, [-0.58_61, 0.12_83, -0.09_31, 0.08_82, 0.44_76, 0.13_29, -0.04_98, 0.06_40]], [37, [-0.49_13, 0.01_10, -0.04_83, 0.05_41, 0.49_54, -0.01_70, 0.03_54, 0.16_51]], # fmt: on ] ) def A ( self : int , _a : Optional[Any] , _a : str ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =PriorTransformer.from_pretrained('kandinsky-community/kandinsky-2-1-prior' , subfolder='prior' ) model.to(_a ) _SCREAMING_SNAKE_CASE =self.get_dummy_seed_input(seed=_a ) with torch.no_grad(): _SCREAMING_SNAKE_CASE =model(**_a )[0] assert list(sample.shape ) == [1, 768] _SCREAMING_SNAKE_CASE =sample[0, :8].flatten().cpu() print(_a ) _SCREAMING_SNAKE_CASE =torch.tensor(_a ) assert torch_all_close(_a , _a , atol=1e-3 )
47
'''simple docstring''' import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets lowerCamelCase : List[Any] = "\\n @inproceedings{kakwani2020indicnlpsuite,\n title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}},\n author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar},\n year={2020},\n booktitle={Findings of EMNLP},\n}\n" lowerCamelCase : Optional[Any] = "\\n IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide\n variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te.\n" lowerCamelCase : int = "\nCompute IndicGLUE evaluation metric associated to each IndicGLUE dataset.\nArgs:\n predictions: list of predictions to score (as int64),\n except for 'cvit-mkb-clsr' where each prediction is a vector (of float32).\n references: list of ground truth labels corresponding to the predictions (as int64),\n except for 'cvit-mkb-clsr' where each reference is a vector (of float32).\nReturns: depending on the IndicGLUE subset, one or several of:\n \"accuracy\": Accuracy\n \"f1\": F1 score\n \"precision\": Precision@10\nExamples:\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr')\n >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'precision@10': 1.0}\n\n" def _lowerCAmelCase ( _UpperCamelCase : List[str] , _UpperCamelCase : Tuple ) -> List[Any]: """simple docstring""" return float((preds == labels).mean() ) def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Any ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =simple_accuracy(_UpperCamelCase , _UpperCamelCase ) _SCREAMING_SNAKE_CASE =float(fa_score(y_true=_UpperCamelCase , y_pred=_UpperCamelCase ) ) return { "accuracy": acc, "f1": fa, } def _lowerCAmelCase ( _UpperCamelCase : Any , _UpperCamelCase : int ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =en_sentvecs.shape[0] # mean centering _SCREAMING_SNAKE_CASE =en_sentvecs - np.mean(_UpperCamelCase , axis=0 ) _SCREAMING_SNAKE_CASE =in_sentvecs - np.mean(_UpperCamelCase , axis=0 ) _SCREAMING_SNAKE_CASE =cdist(_UpperCamelCase , _UpperCamelCase , 'cosine' ) _SCREAMING_SNAKE_CASE =np.array(range(_UpperCamelCase ) ) _SCREAMING_SNAKE_CASE =sim.argsort(axis=1 )[:, :10] _SCREAMING_SNAKE_CASE =np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def A ( self : Any ) -> List[str]: '''simple docstring''' if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('int64' ) if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32' ) ), 'references': datasets.Value('int64' ) if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32' ) ), } ) , codebase_urls=[] , reference_urls=[] , format='numpy' if self.config_name != 'cvit-mkb-clsr' else None , ) def A ( self : List[str] , _a : Tuple , _a : Optional[int] ) -> int: '''simple docstring''' if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(_a , _a )} elif self.config_name in ["wiki-ner"]: return acc_and_fa(_a , _a ) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(_a , _a )} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]' )
47
1
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCamelCase : str = logging.get_logger(__name__) lowerCamelCase : str = {"vocab_file": "sentencepiece.bpe.model"} lowerCamelCase : int = { "vocab_file": { "camembert-base": "https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model", } } lowerCamelCase : str = { "camembert-base": 5_1_2, } lowerCamelCase : List[Any] = "▁" class A__ ( A__ ): A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = ['input_ids', 'attention_mask'] def __init__( self : Optional[Any] , _a : str , _a : Optional[int]="<s>" , _a : Any="</s>" , _a : Tuple="</s>" , _a : Tuple="<s>" , _a : str="<unk>" , _a : Optional[Any]="<pad>" , _a : Optional[Any]="<mask>" , _a : Union[str, Any]=["<s>NOTUSED", "</s>NOTUSED"] , _a : Optional[Dict[str, Any]] = None , **_a : List[str] , ) -> None: '''simple docstring''' _SCREAMING_SNAKE_CASE =AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token _SCREAMING_SNAKE_CASE ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , cls_token=_a , pad_token=_a , mask_token=_a , additional_special_tokens=_a , sp_model_kwargs=self.sp_model_kwargs , **_a , ) _SCREAMING_SNAKE_CASE =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_a ) ) _SCREAMING_SNAKE_CASE =vocab_file # HACK: These tokens were added by fairseq but don't seem to be actually used when duplicated in the actual # sentencepiece vocabulary (this is the case for <s> and </s> _SCREAMING_SNAKE_CASE ={'<s>NOTUSED': 0, '<pad>': 1, '</s>NOTUSED': 2, '<unk>': 3} _SCREAMING_SNAKE_CASE =len(self.fairseq_tokens_to_ids ) _SCREAMING_SNAKE_CASE =len(self.sp_model ) + len(self.fairseq_tokens_to_ids ) _SCREAMING_SNAKE_CASE ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def A ( self : Tuple , _a : List[int] , _a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _SCREAMING_SNAKE_CASE =[self.cls_token_id] _SCREAMING_SNAKE_CASE =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def A ( self : Optional[Any] , _a : List[int] , _a : Optional[List[int]] = None , _a : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def A ( self : Dict , _a : List[int] , _a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =[self.sep_token_id] _SCREAMING_SNAKE_CASE =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def A ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' return len(self.fairseq_tokens_to_ids ) + len(self.sp_model ) def A ( self : Tuple ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE ={self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def A ( self : Optional[int] , _a : str ) -> List[str]: '''simple docstring''' return self.sp_model.encode(_a , out_type=_a ) def A ( self : Optional[int] , _a : Optional[Any] ) -> Optional[Any]: '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] elif self.sp_model.PieceToId(_a ) == 0: # Convert sentence piece unk token to fairseq unk token index return self.unk_token_id return self.fairseq_offset + self.sp_model.PieceToId(_a ) def A ( self : Tuple , _a : Any ) -> str: '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def A ( self : List[Any] , _a : List[Any] ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE ='' _SCREAMING_SNAKE_CASE =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_a ) + token _SCREAMING_SNAKE_CASE =True _SCREAMING_SNAKE_CASE =[] else: current_sub_tokens.append(_a ) _SCREAMING_SNAKE_CASE =False out_string += self.sp_model.decode(_a ) return out_string.strip() def __getstate__( self : str ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.__dict__.copy() _SCREAMING_SNAKE_CASE =None return state def __setstate__( self : Union[str, Any] , _a : Optional[Any] ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): _SCREAMING_SNAKE_CASE ={} _SCREAMING_SNAKE_CASE =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def A ( self : Any , _a : str , _a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(_a ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return _SCREAMING_SNAKE_CASE =os.path.join( _a , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _a ) elif not os.path.isfile(self.vocab_file ): with open(_a , 'wb' ) as fi: _SCREAMING_SNAKE_CASE =self.sp_model.serialized_model_proto() fi.write(_a ) return (out_vocab_file,)
47
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase : Dict = logging.get_logger(__name__) lowerCamelCase : List[Any] = { "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json", } class A__ ( A__ ): A__ = 'deta' A__ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Tuple , _a : Optional[int]=None , _a : int=900 , _a : Optional[Any]=2048 , _a : int=6 , _a : Tuple=2048 , _a : Optional[int]=8 , _a : Any=6 , _a : str=1024 , _a : int=8 , _a : int=0.0 , _a : Optional[Any]=True , _a : Tuple="relu" , _a : Union[str, Any]=256 , _a : Tuple=0.1 , _a : str=0.0 , _a : Dict=0.0 , _a : Tuple=0.02 , _a : Union[str, Any]=1.0 , _a : Any=True , _a : Tuple=False , _a : List[Any]="sine" , _a : str=5 , _a : List[Any]=4 , _a : str=4 , _a : Union[str, Any]=True , _a : Optional[int]=300 , _a : Dict=True , _a : List[Any]=True , _a : List[Any]=1 , _a : List[str]=5 , _a : int=2 , _a : Dict=1 , _a : str=1 , _a : Optional[Any]=5 , _a : Union[str, Any]=2 , _a : List[str]=0.1 , _a : List[Any]=0.25 , **_a : Union[str, Any] , ) -> List[str]: '''simple docstring''' if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) _SCREAMING_SNAKE_CASE =CONFIG_MAPPING['resnet'](out_features=['stage2', 'stage3', 'stage4'] ) else: if isinstance(_a , _a ): _SCREAMING_SNAKE_CASE =backbone_config.pop('model_type' ) _SCREAMING_SNAKE_CASE =CONFIG_MAPPING[backbone_model_type] _SCREAMING_SNAKE_CASE =config_class.from_dict(_a ) _SCREAMING_SNAKE_CASE =backbone_config _SCREAMING_SNAKE_CASE =num_queries _SCREAMING_SNAKE_CASE =max_position_embeddings _SCREAMING_SNAKE_CASE =d_model _SCREAMING_SNAKE_CASE =encoder_ffn_dim _SCREAMING_SNAKE_CASE =encoder_layers _SCREAMING_SNAKE_CASE =encoder_attention_heads _SCREAMING_SNAKE_CASE =decoder_ffn_dim _SCREAMING_SNAKE_CASE =decoder_layers _SCREAMING_SNAKE_CASE =decoder_attention_heads _SCREAMING_SNAKE_CASE =dropout _SCREAMING_SNAKE_CASE =attention_dropout _SCREAMING_SNAKE_CASE =activation_dropout _SCREAMING_SNAKE_CASE =activation_function _SCREAMING_SNAKE_CASE =init_std _SCREAMING_SNAKE_CASE =init_xavier_std _SCREAMING_SNAKE_CASE =encoder_layerdrop _SCREAMING_SNAKE_CASE =auxiliary_loss _SCREAMING_SNAKE_CASE =position_embedding_type # deformable attributes _SCREAMING_SNAKE_CASE =num_feature_levels _SCREAMING_SNAKE_CASE =encoder_n_points _SCREAMING_SNAKE_CASE =decoder_n_points _SCREAMING_SNAKE_CASE =two_stage _SCREAMING_SNAKE_CASE =two_stage_num_proposals _SCREAMING_SNAKE_CASE =with_box_refine _SCREAMING_SNAKE_CASE =assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError('If two_stage is True, with_box_refine must be True.' ) # Hungarian matcher _SCREAMING_SNAKE_CASE =class_cost _SCREAMING_SNAKE_CASE =bbox_cost _SCREAMING_SNAKE_CASE =giou_cost # Loss coefficients _SCREAMING_SNAKE_CASE =mask_loss_coefficient _SCREAMING_SNAKE_CASE =dice_loss_coefficient _SCREAMING_SNAKE_CASE =bbox_loss_coefficient _SCREAMING_SNAKE_CASE =giou_loss_coefficient _SCREAMING_SNAKE_CASE =eos_coefficient _SCREAMING_SNAKE_CASE =focal_alpha super().__init__(is_encoder_decoder=_a , **_a ) @property def A ( self : Dict ) -> int: '''simple docstring''' return self.encoder_attention_heads @property def A ( self : List[Any] ) -> int: '''simple docstring''' return self.d_model def A ( self : Optional[int] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =copy.deepcopy(self.__dict__ ) _SCREAMING_SNAKE_CASE =self.backbone_config.to_dict() _SCREAMING_SNAKE_CASE =self.__class__.model_type return output
47
1
'''simple docstring''' from sklearn.metrics import recall_score import datasets lowerCamelCase : Optional[Any] = "\nRecall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:\nRecall = TP / (TP + FN)\nWhere TP is the true positives and FN is the false negatives.\n" lowerCamelCase : Optional[int] = "\nArgs:\n- **predictions** (`list` of `int`): The predicted labels.\n- **references** (`list` of `int`): The ground truth labels.\n- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None.\n- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.\n- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.\n - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.\n - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n - `'weighted'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall.\n - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.\n- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .\n - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.\n - `0`: If there is a zero division, the return value is `0`.\n - `1`: If there is a zero division, the return value is `1`.\n\nReturns:\n- **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better.\n\nExamples:\n\n Example 1-A simple example with some errors\n >>> recall_metric = datasets.load_metric('recall')\n >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])\n >>> print(results)\n {'recall': 0.6666666666666666}\n\n Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.\n >>> recall_metric = datasets.load_metric('recall')\n >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)\n >>> print(results)\n {'recall': 0.5}\n\n Example 3-The same example as Example 1, but with `sample_weight` included.\n >>> recall_metric = datasets.load_metric('recall')\n >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]\n >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)\n >>> print(results)\n {'recall': 0.55}\n\n Example 4-A multiclass example, using different averages.\n >>> recall_metric = datasets.load_metric('recall')\n >>> predictions = [0, 2, 1, 0, 0, 1]\n >>> references = [0, 1, 2, 0, 1, 2]\n >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')\n >>> print(results)\n {'recall': 0.3333333333333333}\n >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')\n >>> print(results)\n {'recall': 0.3333333333333333}\n >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')\n >>> print(results)\n {'recall': 0.3333333333333333}\n >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)\n >>> print(results)\n {'recall': array([1., 0., 0.])}\n" lowerCamelCase : Dict = "\n@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}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def A ( self : Dict ) -> Union[str, Any]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('int32' ) ), 'references': datasets.Sequence(datasets.Value('int32' ) ), } if self.config_name == 'multilabel' else { 'predictions': datasets.Value('int32' ), 'references': datasets.Value('int32' ), } ) , reference_urls=['https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html'] , ) def A ( self : Optional[int] , _a : int , _a : Optional[Any] , _a : Union[str, Any]=None , _a : Union[str, Any]=1 , _a : List[str]="binary" , _a : Union[str, Any]=None , _a : Dict="warn" , ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =recall_score( _a , _a , labels=_a , pos_label=_a , average=_a , sample_weight=_a , zero_division=_a , ) return {"recall": float(_a ) if score.size == 1 else score}
47
'''simple docstring''' import numpy as np from PIL import Image def _lowerCAmelCase ( _UpperCamelCase : np.ndarray , _UpperCamelCase : int , _UpperCamelCase : int ) -> np.ndarray: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 # compute the shape of the output matrix _SCREAMING_SNAKE_CASE =(arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape _SCREAMING_SNAKE_CASE =np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix _SCREAMING_SNAKE_CASE =np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 return updated_arr def _lowerCAmelCase ( _UpperCamelCase : np.ndarray , _UpperCamelCase : int , _UpperCamelCase : int ) -> np.ndarray: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 # compute the shape of the output matrix _SCREAMING_SNAKE_CASE =(arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape _SCREAMING_SNAKE_CASE =np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix _SCREAMING_SNAKE_CASE =int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name="avgpooling", verbose=True) # Loading the image lowerCamelCase : Optional[Any] = Image.open("path_to_image") # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
47
1
'''simple docstring''' import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class A__ ( A__ ): def __init__( self : str , *_a : Optional[Any] , _a : Union[str, Any]=None , _a : Union[str, Any]=None , **_a : List[Any] ) -> str: '''simple docstring''' super().__init__(*_a , **_a ) _SCREAMING_SNAKE_CASE =eval_examples _SCREAMING_SNAKE_CASE =post_process_function def A ( self : Union[str, Any] , _a : Optional[Dataset] = None , _a : List[str]=None , _a : Optional[List[str]] = None , _a : str = "eval" , **_a : Tuple , ) -> Dict[str, float]: '''simple docstring''' _SCREAMING_SNAKE_CASE =gen_kwargs.copy() _SCREAMING_SNAKE_CASE =( gen_kwargs['max_length'] if gen_kwargs.get('max_length' ) is not None else self.args.generation_max_length ) _SCREAMING_SNAKE_CASE =( gen_kwargs['num_beams'] if gen_kwargs.get('num_beams' ) is not None else self.args.generation_num_beams ) _SCREAMING_SNAKE_CASE =gen_kwargs _SCREAMING_SNAKE_CASE =self.eval_dataset if eval_dataset is None else eval_dataset _SCREAMING_SNAKE_CASE =self.get_eval_dataloader(_a ) _SCREAMING_SNAKE_CASE =self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. _SCREAMING_SNAKE_CASE =self.compute_metrics _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =time.time() _SCREAMING_SNAKE_CASE =self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: _SCREAMING_SNAKE_CASE =eval_loop( _a , description='Evaluation' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_a , metric_key_prefix=_a , ) finally: _SCREAMING_SNAKE_CASE =compute_metrics _SCREAMING_SNAKE_CASE =self.args.eval_batch_size * self.args.world_size if f"{metric_key_prefix}_jit_compilation_time" in output.metrics: start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"] output.metrics.update( speed_metrics( _a , _a , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default _SCREAMING_SNAKE_CASE =self.post_process_function(_a , _a , _a ) _SCREAMING_SNAKE_CASE =self.compute_metrics(_a ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"{metric_key_prefix}_" ): _SCREAMING_SNAKE_CASE =metrics.pop(_a ) metrics.update(output.metrics ) else: _SCREAMING_SNAKE_CASE =output.metrics if self.args.should_log: # Only the main node log the results by default self.log(_a ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) _SCREAMING_SNAKE_CASE =self.callback_handler.on_evaluate(self.args , self.state , self.control , _a ) return metrics def A ( self : Tuple , _a : Optional[int] , _a : List[Any] , _a : int=None , _a : str = "test" , **_a : Tuple ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =gen_kwargs.copy() _SCREAMING_SNAKE_CASE =self.get_test_dataloader(_a ) # Temporarily disable metric computation, we will do it in the loop here. _SCREAMING_SNAKE_CASE =self.compute_metrics _SCREAMING_SNAKE_CASE =None _SCREAMING_SNAKE_CASE =time.time() _SCREAMING_SNAKE_CASE =self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: _SCREAMING_SNAKE_CASE =eval_loop( _a , description='Prediction' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_a , metric_key_prefix=_a , ) finally: _SCREAMING_SNAKE_CASE =compute_metrics _SCREAMING_SNAKE_CASE =self.args.eval_batch_size * self.args.world_size if f"{metric_key_prefix}_jit_compilation_time" in output.metrics: start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"] output.metrics.update( speed_metrics( _a , _a , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output _SCREAMING_SNAKE_CASE =self.post_process_function(_a , _a , _a , 'predict' ) _SCREAMING_SNAKE_CASE =self.compute_metrics(_a ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"{metric_key_prefix}_" ): _SCREAMING_SNAKE_CASE =metrics.pop(_a ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=_a )
47
'''simple docstring''' import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _lowerCAmelCase ( ) -> Any: """simple docstring""" _SCREAMING_SNAKE_CASE =ArgumentParser( description=( 'PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes' ) ) # Optional arguments for the launch helper parser.add_argument('--num_cores' , type=_UpperCamelCase , default=1 , help='Number of TPU cores to use (1 or 8).' ) # positional parser.add_argument( 'training_script' , type=_UpperCamelCase , help=( 'The full path to the single TPU training ' 'program/script to be launched in parallel, ' 'followed by all the arguments for the ' 'training script' ) , ) # rest from the training program parser.add_argument('training_script_args' , nargs=_UpperCamelCase ) return parser.parse_args() def _lowerCAmelCase ( ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =parse_args() # Import training_script as a module. _SCREAMING_SNAKE_CASE =Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) _SCREAMING_SNAKE_CASE =script_fpath.stem _SCREAMING_SNAKE_CASE =importlib.import_module(_UpperCamelCase ) # Patch sys.argv _SCREAMING_SNAKE_CASE =[args.training_script] + args.training_script_args + ['--tpu_num_cores', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
47
1
'''simple docstring''' from __future__ import annotations from collections import namedtuple def _lowerCAmelCase ( _UpperCamelCase : float , _UpperCamelCase : float , _UpperCamelCase : float ) -> tuple: """simple docstring""" _SCREAMING_SNAKE_CASE =namedtuple('result' , 'name value' ) if (voltage, current, power).count(0 ) != 1: raise ValueError('Only one argument must be 0' ) elif power < 0: raise ValueError( 'Power cannot be negative in any electrical/electronics system' ) elif voltage == 0: return result('voltage' , power / current ) elif current == 0: return result('current' , power / voltage ) elif power == 0: return result('power' , float(round(abs(voltage * current ) , 2 ) ) ) else: raise ValueError('Exactly one argument must be 0' ) if __name__ == "__main__": import doctest doctest.testmod()
47
'''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. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class A__ ( A__ ): A__ = ( 'This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.' 'It takes two arguments named `image` which should be the original image, and `label` which should be a text ' 'describing the elements what should be identified in the segmentation mask. The tool returns the mask.' ) A__ = 'CIDAS/clipseg-rd64-refined' A__ = 'image_segmenter' A__ = CLIPSegForImageSegmentation A__ = ['image', 'text'] A__ = ['image'] def __init__( self : Any , *_a : Dict , **_a : str ) -> Any: '''simple docstring''' requires_backends(self , ['vision'] ) super().__init__(*_a , **_a ) def A ( self : int , _a : "Image" , _a : str ) -> Optional[Any]: '''simple docstring''' return self.pre_processor(text=[label] , images=[image] , padding=_a , return_tensors='pt' ) def A ( self : Dict , _a : Dict ) -> str: '''simple docstring''' with torch.no_grad(): _SCREAMING_SNAKE_CASE =self.model(**_a ).logits return logits def A ( self : Any , _a : str ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =outputs.cpu().detach().numpy() _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =1 return Image.fromarray((array * 255).astype(np.uinta ) )
47
1
'''simple docstring''' import math from collections.abc import Iterator from itertools import takewhile def _lowerCAmelCase ( _UpperCamelCase : int ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_UpperCamelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowerCAmelCase ( ) -> Iterator[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =2 while True: if is_prime(_UpperCamelCase ): yield num num += 1 def _lowerCAmelCase ( _UpperCamelCase : int = 2_00_00_00 ) -> int: """simple docstring""" return sum(takewhile(lambda _UpperCamelCase : x < n , prime_generator() ) ) if __name__ == "__main__": print(f'''{solution() = }''')
47
'''simple docstring''' from __future__ import annotations import math def _lowerCAmelCase ( _UpperCamelCase : int ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_UpperCamelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowerCAmelCase ( _UpperCamelCase : int ) -> list[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =str(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =[n] for i in range(1 , len(_UpperCamelCase ) ): list_nums.append(int(str_num[i:] ) ) list_nums.append(int(str_num[:-i] ) ) return list_nums def _lowerCAmelCase ( _UpperCamelCase : int ) -> bool: """simple docstring""" if len(str(_UpperCamelCase ) ) > 3: if not is_prime(int(str(_UpperCamelCase )[-3:] ) ) or not is_prime(int(str(_UpperCamelCase )[:3] ) ): return False return True def _lowerCAmelCase ( _UpperCamelCase : int = 11 ) -> list[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =13 while len(_UpperCamelCase ) != count: if validate(_UpperCamelCase ): _SCREAMING_SNAKE_CASE =list_truncated_nums(_UpperCamelCase ) if all(is_prime(_UpperCamelCase ) for i in list_nums ): list_truncated_primes.append(_UpperCamelCase ) num += 2 return list_truncated_primes def _lowerCAmelCase ( ) -> int: """simple docstring""" return sum(compute_truncated_primes(11 ) ) if __name__ == "__main__": print(f'''{sum(compute_truncated_primes(1_1)) = }''')
47
1
'''simple docstring''' import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class A__ : def __init__( self : Tuple , _a : Any , _a : int , _a : int ) -> List[str]: '''simple docstring''' if dst_width < 0 or dst_height < 0: raise ValueError('Destination width/height should be > 0' ) _SCREAMING_SNAKE_CASE =img _SCREAMING_SNAKE_CASE =img.shape[1] _SCREAMING_SNAKE_CASE =img.shape[0] _SCREAMING_SNAKE_CASE =dst_width _SCREAMING_SNAKE_CASE =dst_height _SCREAMING_SNAKE_CASE =self.src_w / self.dst_w _SCREAMING_SNAKE_CASE =self.src_h / self.dst_h _SCREAMING_SNAKE_CASE =_SCREAMING_SNAKE_CASE =( np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 255 ) def A ( self : Any ) -> Tuple: '''simple docstring''' for i in range(self.dst_h ): for j in range(self.dst_w ): _SCREAMING_SNAKE_CASE =self.img[self.get_y(_a )][self.get_x(_a )] def A ( self : int , _a : int ) -> int: '''simple docstring''' return int(self.ratio_x * x ) def A ( self : Dict , _a : int ) -> int: '''simple docstring''' return int(self.ratio_y * y ) if __name__ == "__main__": lowerCamelCase , lowerCamelCase : Optional[Any] = 8_0_0, 6_0_0 lowerCamelCase : str = imread("image_data/lena.jpg", 1) lowerCamelCase : Optional[int] = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( f'''Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}''', n.output ) waitKey(0) destroyAllWindows()
47
'''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: lowerCamelCase : int = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class A__ ( unittest.TestCase ): def __init__( self : List[str] , _a : List[Any] , _a : List[str]=7 , _a : List[str]=3 , _a : Tuple=18 , _a : Tuple=30 , _a : str=400 , _a : Tuple=None , _a : Union[str, Any]=True , _a : List[str]=True , _a : Optional[int]=None , ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =size if size is not None else {'height': 20, 'width': 20} _SCREAMING_SNAKE_CASE =parent _SCREAMING_SNAKE_CASE =batch_size _SCREAMING_SNAKE_CASE =num_channels _SCREAMING_SNAKE_CASE =image_size _SCREAMING_SNAKE_CASE =min_resolution _SCREAMING_SNAKE_CASE =max_resolution _SCREAMING_SNAKE_CASE =size _SCREAMING_SNAKE_CASE =do_normalize _SCREAMING_SNAKE_CASE =do_convert_rgb _SCREAMING_SNAKE_CASE =[512, 1024, 2048, 4096] _SCREAMING_SNAKE_CASE =patch_size if patch_size is not None else {'height': 16, 'width': 16} def A ( self : Any ) -> List[str]: '''simple docstring''' return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def A ( self : int ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE ='https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg' _SCREAMING_SNAKE_CASE =Image.open(requests.get(_a , stream=_a ).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 A__ ( A__ , unittest.TestCase ): A__ = PixaStructImageProcessor if is_vision_available() else None def A ( self : Dict ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =PixaStructImageProcessingTester(self ) @property def A ( self : Optional[Any] ) -> int: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def A ( self : Any ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_a , 'do_normalize' ) ) self.assertTrue(hasattr(_a , 'do_convert_rgb' ) ) def A ( self : Any ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processor_tester.prepare_dummy_image() _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) _SCREAMING_SNAKE_CASE =2048 _SCREAMING_SNAKE_CASE =image_processor(_a , return_tensors='pt' , max_patches=_a ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.06_06 ) , atol=1e-3 , rtol=1e-3 ) ) def A ( self : Any ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PIL images _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input _SCREAMING_SNAKE_CASE =( (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 _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def A ( self : List[str] ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PIL images _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input _SCREAMING_SNAKE_CASE =( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 _SCREAMING_SNAKE_CASE =True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(_a ): _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches _SCREAMING_SNAKE_CASE ='Hello' _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a , header_text=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a , header_text=_a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def A ( self : List[Any] ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , numpify=_a ) for image in image_inputs: self.assertIsInstance(_a , np.ndarray ) _SCREAMING_SNAKE_CASE =( (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 _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def A ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , torchify=_a ) for image in image_inputs: self.assertIsInstance(_a , torch.Tensor ) # Test not batched input _SCREAMING_SNAKE_CASE =( (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 _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a ).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 A__ ( A__ , unittest.TestCase ): A__ = PixaStructImageProcessor if is_vision_available() else None def A ( self : str ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =PixaStructImageProcessingTester(self , num_channels=4 ) _SCREAMING_SNAKE_CASE =3 @property def A ( self : List[str] ) -> Optional[Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def A ( self : List[str] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_a , 'do_normalize' ) ) self.assertTrue(hasattr(_a , 'do_convert_rgb' ) ) def A ( self : Dict ) -> int: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.image_processing_class(**self.image_processor_dict ) # create random PIL images _SCREAMING_SNAKE_CASE =prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input _SCREAMING_SNAKE_CASE =( (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 _SCREAMING_SNAKE_CASE =image_processor( image_inputs[0] , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched _SCREAMING_SNAKE_CASE =image_processor( _a , return_tensors='pt' , max_patches=_a ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
47
1