code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : List[str] = logging.get_logger(__name__) a_ : int = { """facebook/wav2vec2-base-960h""": """https://huggingface.co/facebook/wav2vec2-base-960h/resolve/main/config.json""", # See all Wav2Vec2 models at https://huggingface.co/models?filter=wav2vec2 } class _snake_case ( __A ): _lowercase : int = 'wav2vec2' def __init__( self , a=32 , a=768 , a=12 , a=12 , a=3072 , a="gelu" , a=0.1 , a=0.1 , a=0.1 , a=0.0 , a=0.0 , a=0.1 , a=0.1 , a=0.02 , a=1E-5 , a="group" , a="gelu" , a=(512, 512, 512, 512, 512, 512, 512) , a=(5, 2, 2, 2, 2, 2, 2) , a=(10, 3, 3, 3, 3, 2, 2) , a=False , a=128 , a=16 , a=False , a=True , a=0.05 , a=10 , a=2 , a=0.0 , a=10 , a=0 , a=320 , a=2 , a=0.1 , a=100 , a=256 , a=256 , a=0.1 , a="sum" , a=False , a=False , a=256 , a=(512, 512, 512, 512, 1500) , a=(5, 3, 3, 1, 1) , a=(1, 2, 3, 1, 1) , a=512 , a=0 , a=1 , a=2 , a=False , a=3 , a=2 , a=3 , a=None , a=None , **a , ) -> Union[str, Any]: super().__init__(**__lowercase , pad_token_id=__lowercase , bos_token_id=__lowercase , eos_token_id=__lowercase) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = feat_extract_norm SCREAMING_SNAKE_CASE = feat_extract_activation SCREAMING_SNAKE_CASE = list(__lowercase) SCREAMING_SNAKE_CASE = list(__lowercase) SCREAMING_SNAKE_CASE = list(__lowercase) SCREAMING_SNAKE_CASE = conv_bias SCREAMING_SNAKE_CASE = num_conv_pos_embeddings SCREAMING_SNAKE_CASE = num_conv_pos_embedding_groups SCREAMING_SNAKE_CASE = len(self.conv_dim) SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = feat_proj_dropout SCREAMING_SNAKE_CASE = final_dropout SCREAMING_SNAKE_CASE = layerdrop SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = do_stable_layer_norm SCREAMING_SNAKE_CASE = use_weighted_layer_sum if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==' ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =' f''' {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel)}`.''') # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 SCREAMING_SNAKE_CASE = apply_spec_augment SCREAMING_SNAKE_CASE = mask_time_prob SCREAMING_SNAKE_CASE = mask_time_length SCREAMING_SNAKE_CASE = mask_time_min_masks SCREAMING_SNAKE_CASE = mask_feature_prob SCREAMING_SNAKE_CASE = mask_feature_length SCREAMING_SNAKE_CASE = mask_feature_min_masks # parameters for pretraining with codevector quantized representations SCREAMING_SNAKE_CASE = num_codevectors_per_group SCREAMING_SNAKE_CASE = num_codevector_groups SCREAMING_SNAKE_CASE = contrastive_logits_temperature SCREAMING_SNAKE_CASE = feat_quantizer_dropout SCREAMING_SNAKE_CASE = num_negatives SCREAMING_SNAKE_CASE = codevector_dim SCREAMING_SNAKE_CASE = proj_codevector_dim SCREAMING_SNAKE_CASE = diversity_loss_weight # ctc loss SCREAMING_SNAKE_CASE = ctc_loss_reduction SCREAMING_SNAKE_CASE = ctc_zero_infinity # adapter SCREAMING_SNAKE_CASE = add_adapter SCREAMING_SNAKE_CASE = adapter_kernel_size SCREAMING_SNAKE_CASE = adapter_stride SCREAMING_SNAKE_CASE = num_adapter_layers SCREAMING_SNAKE_CASE = output_hidden_size or hidden_size SCREAMING_SNAKE_CASE = adapter_attn_dim # SequenceClassification-specific parameter. Feel free to ignore for other classes. SCREAMING_SNAKE_CASE = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. SCREAMING_SNAKE_CASE = list(__lowercase) SCREAMING_SNAKE_CASE = list(__lowercase) SCREAMING_SNAKE_CASE = list(__lowercase) SCREAMING_SNAKE_CASE = xvector_output_dim @property def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: return functools.reduce(operator.mul , self.conv_stride , 1)
359
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput a_ : Dict = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class _snake_case ( A__ ): def __init__( self , *a , a=None , a=None , a=None , **a) -> List[Any]: super().__init__(*a , **a) SCREAMING_SNAKE_CASE = eval_examples SCREAMING_SNAKE_CASE = post_process_function SCREAMING_SNAKE_CASE = quant_trainer_args SCREAMING_SNAKE_CASE = 128 # default number of calibration samples def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Union[str, Any]: if calib_dataset is None and self.calib_dataset is None: raise ValueError('Trainer: calibration requires an calib_dataset.') SCREAMING_SNAKE_CASE = calib_dataset if calib_dataset is not None else self.calib_dataset SCREAMING_SNAKE_CASE = self._remove_unused_columns(a , description='Calibration') return DataLoader( a , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=a , ) def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.train_dataset if calib_dataset is None else calib_dataset SCREAMING_SNAKE_CASE = self.get_calib_dataloader(a) SCREAMING_SNAKE_CASE = self.model quant_trainer.configure_model(a , self.quant_trainer_args , calib=a) model.eval() quant_trainer.enable_calibration(a) logger.info('***** Running calibration *****') logger.info(f''' Num examples = {self.calib_num}''') logger.info(f''' Batch size = {calib_dataloader.batch_size}''') for step, inputs in enumerate(a): # Prediction step SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.prediction_step(a , a , prediction_loss_only=a) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = model def SCREAMING_SNAKE_CASE__ ( self , a=None , a=None , a=None , a = "eval") -> str: 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 = 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 , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions) 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) self.log(a) else: SCREAMING_SNAKE_CASE = {} 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 SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a = "test") -> Optional[Any]: 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 = 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 , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions , '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) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=a) def SCREAMING_SNAKE_CASE__ ( self , a="./") -> List[Any]: SCREAMING_SNAKE_CASE = self.eval_dataset SCREAMING_SNAKE_CASE = self.get_eval_dataloader(a) SCREAMING_SNAKE_CASE = next(iter(a)) # saving device - to make it consistent SCREAMING_SNAKE_CASE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # convert to tuple SCREAMING_SNAKE_CASE = tuple(v.to(a) for k, v in batch.items()) logger.info('Converting model to be onnx compatible') from pytorch_quantization.nn import TensorQuantizer SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = self.model.to(a) model.eval() model.float() SCREAMING_SNAKE_CASE = model.module if hasattr(a , 'module') else model quant_trainer.configure_model(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = os.path.join(a , 'model.onnx') logger.info(f'''exporting model to {output_model_file}''') SCREAMING_SNAKE_CASE = {0: 'batch_size', 1: 'seq_len'} torch.onnx.export( a , a , a , export_params=a , opset_version=13 , do_constant_folding=a , input_names=['input_ids', 'attention_mask', 'token_type_ids'] , output_names=['output_start_logits', 'output_end_logits'] , dynamic_axes={ 'input_ids': axes, 'attention_mask': axes, 'token_type_ids': axes, 'output_start_logits': axes, 'output_end_logits': axes, } , verbose=a , ) logger.info('onnx export finished')
327
0
"""simple docstring""" import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed a_ : Dict = { 'distilbert': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), 'roberta': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), 'bert': (BertConfig, BertForMaskedLM, BertTokenizer), 'gpt2': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def lowerCamelCase__ (_UpperCAmelCase): assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): if args.student_type == "roberta": SCREAMING_SNAKE_CASE = False elif args.student_type == "gpt2": SCREAMING_SNAKE_CASE = False def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): if args.student_type == "roberta": SCREAMING_SNAKE_CASE = False def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description='Training') parser.add_argument('--force' , action='store_true' , help='Overwrite dump_path if it already exists.') parser.add_argument( '--dump_path' , type=__lowerCamelCase , required=__lowerCamelCase , help='The output directory (log, checkpoints, parameters, etc.)') parser.add_argument( '--data_file' , type=__lowerCamelCase , required=__lowerCamelCase , help='The binarized file (tokenized + tokens_to_ids) and grouped by sequence.' , ) parser.add_argument( '--student_type' , type=__lowerCamelCase , choices=['distilbert', 'roberta', 'gpt2'] , required=__lowerCamelCase , help='The student type (DistilBERT, RoBERTa).' , ) parser.add_argument('--student_config' , type=__lowerCamelCase , required=__lowerCamelCase , help='Path to the student configuration.') parser.add_argument( '--student_pretrained_weights' , default=__lowerCamelCase , type=__lowerCamelCase , help='Load student initialization checkpoint.') parser.add_argument( '--teacher_type' , choices=['bert', 'roberta', 'gpt2'] , required=__lowerCamelCase , help='Teacher type (BERT, RoBERTa).') parser.add_argument('--teacher_name' , type=__lowerCamelCase , required=__lowerCamelCase , help='The teacher model.') parser.add_argument('--temperature' , default=2.0 , type=__lowerCamelCase , help='Temperature for the softmax temperature.') parser.add_argument( '--alpha_ce' , default=0.5 , type=__lowerCamelCase , help='Linear weight for the distillation loss. Must be >=0.') parser.add_argument( '--alpha_mlm' , default=0.0 , type=__lowerCamelCase , help='Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.' , ) parser.add_argument('--alpha_clm' , default=0.5 , type=__lowerCamelCase , help='Linear weight for the CLM loss. Must be >=0.') parser.add_argument('--alpha_mse' , default=0.0 , type=__lowerCamelCase , help='Linear weight of the MSE loss. Must be >=0.') parser.add_argument( '--alpha_cos' , default=0.0 , type=__lowerCamelCase , help='Linear weight of the cosine embedding loss. Must be >=0.') parser.add_argument( '--mlm' , action='store_true' , help='The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.') parser.add_argument( '--mlm_mask_prop' , default=0.15 , type=__lowerCamelCase , help='Proportion of tokens for which we need to make a prediction.' , ) parser.add_argument('--word_mask' , default=0.8 , type=__lowerCamelCase , help='Proportion of tokens to mask out.') parser.add_argument('--word_keep' , default=0.1 , type=__lowerCamelCase , help='Proportion of tokens to keep.') parser.add_argument('--word_rand' , default=0.1 , type=__lowerCamelCase , help='Proportion of tokens to randomly replace.') parser.add_argument( '--mlm_smoothing' , default=0.7 , type=__lowerCamelCase , help='Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).' , ) parser.add_argument('--token_counts' , type=__lowerCamelCase , help='The token counts in the data_file for MLM.') parser.add_argument( '--restrict_ce_to_mask' , action='store_true' , help='If true, compute the distillation loss only the [MLM] prediction distribution.' , ) parser.add_argument( '--freeze_pos_embs' , action='store_true' , help='Freeze positional embeddings during distillation. For student_type in [\'roberta\', \'gpt2\'] only.' , ) parser.add_argument( '--freeze_token_type_embds' , action='store_true' , help='Freeze token type embeddings during distillation if existent. For student_type in [\'roberta\'] only.' , ) parser.add_argument('--n_epoch' , type=__lowerCamelCase , default=3 , help='Number of pass on the whole dataset.') parser.add_argument('--batch_size' , type=__lowerCamelCase , default=5 , help='Batch size (for each process).') parser.add_argument( '--group_by_size' , action='store_false' , help='If true, group sequences that have similar length into the same batch. Default is true.' , ) parser.add_argument( '--gradient_accumulation_steps' , type=__lowerCamelCase , default=50 , help='Gradient accumulation for larger training batches.' , ) parser.add_argument('--warmup_prop' , default=0.05 , type=__lowerCamelCase , help='Linear warmup proportion.') parser.add_argument('--weight_decay' , default=0.0 , type=__lowerCamelCase , help='Weight decay if we apply some.') parser.add_argument('--learning_rate' , default=5e-4 , type=__lowerCamelCase , help='The initial learning rate for Adam.') parser.add_argument('--adam_epsilon' , default=1e-6 , type=__lowerCamelCase , help='Epsilon for Adam optimizer.') parser.add_argument('--max_grad_norm' , default=5.0 , type=__lowerCamelCase , help='Max gradient norm.') parser.add_argument('--initializer_range' , default=0.02 , type=__lowerCamelCase , help='Random initialization range.') parser.add_argument( '--fp16' , action='store_true' , help='Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit' , ) parser.add_argument( '--fp16_opt_level' , type=__lowerCamelCase , default='O1' , help=( 'For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].' 'See details at https://nvidia.github.io/apex/amp.html' ) , ) parser.add_argument('--n_gpu' , type=__lowerCamelCase , default=1 , help='Number of GPUs in the node.') parser.add_argument('--local_rank' , type=__lowerCamelCase , default=-1 , help='Distributed training - Local rank') parser.add_argument('--seed' , type=__lowerCamelCase , default=56 , help='Random seed') parser.add_argument('--log_interval' , type=__lowerCamelCase , default=500 , help='Tensorboard logging interval.') parser.add_argument('--checkpoint_interval' , type=__lowerCamelCase , default=4000 , help='Checkpoint interval.') SCREAMING_SNAKE_CASE = parser.parse_args() sanity_checks(__lowerCamelCase) # ARGS # init_gpu_params(__lowerCamelCase) set_seed(__lowerCamelCase) if args.is_master: if os.path.exists(args.dump_path): if not args.force: raise ValueError( F'''Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite''' ' itUse `--force` if you want to overwrite it') else: shutil.rmtree(args.dump_path) if not os.path.exists(args.dump_path): os.makedirs(args.dump_path) logger.info(F'''Experiment will be dumped and logged in {args.dump_path}''') # SAVE PARAMS # logger.info(F'''Param: {args}''') with open(os.path.join(args.dump_path , 'parameters.json') , 'w') as f: json.dump(vars(__lowerCamelCase) , __lowerCamelCase , indent=4) git_log(args.dump_path) SCREAMING_SNAKE_CASE = MODEL_CLASSES[args.student_type] SCREAMING_SNAKE_CASE = MODEL_CLASSES[args.teacher_type] # TOKENIZER # SCREAMING_SNAKE_CASE = teacher_tokenizer_class.from_pretrained(args.teacher_name) SCREAMING_SNAKE_CASE = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): SCREAMING_SNAKE_CASE = tokenizer.all_special_tokens.index(__lowerCamelCase) SCREAMING_SNAKE_CASE = tokenizer.all_special_ids[idx] logger.info(F'''Special tokens {special_tok_ids}''') SCREAMING_SNAKE_CASE = special_tok_ids SCREAMING_SNAKE_CASE = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(F'''Loading data from {args.data_file}''') with open(args.data_file , 'rb') as fp: SCREAMING_SNAKE_CASE = pickle.load(__lowerCamelCase) if args.mlm: logger.info(F'''Loading token counts from {args.token_counts} (already pre-computed)''') with open(args.token_counts , 'rb') as fp: SCREAMING_SNAKE_CASE = pickle.load(__lowerCamelCase) SCREAMING_SNAKE_CASE = np.maximum(__lowerCamelCase , 1) ** -args.mlm_smoothing for idx in special_tok_ids.values(): SCREAMING_SNAKE_CASE = 0.0 # do not predict special tokens SCREAMING_SNAKE_CASE = torch.from_numpy(__lowerCamelCase) else: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = LmSeqsDataset(params=__lowerCamelCase , data=__lowerCamelCase) logger.info('Data loader created.') # STUDENT # logger.info(F'''Loading student config from {args.student_config}''') SCREAMING_SNAKE_CASE = student_config_class.from_pretrained(args.student_config) SCREAMING_SNAKE_CASE = True if args.student_pretrained_weights is not None: logger.info(F'''Loading pretrained weights from {args.student_pretrained_weights}''') SCREAMING_SNAKE_CASE = student_model_class.from_pretrained(args.student_pretrained_weights , config=__lowerCamelCase) else: SCREAMING_SNAKE_CASE = student_model_class(__lowerCamelCase) if args.n_gpu > 0: student.to(F'''cuda:{args.local_rank}''') logger.info('Student loaded.') # TEACHER # SCREAMING_SNAKE_CASE = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=__lowerCamelCase) if args.n_gpu > 0: teacher.to(F'''cuda:{args.local_rank}''') logger.info(F'''Teacher loaded from {args.teacher_name}.''') # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(__lowerCamelCase , __lowerCamelCase) if args.freeze_token_type_embds: freeze_token_type_embeddings(__lowerCamelCase , __lowerCamelCase) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() SCREAMING_SNAKE_CASE = Distiller( params=__lowerCamelCase , dataset=__lowerCamelCase , token_probs=__lowerCamelCase , student=__lowerCamelCase , teacher=__lowerCamelCase) distiller.train() logger.info('Let\'s go get some drinks.') if __name__ == "__main__": main()
360
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging a_ : Union[str, Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : List[str] = ['''pixel_values'''] def __init__( self , a = True , a = 1 / 255 , a = True , a = 8 , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = do_rescale SCREAMING_SNAKE_CASE = rescale_factor SCREAMING_SNAKE_CASE = do_pad SCREAMING_SNAKE_CASE = pad_size def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a) -> np.ndarray: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_image_size(a) SCREAMING_SNAKE_CASE = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE = (old_width // size + 1) * size - old_width return pad(a , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> List[str]: 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_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE = pad_size if pad_size is not None else self.pad_size 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_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE = [to_numpy_array(a) for image in images] if do_rescale: SCREAMING_SNAKE_CASE = [self.rescale(image=a , scale=a) for image in images] if do_pad: SCREAMING_SNAKE_CASE = [self.pad(a , size=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)
327
0
a_ : List[Any] = { 'meter': 'm', 'kilometer': 'km', 'megametre': 'Mm', 'gigametre': 'Gm', 'terametre': 'Tm', 'petametre': 'Pm', 'exametre': 'Em', 'zettametre': 'Zm', 'yottametre': 'Ym', } # Exponent of the factor(meter) a_ : int = { 'm': 0, 'km': 3, 'Mm': 6, 'Gm': 9, 'Tm': 12, 'Pm': 15, 'Em': 18, 'Zm': 21, 'Ym': 24, } def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = from_type.lower().strip('s') SCREAMING_SNAKE_CASE = to_type.lower().strip('s') SCREAMING_SNAKE_CASE = UNIT_SYMBOL.get(lowerCAmelCase__ , lowerCAmelCase__) SCREAMING_SNAKE_CASE = UNIT_SYMBOL.get(lowerCAmelCase__ , lowerCAmelCase__) if from_sanitized not in METRIC_CONVERSION: SCREAMING_SNAKE_CASE = ( F'''Invalid \'from_type\' value: {from_type!r}.\n''' F'''Conversion abbreviations are: {', '.join(lowerCAmelCase__)}''' ) raise ValueError(lowerCAmelCase__) if to_sanitized not in METRIC_CONVERSION: SCREAMING_SNAKE_CASE = ( F'''Invalid \'to_type\' value: {to_type!r}.\n''' F'''Conversion abbreviations are: {', '.join(lowerCAmelCase__)}''' ) raise ValueError(lowerCAmelCase__) SCREAMING_SNAKE_CASE = METRIC_CONVERSION[from_sanitized] SCREAMING_SNAKE_CASE = METRIC_CONVERSION[to_sanitized] SCREAMING_SNAKE_CASE = 1 if from_exponent > to_exponent: SCREAMING_SNAKE_CASE = from_exponent - to_exponent else: SCREAMING_SNAKE_CASE = -(to_exponent - from_exponent) return value * pow(10 , lowerCAmelCase__) if __name__ == "__main__": from doctest import testmod testmod()
361
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class _snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = TFCamembertModel.from_pretrained('jplu/tf-camembert-base') SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 2_5543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" SCREAMING_SNAKE_CASE = model(a)['last_hidden_state'] SCREAMING_SNAKE_CASE = tf.TensorShape((1, 10, 768)) self.assertEqual(output.shape , a) # compare the actual values for a slice. SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[[-0.02_54, 0.02_35, 0.10_27], [0.06_06, -0.18_11, -0.04_18], [-0.15_61, -0.11_27, 0.26_87]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4))
327
0
from random import shuffle import tensorflow as tf from numpy import array def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = int(lowercase__) assert noofclusters < len(lowercase__) # Find out the dimensionality SCREAMING_SNAKE_CASE = len(vectors[0]) # Will help select random centroids from among the available vectors SCREAMING_SNAKE_CASE = list(range(len(lowercase__))) shuffle(lowercase__) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. SCREAMING_SNAKE_CASE = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION SCREAMING_SNAKE_CASE = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points SCREAMING_SNAKE_CASE = [ tf.Variable(vectors[vector_indices[i]]) for i in range(lowercase__) ] ##These nodes will assign the centroid Variables the appropriate ##values SCREAMING_SNAKE_CASE = tf.placeholder('float64' , [dim]) SCREAMING_SNAKE_CASE = [] for centroid in centroids: cent_assigns.append(tf.assign(lowercase__ , lowercase__)) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) SCREAMING_SNAKE_CASE = [tf.Variable(0) for i in range(len(lowercase__))] ##These nodes will assign an assignment Variable the appropriate ##value SCREAMING_SNAKE_CASE = tf.placeholder('int32') SCREAMING_SNAKE_CASE = [] for assignment in assignments: cluster_assigns.append(tf.assign(lowercase__ , lowercase__)) ##Now lets construct the node that will compute the mean # The placeholder for the input SCREAMING_SNAKE_CASE = tf.placeholder('float' , [None, dim]) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors SCREAMING_SNAKE_CASE = tf.reduce_mean(lowercase__ , 0) ##Node for computing Euclidean distances # Placeholders for input SCREAMING_SNAKE_CASE = tf.placeholder('float' , [dim]) SCREAMING_SNAKE_CASE = tf.placeholder('float' , [dim]) SCREAMING_SNAKE_CASE = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(lowercase__ , lowercase__) , 2))) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input SCREAMING_SNAKE_CASE = tf.placeholder('float' , [noofclusters]) SCREAMING_SNAKE_CASE = tf.argmin(lowercase__ , 0) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. SCREAMING_SNAKE_CASE = tf.initialize_all_variables() # Initialize all variables sess.run(lowercase__) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. SCREAMING_SNAKE_CASE = 100 for _ in range(lowercase__): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(lowercase__)): SCREAMING_SNAKE_CASE = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. SCREAMING_SNAKE_CASE = [ sess.run(lowercase__ , feed_dict={va: vect, va: sess.run(lowercase__)}) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input SCREAMING_SNAKE_CASE = sess.run( lowercase__ , feed_dict={centroid_distances: distances}) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n] , feed_dict={assignment_value: assignment}) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(lowercase__): # Collect all the vectors assigned to this cluster SCREAMING_SNAKE_CASE = [ vectors[i] for i in range(len(lowercase__)) if sess.run(assignments[i]) == cluster_n ] # Compute new centroid location SCREAMING_SNAKE_CASE = sess.run( lowercase__ , feed_dict={mean_input: array(lowercase__)}) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n] , feed_dict={centroid_value: new_location}) # Return centroids and assignments SCREAMING_SNAKE_CASE = sess.run(lowercase__) SCREAMING_SNAKE_CASE = sess.run(lowercase__) return centroids, assignments
362
from scipy.stats import pearsonr import datasets a_ : Optional[int] = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n' a_ : Optional[int] = '\nArgs:\n predictions (`list` of `int`): Predicted class labels, as returned by a model.\n references (`list` of `int`): Ground truth labels.\n return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n Example 1-A simple example using only predictions and references.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n\n Example 2-The same as Example 1, but that also returns the `p-value`.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n >>> print(sorted(list(results.keys())))\n [\'p-value\', \'pearsonr\']\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n >>> print(round(results[\'p-value\'], 2))\n 0.15\n' a_ : Any = '\n@article{2020SciPy-NMeth,\nauthor = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Antonio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\njournal = {Nature Methods},\nyear = {2020},\nvolume = {17},\npages = {261--272},\nadsurl = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('float'), 'references': datasets.Value('float'), }) , reference_urls=['https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=False) -> Optional[Any]: if return_pvalue: SCREAMING_SNAKE_CASE = pearsonr(a , a) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(a , a)[0])}
327
0
import os import random import sys from . import cryptomath_module as cryptoMath # noqa: N812 from . import rabin_miller as rabinMiller # noqa: N812 def lowerCamelCase__ (): print('Making key files...') make_key_files('rsa' , 1024) print('Key files generation successful.') def lowerCamelCase__ (_UpperCAmelCase): print('Generating prime p...') SCREAMING_SNAKE_CASE = rabinMiller.generate_large_prime(_lowerCamelCase) print('Generating prime q...') SCREAMING_SNAKE_CASE = rabinMiller.generate_large_prime(_lowerCamelCase) SCREAMING_SNAKE_CASE = p * q print('Generating e that is relatively prime to (p - 1) * (q - 1)...') while True: SCREAMING_SNAKE_CASE = random.randrange(2 ** (key_size - 1) , 2 ** (key_size)) if cryptoMath.gcd(_lowerCamelCase , (p - 1) * (q - 1)) == 1: break print('Calculating d that is mod inverse of e...') SCREAMING_SNAKE_CASE = cryptoMath.find_mod_inverse(_lowerCamelCase , (p - 1) * (q - 1)) SCREAMING_SNAKE_CASE = (n, e) SCREAMING_SNAKE_CASE = (n, d) return (public_key, private_key) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): if os.path.exists(F'''{name}_pubkey.txt''') or os.path.exists(F'''{name}_privkey.txt'''): print('\nWARNING:') print( F'''"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n''' 'Use a different name or delete these files and re-run this program.') sys.exit() SCREAMING_SNAKE_CASE = generate_key(_lowerCamelCase) print(F'''\nWriting public key to file {name}_pubkey.txt...''') with open(F'''{name}_pubkey.txt''' , 'w') as out_file: out_file.write(F'''{key_size},{public_key[0]},{public_key[1]}''') print(F'''Writing private key to file {name}_privkey.txt...''') with open(F'''{name}_privkey.txt''' , 'w') as out_file: out_file.write(F'''{key_size},{private_key[0]},{private_key[1]}''') if __name__ == "__main__": main()
363
import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class _snake_case ( unittest.TestCase ): _lowercase : List[Any] = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING _lowercase : int = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Any: SCREAMING_SNAKE_CASE = TextaTextGenerationPipeline(model=a , tokenizer=a) return generator, ["Something to write", "Something else"] def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Any: SCREAMING_SNAKE_CASE = generator('Something there') self.assertEqual(a , [{'generated_text': ANY(a)}]) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]['generated_text'].startswith('Something there')) SCREAMING_SNAKE_CASE = generator(['This is great !', 'Something else'] , num_return_sequences=2 , do_sample=a) self.assertEqual( a , [ [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], ] , ) SCREAMING_SNAKE_CASE = generator( ['This is great !', 'Something else'] , num_return_sequences=2 , batch_size=2 , do_sample=a) self.assertEqual( a , [ [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], ] , ) with self.assertRaises(a): generator(4) @require_torch def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='pt') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE = generator('Something there' , do_sample=a) self.assertEqual(a , [{'generated_text': ''}]) SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = generator( 'Something there' , num_return_sequences=a , num_beams=a , ) SCREAMING_SNAKE_CASE = [ {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': ''}, ] self.assertEqual(a , a) SCREAMING_SNAKE_CASE = generator('This is a test' , do_sample=a , num_return_sequences=2 , return_tensors=a) self.assertEqual( a , [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ] , ) SCREAMING_SNAKE_CASE = generator.model.config.eos_token_id SCREAMING_SNAKE_CASE = '<pad>' SCREAMING_SNAKE_CASE = generator( ['This is a test', 'This is a second test'] , do_sample=a , num_return_sequences=2 , batch_size=2 , return_tensors=a , ) self.assertEqual( a , [ [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ], [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ], ] , ) @require_tf def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='tf') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE = generator('Something there' , do_sample=a) self.assertEqual(a , [{'generated_text': ''}])
327
0
import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate a_ : Optional[Any] = trt.Logger(trt.Logger.WARNING) a_ : Union[str, Any] = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) a_ : Optional[int] = logging.getLogger(__name__) a_ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '--onnx_model_path', default=None, type=str, required=True, help='Path to ONNX model: ', ) parser.add_argument( '--output_dir', default=None, type=str, required=True, help='The output directory where the model checkpoints and predictions will be written.', ) # Other parameters parser.add_argument( '--tokenizer_name', default='', type=str, required=True, help='Pretrained tokenizer name or path if not the same as model_name', ) parser.add_argument( '--version_2_with_negative', action='store_true', help='If true, the SQuAD examples contain some that do not have an answer.', ) parser.add_argument( '--null_score_diff_threshold', type=float, default=0.0, help='If null_score - best_non_null is greater than the threshold predict null.', ) parser.add_argument( '--max_seq_length', default=3_84, type=int, help=( 'The maximum total input sequence length after WordPiece tokenization. Sequences ' 'longer than this will be truncated, and sequences shorter than this will be padded.' ), ) parser.add_argument( '--doc_stride', default=1_28, type=int, help='When splitting up a long document into chunks, how much stride to take between chunks.', ) parser.add_argument('--per_device_eval_batch_size', default=8, type=int, help='Batch size per GPU/CPU for evaluation.') parser.add_argument( '--n_best_size', default=20, type=int, help='The total number of n-best predictions to generate in the nbest_predictions.json output file.', ) parser.add_argument( '--max_answer_length', default=30, type=int, help=( 'The maximum length of an answer that can be generated. This is needed because the start ' 'and end predictions are not conditioned on one another.' ), ) parser.add_argument('--seed', type=int, default=42, help='random seed for initialization') parser.add_argument( '--dataset_name', type=str, default=None, required=True, help='The name of the dataset to use (via the datasets library).', ) parser.add_argument( '--dataset_config_name', type=str, default=None, help='The configuration name of the dataset to use (via the datasets library).', ) parser.add_argument( '--preprocessing_num_workers', type=int, default=4, help='A csv or a json file containing the training data.' ) parser.add_argument('--overwrite_cache', action='store_true', help='Overwrite the cached training and evaluation sets') parser.add_argument( '--fp16', action='store_true', help='Whether to use 16-bit (mixed) precision instead of 32-bit', ) parser.add_argument( '--int8', action='store_true', help='Whether to use INT8', ) a_ : List[Any] = parser.parse_args() if args.tokenizer_name: a_ : int = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( 'You are instantiating a new tokenizer from scratch. This is not supported by this script.' 'You can do it from another script, save it, and load it from here, using --tokenizer_name.' ) logger.info('Training/evaluation parameters %s', args) a_ : Any = args.per_device_eval_batch_size a_ : Optional[int] = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties a_ : Optional[int] = True a_ : Optional[int] = 'temp_engine/bert-fp32.engine' if args.fpaa: a_ : List[str] = 'temp_engine/bert-fp16.engine' if args.inta: a_ : str = 'temp_engine/bert-int8.engine' # import ONNX file if not os.path.exists('temp_engine'): os.makedirs('temp_engine') a_ : List[str] = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, 'rb') as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network a_ : Any = [network.get_input(i) for i in range(network.num_inputs)] a_ : str = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: a_ : List[str] = 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) a_ : Optional[Any] = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) a_ : Optional[Any] = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, 'wb') as f: f.write(engine.serialize()) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = np.asarray(inputs['input_ids'] , dtype=np.intaa) SCREAMING_SNAKE_CASE = np.asarray(inputs['attention_mask'] , dtype=np.intaa) SCREAMING_SNAKE_CASE = np.asarray(inputs['token_type_ids'] , dtype=np.intaa) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , a_) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , a_) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , a_) # start time SCREAMING_SNAKE_CASE = time.time() # Run inference context.execute_async( bindings=[int(a_) for d_inp in d_inputs] + [int(a_), int(a_)] , stream_handle=stream.handle) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(a_ , a_ , a_) cuda.memcpy_dtoh_async(a_ , a_ , a_) # Synchronize the stream and take time stream.synchronize() # end time SCREAMING_SNAKE_CASE = time.time() SCREAMING_SNAKE_CASE = end_time - start_time SCREAMING_SNAKE_CASE = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. a_ : Tuple = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. a_ : List[Any] = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError('Evaluation requires a dataset name') # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. a_ : int = raw_datasets['validation'].column_names a_ : List[Any] = 'question' if 'question' in column_names else column_names[0] a_ : Union[str, Any] = 'context' if 'context' in column_names else column_names[1] a_ : List[Any] = 'answers' if 'answers' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). a_ : List[str] = tokenizer.padding_side == 'right' if args.max_seq_length > tokenizer.model_max_length: logger.warning( f"""The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the""" f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) a_ : int = min(args.max_seq_length, tokenizer.model_max_length) def lowerCamelCase__ (_UpperCAmelCase): # Some of the questions have lots of whitespace on the left, which is not useful and will make the # truncation of the context fail (the tokenized question will take a lots of space). So we remove that # left whitespace SCREAMING_SNAKE_CASE = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. SCREAMING_SNAKE_CASE = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='only_second' if pad_on_right else 'only_first' , max_length=a_ , stride=args.doc_stride , return_overflowing_tokens=a_ , return_offsets_mapping=a_ , padding='max_length' , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. SCREAMING_SNAKE_CASE = tokenized_examples.pop('overflow_to_sample_mapping') # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. SCREAMING_SNAKE_CASE = [] for i in range(len(tokenized_examples['input_ids'])): # Grab the sequence corresponding to that example (to know what is the context and what is the question). SCREAMING_SNAKE_CASE = tokenized_examples.sequence_ids(a_) SCREAMING_SNAKE_CASE = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. SCREAMING_SNAKE_CASE = sample_mapping[i] tokenized_examples["example_id"].append(examples['id'][sample_index]) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. SCREAMING_SNAKE_CASE = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['offset_mapping'][i]) ] return tokenized_examples a_ : List[Any] = raw_datasets['validation'] # Validation Feature Creation a_ : int = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='Running tokenizer on validation dataset', ) a_ : Tuple = default_data_collator a_ : List[Any] = eval_dataset.remove_columns(['example_id', 'offset_mapping']) a_ : List[Any] = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase="eval"): # Post-processing: we match the start logits and end logits to answers in the original context. SCREAMING_SNAKE_CASE = postprocess_qa_predictions( examples=a_ , features=a_ , predictions=a_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=a_ , ) # Format the result to the format the metric expects. if args.version_2_with_negative: SCREAMING_SNAKE_CASE = [ {'id': k, 'prediction_text': v, 'no_answer_probability': 0.0} for k, v in predictions.items() ] else: SCREAMING_SNAKE_CASE = [{'id': k, 'prediction_text': v} for k, v in predictions.items()] SCREAMING_SNAKE_CASE = [{'id': ex['id'], 'answers': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=a_ , label_ids=a_) a_ : List[Any] = load_metric('squad_v2' if args.version_2_with_negative else 'squad') # Evaluation! logger.info('Loading ONNX model %s for evaluation', args.onnx_model_path) with open(engine_name, 'rb') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def lowerCamelCase__ (_UpperCAmelCase): return trt.volume(engine.get_binding_shape(a_)) * engine.get_binding_dtype(a_).itemsize # Allocate device memory for inputs and outputs. a_ : Union[str, Any] = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer a_ : Dict = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) a_ : Tuple = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) a_ : List[str] = cuda.mem_alloc(h_outputa.nbytes) a_ : Dict = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. a_ : Optional[int] = cuda.Stream() # Evaluation logger.info('***** Running Evaluation *****') logger.info(f""" Num examples = {len(eval_dataset)}""") logger.info(f""" Batch size = {args.per_device_eval_batch_size}""") a_ : Optional[Any] = 0.0 a_ : Optional[int] = 0 a_ : List[str] = timeit.default_timer() a_ : Tuple = None for step, batch in enumerate(eval_dataloader): a_ , a_ : Dict = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 a_ , a_ : str = outputs a_ : str = torch.tensor(start_logits) a_ : Any = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered a_ : Dict = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00) a_ : List[Any] = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00) a_ : List[str] = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) a_ : str = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00) if all_preds is not None: a_ : Tuple = nested_truncate(all_preds, len(eval_dataset)) a_ : Union[str, Any] = timeit.default_timer() - start_time logger.info(' Evaluation done in total %f secs (%f sec per example)', evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info('Average Inference Time = {:.3f} ms'.format(total_time * 10_00 / niter)) logger.info('Total Inference Time = {:.3f} ms'.format(total_time * 10_00)) logger.info('Total Number of Inference = %d', niter) a_ : Dict = post_processing_function(eval_examples, eval_dataset, all_preds) a_ : List[str] = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f"""Evaluation metrics: {eval_metric}""")
364
import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights SCREAMING_SNAKE_CASE = FlaxDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=a , cache_dir=a) SCREAMING_SNAKE_CASE = [t[-1] for t in os.walk(os.path.join(a , os.listdir(a)[0] , 'snapshots'))] SCREAMING_SNAKE_CASE = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith('.bin') for f in files) @slow @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 4 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 4.1_51_47_45) < 1E-3 assert np.abs(np.abs(a , dtype=np.floataa).sum() - 4_99_47.8_75) < 5E-1 SCREAMING_SNAKE_CASE = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]))) assert len(a) == num_samples def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='flax' , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.05_65_24_01)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_38_38_08.2)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_00_39_06)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_37_35_16.75)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_00_39_06)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_37_35_16.75)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = FlaxDDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , set_alpha_to_one=a , steps_offset=1 , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , scheduler=a , safety_checker=a , ) SCREAMING_SNAKE_CASE = scheduler.create_state() SCREAMING_SNAKE_CASE = scheduler_state SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.0_45_04_39_45)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_34_76_93.5)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = jax.random.split(jax.random.PRNGKey(0) , a) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a , ) SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) SCREAMING_SNAKE_CASE = images[2, 0, 256, 10:17, 1] # With memory efficient attention SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a , use_memory_efficient_attention=a , ) SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , jit=a).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) SCREAMING_SNAKE_CASE = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice).max() < 1E-2
327
0
def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = set({'(', '[', '{'}) SCREAMING_SNAKE_CASE = set({')', ']', '}'}) SCREAMING_SNAKE_CASE = {'''{''': '''}''', '''[''': ''']''', '''(''': ''')'''} for i in range(len(__a)): if s[i] in open_brackets: stack.append(s[i]) elif s[i] in closed_brackets and ( len(__a) == 0 or (len(__a) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(__a) == 0 def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = input('Enter sequence of brackets: ') if is_balanced(__a): print(__a , 'is balanced') else: print(__a , 'is not balanced') if __name__ == "__main__": main()
365
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets a_ : Tuple = '\\n@inproceedings{lin-2004-rouge,\n title = "{ROUGE}: A Package for Automatic Evaluation of Summaries",\n author = "Lin, Chin-Yew",\n booktitle = "Text Summarization Branches Out",\n month = jul,\n year = "2004",\n address = "Barcelona, Spain",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W04-1013",\n pages = "74--81",\n}\n' a_ : List[Any] = '\\nROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for\nevaluating automatic summarization and machine translation software in natural language processing.\nThe metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.\n\nNote that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.\n\nThis metrics is a wrapper around Google Research reimplementation of ROUGE:\nhttps://github.com/google-research/google-research/tree/master/rouge\n' a_ : List[str] = '\nCalculates average rouge scores for a list of hypotheses and 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 rouge_types: A list of rouge types to calculate.\n Valid names:\n `"rouge{n}"` (e.g. `"rouge1"`, `"rouge2"`) where: {n} is the n-gram based scoring,\n `"rougeL"`: Longest common subsequence based scoring.\n `"rougeLSum"`: rougeLsum splits text using `"\n"`.\n See details in https://github.com/huggingface/datasets/issues/617\n use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.\n use_aggregator: Return aggregates if this is set to True\nReturns:\n rouge1: rouge_1 (precision, recall, f1),\n rouge2: rouge_2 (precision, recall, f1),\n rougeL: rouge_l (precision, recall, f1),\n rougeLsum: rouge_lsum (precision, recall, f1)\nExamples:\n\n >>> rouge = datasets.load_metric(\'rouge\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> results = rouge.compute(predictions=predictions, references=references)\n >>> print(list(results.keys()))\n [\'rouge1\', \'rouge2\', \'rougeL\', \'rougeLsum\']\n >>> print(results["rouge1"])\n AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))\n >>> print(results["rouge1"].mid.fmeasure)\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence'), 'references': datasets.Value('string' , id='sequence'), }) , codebase_urls=['https://github.com/google-research/google-research/tree/master/rouge'] , reference_urls=[ 'https://en.wikipedia.org/wiki/ROUGE_(metric)', 'https://github.com/google-research/google-research/tree/master/rouge', ] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a=True , a=False) -> Optional[Any]: if rouge_types is None: SCREAMING_SNAKE_CASE = ['rouge1', 'rouge2', 'rougeL', 'rougeLsum'] SCREAMING_SNAKE_CASE = rouge_scorer.RougeScorer(rouge_types=a , use_stemmer=a) if use_aggregator: SCREAMING_SNAKE_CASE = scoring.BootstrapAggregator() else: SCREAMING_SNAKE_CASE = [] for ref, pred in zip(a , a): SCREAMING_SNAKE_CASE = scorer.score(a , a) if use_aggregator: aggregator.add_scores(a) else: scores.append(a) if use_aggregator: SCREAMING_SNAKE_CASE = aggregator.aggregate() else: SCREAMING_SNAKE_CASE = {} for key in scores[0]: SCREAMING_SNAKE_CASE = [score[key] for score in scores] return result
327
0
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() a_ : Tuple = logging.get_logger() @dataclass class _snake_case : _lowercase : nn.Module _lowercase : List[nn.Module] = field(default_factory=__SCREAMING_SNAKE_CASE ) _lowercase : list = field(default_factory=__SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Dict: SCREAMING_SNAKE_CASE = len(list(m.modules())) == 1 or isinstance(__UpperCAmelCase , nn.Convad) or isinstance(__UpperCAmelCase , nn.BatchNormad) if has_not_submodules: self.traced.append(__UpperCAmelCase) def __call__( self , a) -> str: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook)) self.module(__UpperCAmelCase) [x.remove() for x in self.handles] return self @property def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return list(filter(lambda a: len(list(x.state_dict().keys())) > 0 , self.traced)) @dataclass class _snake_case : _lowercase : nn.Module _lowercase : nn.Module _lowercase : int = 1 _lowercase : List = field(default_factory=__SCREAMING_SNAKE_CASE ) _lowercase : List = field(default_factory=__SCREAMING_SNAKE_CASE ) _lowercase : bool = True def __call__( self , a) -> Any: SCREAMING_SNAKE_CASE = Tracker(self.dest)(__UpperCAmelCase).parametrized SCREAMING_SNAKE_CASE = Tracker(self.src)(__UpperCAmelCase).parametrized SCREAMING_SNAKE_CASE = list(filter(lambda a: type(__UpperCAmelCase) not in self.src_skip , __UpperCAmelCase)) SCREAMING_SNAKE_CASE = list(filter(lambda a: type(__UpperCAmelCase) not in self.dest_skip , __UpperCAmelCase)) if len(__UpperCAmelCase) != len(__UpperCAmelCase) and self.raise_if_mismatch: raise Exception( f'''Numbers of operations are different. Source module has {len(__UpperCAmelCase)} operations while''' f''' destination module has {len(__UpperCAmelCase)}.''') for dest_m, src_m in zip(__UpperCAmelCase , __UpperCAmelCase): dest_m.load_state_dict(src_m.state_dict()) if self.verbose == 1: print(f'''Transfered from={src_m} to={dest_m}''') class _snake_case ( nn.Module ): def __init__( self , a) -> Optional[int]: super().__init__() SCREAMING_SNAKE_CASE = [] # - get the stem feature_blocks.append(('conv1', model.stem)) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block'), f'''Unexpected layer name {k}''' SCREAMING_SNAKE_CASE = len(__UpperCAmelCase) + 1 feature_blocks.append((f'''res{block_index}''', v)) SCREAMING_SNAKE_CASE = nn.ModuleDict(__UpperCAmelCase) def SCREAMING_SNAKE_CASE__ ( self , a) -> List[Any]: return get_trunk_forward_outputs( __UpperCAmelCase , out_feat_keys=__UpperCAmelCase , feature_blocks=self._feature_blocks , ) class _snake_case ( __SCREAMING_SNAKE_CASE ): def SCREAMING_SNAKE_CASE__ ( self , a) -> str: SCREAMING_SNAKE_CASE = x.split('-') return x_split[0] + x_split[1] + "_" + "".join(x_split[2:]) def __getitem__( self , a) -> Callable[[], Tuple[nn.Module, Dict]]: # default to timm! if x not in self: SCREAMING_SNAKE_CASE = self.convert_name_to_timm(__UpperCAmelCase) SCREAMING_SNAKE_CASE = partial(lambda: (timm.create_model(__UpperCAmelCase , pretrained=__UpperCAmelCase).eval(), None)) else: SCREAMING_SNAKE_CASE = super().__getitem__(__UpperCAmelCase) return val class _snake_case ( __SCREAMING_SNAKE_CASE ): def __getitem__( self , a) -> Callable[[], nn.Module]: if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE = RegNetModel else: SCREAMING_SNAKE_CASE = RegNetForImageClassification return val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for from_key, to_key in keys: SCREAMING_SNAKE_CASE = from_state_dict[from_key].clone() print(F'''Copied key={from_key} to={to_key}''') return to_state_dict def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = True , ): print(F'''Converting {name}...''') with torch.no_grad(): SCREAMING_SNAKE_CASE = from_model_func() SCREAMING_SNAKE_CASE = our_model_func(lowerCAmelCase__).eval() SCREAMING_SNAKE_CASE = ModuleTransfer(src=lowerCAmelCase__ , dest=lowerCAmelCase__ , raise_if_mismatch=lowerCAmelCase__) SCREAMING_SNAKE_CASE = torch.randn((1, 3, 224, 224)) module_transfer(lowerCAmelCase__) if from_state_dict is not None: SCREAMING_SNAKE_CASE = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE = [("""0.clf.0.weight""", """classifier.1.weight"""), ("""0.clf.0.bias""", """classifier.1.bias""")] SCREAMING_SNAKE_CASE = manually_copy_vissl_head(lowerCAmelCase__ , our_model.state_dict() , lowerCAmelCase__) our_model.load_state_dict(lowerCAmelCase__) SCREAMING_SNAKE_CASE = our_model(lowerCAmelCase__ , output_hidden_states=lowerCAmelCase__) SCREAMING_SNAKE_CASE = ( our_outputs.logits if isinstance(lowerCAmelCase__ , lowerCAmelCase__) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE = from_model(lowerCAmelCase__) SCREAMING_SNAKE_CASE = from_output[-1] if type(lowerCAmelCase__) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE = our_outputs.hidden_states[-1] assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add model' , use_temp_dir=lowerCAmelCase__ , ) SCREAMING_SNAKE_CASE = 224 if """seer""" not in name else 384 # we can use the convnext one SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' , size=lowerCAmelCase__) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add image processor' , use_temp_dir=lowerCAmelCase__ , ) print(F'''Pushed {name}''') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = None , _UpperCAmelCase = True): SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE = 1000 SCREAMING_SNAKE_CASE = (1, num_labels) SCREAMING_SNAKE_CASE = """huggingface/label-files""" SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = json.load(open(cached_download(hf_hub_url(lowerCAmelCase__ , lowerCAmelCase__ , repo_type='dataset')) , 'r')) SCREAMING_SNAKE_CASE = {int(lowerCAmelCase__): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = idalabel SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = partial(lowerCAmelCase__ , num_labels=lowerCAmelCase__ , idalabel=lowerCAmelCase__ , labelaid=lowerCAmelCase__) SCREAMING_SNAKE_CASE = { """regnet-x-002""": ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 , layer_type='x'), """regnet-x-004""": ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 160, 384] , groups_width=16 , layer_type='x'), """regnet-x-006""": ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 240, 528] , groups_width=24 , layer_type='x'), """regnet-x-008""": ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 128, 288, 672] , groups_width=16 , layer_type='x'), """regnet-x-016""": ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 168, 408, 912] , groups_width=24 , layer_type='x'), """regnet-x-032""": ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 192, 432, 1008] , groups_width=48 , layer_type='x'), """regnet-x-040""": ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 240, 560, 1360] , groups_width=40 , layer_type='x'), """regnet-x-064""": ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 392, 784, 1624] , groups_width=56 , layer_type='x'), """regnet-x-080""": ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 240, 720, 1920] , groups_width=120 , layer_type='x'), """regnet-x-120""": ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2240] , groups_width=112 , layer_type='x'), """regnet-x-160""": ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[256, 512, 896, 2048] , groups_width=128 , layer_type='x'), """regnet-x-320""": ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[336, 672, 1344, 2520] , groups_width=168 , layer_type='x'), # y variant """regnet-y-002""": ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8), """regnet-y-004""": ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 104, 208, 440] , groups_width=8), """regnet-y-006""": ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 112, 256, 608] , groups_width=16), """regnet-y-008""": ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 128, 320, 768] , groups_width=16), """regnet-y-016""": ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 120, 336, 888] , groups_width=24), """regnet-y-032""": ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 216, 576, 1512] , groups_width=24), """regnet-y-040""": ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[128, 192, 512, 1088] , groups_width=64), """regnet-y-064""": ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[144, 288, 576, 1296] , groups_width=72), """regnet-y-080""": ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 448, 896, 2016] , groups_width=56), """regnet-y-120""": ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2240] , groups_width=112), """regnet-y-160""": ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[224, 448, 1232, 3024] , groups_width=112), """regnet-y-320""": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232), # models created by SEER -> https://arxiv.org/abs/2202.08360 """regnet-y-320-seer""": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232), """regnet-y-640-seer""": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1968, 4920] , groups_width=328), """regnet-y-1280-seer""": RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1056, 2904, 7392] , groups_width=264), """regnet-y-2560-seer""": RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1696, 2544, 5088] , groups_width=640), """regnet-y-10b-seer""": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2020, 4040, 1_1110, 2_8280] , groups_width=1010), # finetuned on imagenet """regnet-y-320-seer-in1k""": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232), """regnet-y-640-seer-in1k""": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1968, 4920] , groups_width=328), """regnet-y-1280-seer-in1k""": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1056, 2904, 7392] , groups_width=264), """regnet-y-2560-seer-in1k""": ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1696, 2544, 5088] , groups_width=640), """regnet-y-10b-seer-in1k""": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2020, 4040, 1_1110, 2_8280] , groups_width=1010), } SCREAMING_SNAKE_CASE = NameToOurModelFuncMap() SCREAMING_SNAKE_CASE = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(_UpperCAmelCase , _UpperCAmelCase) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , model_dir=str(lowerCAmelCase__) , map_location='cpu') SCREAMING_SNAKE_CASE = model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE = files["""classy_state_dict"""]["""base_model"""]["""model"""] SCREAMING_SNAKE_CASE = model_state_dict["""trunk"""] model.load_state_dict(lowerCAmelCase__) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE = partial( lowerCAmelCase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf()) , ) SCREAMING_SNAKE_CASE = partial( lowerCAmelCase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf()) , ) SCREAMING_SNAKE_CASE = partial( lowerCAmelCase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf()) , ) SCREAMING_SNAKE_CASE = partial( lowerCAmelCase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1010 , w_a=1744 , w_a=6_20.83 , w_m=2.52))) , ) # IN1K finetuned SCREAMING_SNAKE_CASE = partial( lowerCAmelCase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf()) , ) SCREAMING_SNAKE_CASE = partial( lowerCAmelCase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf()) , ) SCREAMING_SNAKE_CASE = partial( lowerCAmelCase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf()) , ) SCREAMING_SNAKE_CASE = partial( lowerCAmelCase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1010 , w_a=1744 , w_a=6_20.83 , w_m=2.52))) , ) if model_name: convert_weight_and_push( lowerCAmelCase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , lowerCAmelCase__ , lowerCAmelCase__ , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowerCAmelCase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ) return config, expected_shape if __name__ == "__main__": a_ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default=None, type=str, help=( 'The name of the model you wish to convert, it must be one of the supported regnet* architecture,' ' currently: regnetx-*, regnety-*. If `None`, all of them will the converted.' ), ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=Path, required=True, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', default=True, type=bool, required=False, help='If True, push model and image processor to the hub.', ) a_ : str = parser.parse_args() a_ : Optional[int] = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
366
import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def lowerCamelCase__ (_UpperCAmelCase): if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class _snake_case ( nn.Module ): def __init__( self , a , a) -> Union[str, Any]: super().__init__() SCREAMING_SNAKE_CASE = module SCREAMING_SNAKE_CASE = nn.Sequential( nn.Linear(module.in_features , a , bias=a) , nn.Linear(a , module.out_features , bias=a) , ) SCREAMING_SNAKE_CASE = (2.0 / (5 * min(module.in_features , module.out_features))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=a) nn.init.zeros_(self.adapter[1].weight) self.adapter.to(module.weight.device) def SCREAMING_SNAKE_CASE__ ( self , a , *a , **a) -> Any: return self.module(a , *a , **a) + self.adapter(a) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): # We keep the constants inside the init function and model loading inside setUp function # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) # Therefore here we use only bloom-1b3 to test our module _lowercase : Union[str, Any] = '''bigscience/bloom-1b7''' # Constant values _lowercase : str = 2.109_6595_5269_2574 _lowercase : Any = '''Hello my name is''' _lowercase : Any = set() EXPECTED_OUTPUTS.add('''Hello my name is John and I am a professional photographer. I''' ) EXPECTED_OUTPUTS.add('''Hello my name is John.\nI am a friend of your father.\n''' ) EXPECTED_OUTPUTS.add('''Hello my name is John Doe, I am a student at the University''' ) _lowercase : Union[str, Any] = 10 def SCREAMING_SNAKE_CASE__ ( self) -> Any: # Models and tokenizer SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(self.model_name) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: super().setUp() # Models and tokenizer SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map='auto') SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_abit.config self.assertTrue(hasattr(a , 'quantization_config')) SCREAMING_SNAKE_CASE = config.to_dict() SCREAMING_SNAKE_CASE = config.to_diff_dict() SCREAMING_SNAKE_CASE = config.to_json_string() def SCREAMING_SNAKE_CASE__ ( self) -> Any: from bitsandbytes.nn import Paramsabit SCREAMING_SNAKE_CASE = self.model_fpaa.get_memory_footprint() SCREAMING_SNAKE_CASE = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE) SCREAMING_SNAKE_CASE = get_some_linear_layer(self.model_abit) self.assertTrue(linear.weight.__class__ == Paramsabit) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(a , torch.nn.Linear): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = self.model_abit.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = BitsAndBytesConfig() SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = model_abit_from_config.generate( input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) def SCREAMING_SNAKE_CASE__ ( self) -> str: with self.assertRaises(a), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = BitsAndBytesConfig() with self.assertRaises(a): SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=a , load_in_abit=a , device_map='auto' , bnb_abit_quant_type='nf4' , ) def SCREAMING_SNAKE_CASE__ ( self) -> int: with self.assertRaises(a): # Tries with `str` self.model_abit.to('cpu') with self.assertRaises(a): # Tries with a `dtype`` self.model_abit.to(torch.floataa) with self.assertRaises(a): # Tries with a `device` self.model_abit.to(torch.device('cuda:0')) with self.assertRaises(a): # Tries with a `device` self.model_abit.float() with self.assertRaises(a): # Tries with a `device` self.model_abit.half() # Test if we did not break anything SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = self.model_fpaa.to(torch.floataa) SCREAMING_SNAKE_CASE = self.model_fpaa.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.to('cpu') # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.half() # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.float() def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained('t5-small' , load_in_abit=a , device_map='auto') self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Tuple: SCREAMING_SNAKE_CASE = 't5-small' SCREAMING_SNAKE_CASE = 'google/flan-t5-small' # flan-t5 uses dense-act instead of dense-relu-dense SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(cls.model_name) SCREAMING_SNAKE_CASE = 'Translate in German: Hello, my dog is cute' def SCREAMING_SNAKE_CASE__ ( self) -> Dict: gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: from transformers import TaForConditionalGeneration SCREAMING_SNAKE_CASE = TaForConditionalGeneration._keep_in_fpaa_modules SCREAMING_SNAKE_CASE = None # test with `t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) # test with `flan-t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) SCREAMING_SNAKE_CASE = modules def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit)) SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) # test with `flan-t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> str: super().setUp() # model_name SCREAMING_SNAKE_CASE = 'bigscience/bloom-560m' SCREAMING_SNAKE_CASE = 't5-small' # Different types of model SCREAMING_SNAKE_CASE = AutoModel.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # Sequence classification model SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=a , device_map='auto') # CausalLM model SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # Seq2seq model SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=a , device_map='auto') def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Dict: del self.pipe gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = pipeline( 'text-generation' , model=self.model_name , model_kwargs={'device_map': 'auto', 'load_in_4bit': True, 'torch_dtype': torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass SCREAMING_SNAKE_CASE = self.pipe(self.input_text) self.assertIn(pipeline_output[0]['generated_text'] , self.EXPECTED_OUTPUTS) @require_torch_multi_gpu class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> int: super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=a , device_map='balanced') # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values()) , {0, 1}) # Check that inference pass works on the model SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') # Second real batch SCREAMING_SNAKE_CASE = model_parallel.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = 'facebook/opt-350m' super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Any: if version.parse(importlib.metadata.version('bitsandbytes')) < version.parse('0.37.0'): return # Step 1: freeze all parameters SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a) self.assertEqual(set(model.hf_device_map.values()) , {torch.cuda.current_device()}) for param in model.parameters(): SCREAMING_SNAKE_CASE = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability SCREAMING_SNAKE_CASE = param.data.to(torch.floataa) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(a)): SCREAMING_SNAKE_CASE = LoRALayer(module.q_proj , rank=16) SCREAMING_SNAKE_CASE = LoRALayer(module.k_proj , rank=16) SCREAMING_SNAKE_CASE = LoRALayer(module.v_proj , rank=16) # Step 3: dummy batch SCREAMING_SNAKE_CASE = self.tokenizer('Test batch ' , return_tensors='pt').to(0) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): SCREAMING_SNAKE_CASE = model.forward(**a) out.logits.norm().backward() for module in model.modules(): if isinstance(a , a): self.assertTrue(module.adapter[1].weight.grad is not None) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0) elif isinstance(a , nn.Embedding): self.assertTrue(module.weight.grad is None) class _snake_case ( A__ ): _lowercase : str = '''gpt2-xl''' _lowercase : Union[str, Any] = 3.3191_8548_5415_2187
327
0
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() a_ : List[str] = logging.get_logger() @dataclass class _snake_case : _lowercase : nn.Module _lowercase : List[nn.Module] = field(default_factory=A__ ) _lowercase : list = field(default_factory=A__ ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> List[Any]: SCREAMING_SNAKE_CASE = len(list(m.modules())) == 1 or isinstance(lowerCAmelCase__ , nn.Convad) or isinstance(lowerCAmelCase__ , nn.BatchNormad) if has_not_submodules: self.traced.append(lowerCAmelCase__) def __call__( self , a) -> List[Any]: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook)) self.module(lowerCAmelCase__) [x.remove() for x in self.handles] return self @property def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: return list(filter(lambda a: len(list(x.state_dict().keys())) > 0 , self.traced)) @dataclass class _snake_case : _lowercase : nn.Module _lowercase : nn.Module _lowercase : int = 1 _lowercase : List = field(default_factory=A__ ) _lowercase : List = field(default_factory=A__ ) _lowercase : bool = True def __call__( self , a) -> str: SCREAMING_SNAKE_CASE = Tracker(self.dest)(lowerCAmelCase__).parametrized SCREAMING_SNAKE_CASE = Tracker(self.src)(lowerCAmelCase__).parametrized SCREAMING_SNAKE_CASE = list(filter(lambda a: type(lowerCAmelCase__) not in self.src_skip , lowerCAmelCase__)) SCREAMING_SNAKE_CASE = list(filter(lambda a: type(lowerCAmelCase__) not in self.dest_skip , lowerCAmelCase__)) if len(lowerCAmelCase__) != len(lowerCAmelCase__) and self.raise_if_mismatch: raise Exception( f'''Numbers of operations are different. Source module has {len(lowerCAmelCase__)} operations while''' f''' destination module has {len(lowerCAmelCase__)}.''') for dest_m, src_m in zip(lowerCAmelCase__ , lowerCAmelCase__): dest_m.load_state_dict(src_m.state_dict()) if self.verbose == 1: print(f'''Transfered from={src_m} to={dest_m}''') class _snake_case ( nn.Module ): def __init__( self , a) -> Dict: super().__init__() SCREAMING_SNAKE_CASE = [] # - get the stem feature_blocks.append(('conv1', model.stem)) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block'), f'''Unexpected layer name {k}''' SCREAMING_SNAKE_CASE = len(lowerCAmelCase__) + 1 feature_blocks.append((f'''res{block_index}''', v)) SCREAMING_SNAKE_CASE = nn.ModuleDict(lowerCAmelCase__) def SCREAMING_SNAKE_CASE__ ( self , a) -> List[str]: return get_trunk_forward_outputs( lowerCAmelCase__ , out_feat_keys=lowerCAmelCase__ , feature_blocks=self._feature_blocks , ) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self , a) -> str: SCREAMING_SNAKE_CASE = x.split('-') return x_split[0] + x_split[1] + "_" + "".join(x_split[2:]) def __getitem__( self , a) -> Callable[[], Tuple[nn.Module, Dict]]: if x not in self: SCREAMING_SNAKE_CASE = self.convert_name_to_timm(lowerCAmelCase__) SCREAMING_SNAKE_CASE = partial(lambda: (timm.create_model(lowerCAmelCase__ , pretrained=lowerCAmelCase__).eval(), None)) else: SCREAMING_SNAKE_CASE = super().__getitem__(lowerCAmelCase__) return val class _snake_case ( A__ ): def __getitem__( self , a) -> Callable[[], nn.Module]: if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE = RegNetModel else: SCREAMING_SNAKE_CASE = RegNetForImageClassification return val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for from_key, to_key in keys: SCREAMING_SNAKE_CASE = from_state_dict[from_key].clone() print(F'''Copied key={from_key} to={to_key}''') return to_state_dict def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = True , ): print(F'''Converting {name}...''') with torch.no_grad(): SCREAMING_SNAKE_CASE = from_model_func() SCREAMING_SNAKE_CASE = our_model_func(a_).eval() SCREAMING_SNAKE_CASE = ModuleTransfer(src=a_ , dest=a_ , raise_if_mismatch=a_) SCREAMING_SNAKE_CASE = torch.randn((1, 3, 224, 224)) module_transfer(a_) if from_state_dict is not None: SCREAMING_SNAKE_CASE = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE = [("0.clf.0.weight", "classifier.1.weight"), ("0.clf.0.bias", "classifier.1.bias")] SCREAMING_SNAKE_CASE = manually_copy_vissl_head(a_ , our_model.state_dict() , a_) our_model.load_state_dict(a_) SCREAMING_SNAKE_CASE = our_model(a_ , output_hidden_states=a_) SCREAMING_SNAKE_CASE = ( our_outputs.logits if isinstance(a_ , a_) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE = from_model(a_) SCREAMING_SNAKE_CASE = from_output[-1] if type(a_) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE = our_outputs.hidden_states[-1] assert torch.allclose(a_ , a_), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add model' , use_temp_dir=a_ , ) SCREAMING_SNAKE_CASE = 224 if "seer" not in name else 384 # we can use the convnext one SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' , size=a_) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add image processor' , use_temp_dir=a_ , ) print(F'''Pushed {name}''') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = None , _UpperCAmelCase = True): SCREAMING_SNAKE_CASE = "imagenet-1k-id2label.json" SCREAMING_SNAKE_CASE = 1000 SCREAMING_SNAKE_CASE = (1, num_labels) SCREAMING_SNAKE_CASE = "huggingface/label-files" SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = json.load(open(cached_download(hf_hub_url(a_ , a_ , repo_type='dataset')) , 'r')) SCREAMING_SNAKE_CASE = {int(a_): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = idalabel SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = partial(a_ , num_labels=a_ , idalabel=a_ , labelaid=a_) SCREAMING_SNAKE_CASE = { "regnet-x-002": ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 , layer_type='x'), "regnet-x-004": ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 160, 384] , groups_width=16 , layer_type='x'), "regnet-x-006": ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 240, 528] , groups_width=24 , layer_type='x'), "regnet-x-008": ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 128, 288, 672] , groups_width=16 , layer_type='x'), "regnet-x-016": ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 168, 408, 912] , groups_width=24 , layer_type='x'), "regnet-x-032": ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 192, 432, 1008] , groups_width=48 , layer_type='x'), "regnet-x-040": ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 240, 560, 1360] , groups_width=40 , layer_type='x'), "regnet-x-064": ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 392, 784, 1624] , groups_width=56 , layer_type='x'), "regnet-x-080": ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 240, 720, 1920] , groups_width=120 , layer_type='x'), "regnet-x-120": ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2240] , groups_width=112 , layer_type='x'), "regnet-x-160": ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[256, 512, 896, 2048] , groups_width=128 , layer_type='x'), "regnet-x-320": ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[336, 672, 1344, 2520] , groups_width=168 , layer_type='x'), # y variant "regnet-y-002": ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8), "regnet-y-004": ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 104, 208, 440] , groups_width=8), "regnet-y-006": ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 112, 256, 608] , groups_width=16), "regnet-y-008": ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 128, 320, 768] , groups_width=16), "regnet-y-016": ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 120, 336, 888] , groups_width=24), "regnet-y-032": ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 216, 576, 1512] , groups_width=24), "regnet-y-040": ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[128, 192, 512, 1088] , groups_width=64), "regnet-y-064": ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[144, 288, 576, 1296] , groups_width=72), "regnet-y-080": ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 448, 896, 2016] , groups_width=56), "regnet-y-120": ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2240] , groups_width=112), "regnet-y-160": ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[224, 448, 1232, 3024] , groups_width=112), "regnet-y-320": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232), # models created by SEER -> https://arxiv.org/abs/2202.08360 "regnet-y-320-seer": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232), "regnet-y-640-seer": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1968, 4920] , groups_width=328), "regnet-y-1280-seer": RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1056, 2904, 7392] , groups_width=264), "regnet-y-2560-seer": RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1696, 2544, 5088] , groups_width=640), "regnet-y-10b-seer": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2020, 4040, 1_1110, 2_8280] , groups_width=1010), # finetuned on imagenet "regnet-y-320-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232), "regnet-y-640-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1968, 4920] , groups_width=328), "regnet-y-1280-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1056, 2904, 7392] , groups_width=264), "regnet-y-2560-seer-in1k": ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1696, 2544, 5088] , groups_width=640), "regnet-y-10b-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2020, 4040, 1_1110, 2_8280] , groups_width=1010), } SCREAMING_SNAKE_CASE = NameToOurModelFuncMap() SCREAMING_SNAKE_CASE = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(_UpperCAmelCase , _UpperCAmelCase) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE = torch.hub.load_state_dict_from_url(a_ , model_dir=str(a_) , map_location='cpu') SCREAMING_SNAKE_CASE = model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE = files["classy_state_dict"]["base_model"]["model"] SCREAMING_SNAKE_CASE = model_state_dict["trunk"] model.load_state_dict(a_) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE = partial( a_ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf()) , ) SCREAMING_SNAKE_CASE = partial( a_ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf()) , ) SCREAMING_SNAKE_CASE = partial( a_ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf()) , ) SCREAMING_SNAKE_CASE = partial( a_ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1010 , w_a=1744 , w_a=620.83 , w_m=2.52))) , ) # IN1K finetuned SCREAMING_SNAKE_CASE = partial( a_ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf()) , ) SCREAMING_SNAKE_CASE = partial( a_ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf()) , ) SCREAMING_SNAKE_CASE = partial( a_ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf()) , ) SCREAMING_SNAKE_CASE = partial( a_ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1010 , w_a=1744 , w_a=620.83 , w_m=2.52))) , ) if model_name: convert_weight_and_push( a_ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , a_ , a_ , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( a_ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , a_ , a_ , a_ , ) return config, expected_shape if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default=None, type=str, help=( 'The name of the model you wish to convert, it must be one of the supported regnet* architecture,' ' currently: regnetx-*, regnety-*. If `None`, all of them will the converted.' ), ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=Path, required=True, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', default=True, type=bool, required=False, help='If True, push model and image processor to the hub.', ) a_ : List[str] = parser.parse_args() a_ : Optional[Any] = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
367
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : Optional[Any] = { 'configuration_efficientnet': [ 'EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'EfficientNetConfig', 'EfficientNetOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[str] = ['EfficientNetImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = [ 'EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'EfficientNetForImageClassification', 'EfficientNetModel', 'EfficientNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure)
327
0
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin a_ : List[str] = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class _snake_case ( _UpperCamelCase , unittest.TestCase ): _lowercase : Union[str, Any] = PegasusTokenizer _lowercase : List[Any] = PegasusTokenizerFast _lowercase : Union[str, Any] = True _lowercase : int = True def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE = PegasusTokenizer(_SCREAMING_SNAKE_CASE) tokenizer.save_pretrained(self.tmpdirname) @cached_property def SCREAMING_SNAKE_CASE__ ( self) -> str: return PegasusTokenizer.from_pretrained('google/pegasus-large') def SCREAMING_SNAKE_CASE__ ( self , **a) -> PegasusTokenizer: return PegasusTokenizer.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ ( self , a) -> str: return ("This is a test", "This is a test") def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = '</s>' SCREAMING_SNAKE_CASE = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_SCREAMING_SNAKE_CASE) , _SCREAMING_SNAKE_CASE) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_SCREAMING_SNAKE_CASE) , _SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , '<pad>') self.assertEqual(vocab_keys[1] , '</s>') self.assertEqual(vocab_keys[-1] , 'v') self.assertEqual(len(_SCREAMING_SNAKE_CASE) , 1103) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: self.assertEqual(self.get_tokenizer().vocab_size , 1103) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE = rust_tokenizer([raw_input_str] , return_tensors=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE).input_ids[0] SCREAMING_SNAKE_CASE = py_tokenizer([raw_input_str] , return_tensors=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE).input_ids[0] self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word SCREAMING_SNAKE_CASE = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' SCREAMING_SNAKE_CASE = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE = tokenizer([raw_input_str] , return_tensors=_SCREAMING_SNAKE_CASE).input_ids[0] self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 SCREAMING_SNAKE_CASE = 'To ensure a smooth flow of bank resolutions.' SCREAMING_SNAKE_CASE = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE = tokenizer([raw_input_str] , return_tensors=_SCREAMING_SNAKE_CASE).input_ids[0] self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3]) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ['This is going to be way too long.' * 150, 'short example'] SCREAMING_SNAKE_CASE = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE = self._large_tokenizer(_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , return_tensors='pt') SCREAMING_SNAKE_CASE = self._large_tokenizer( text_target=_SCREAMING_SNAKE_CASE , max_length=5 , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , return_tensors='pt') assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(_SCREAMING_SNAKE_CASE) == 2 # input_ids, attention_mask. @slow def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: # fmt: off SCREAMING_SNAKE_CASE = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 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], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 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]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_SCREAMING_SNAKE_CASE , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class _snake_case ( _UpperCamelCase , unittest.TestCase ): _lowercase : int = PegasusTokenizer _lowercase : List[str] = PegasusTokenizerFast _lowercase : Dict = True _lowercase : Tuple = True def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE = PegasusTokenizer(_SCREAMING_SNAKE_CASE , offset=0 , mask_token_sent=_SCREAMING_SNAKE_CASE , mask_token='[MASK]') tokenizer.save_pretrained(self.tmpdirname) @cached_property def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv') def SCREAMING_SNAKE_CASE__ ( self , **a) -> PegasusTokenizer: return PegasusTokenizer.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ ( self , a) -> int: return ("This is a test", "This is a test") def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE = rust_tokenizer([raw_input_str] , return_tensors=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE).input_ids[0] SCREAMING_SNAKE_CASE = py_tokenizer([raw_input_str] , return_tensors=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE).input_ids[0] self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) @require_torch def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = ['This is going to be way too long.' * 1000, 'short example'] SCREAMING_SNAKE_CASE = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE = self._large_tokenizer(_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , return_tensors='pt') SCREAMING_SNAKE_CASE = self._large_tokenizer( text_target=_SCREAMING_SNAKE_CASE , max_length=5 , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , return_tensors='pt') assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(_SCREAMING_SNAKE_CASE) == 2 # input_ids, attention_mask. def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) SCREAMING_SNAKE_CASE = self._large_tokenizer(_SCREAMING_SNAKE_CASE).input_ids self.assertListEqual( _SCREAMING_SNAKE_CASE , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
368
import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) a_ : Dict = [ 'cross_validation.py', 'gradient_accumulation.py', 'local_sgd.py', 'multi_process_metrics.py', 'memory.py', 'automatic_gradient_accumulation.py', 'fsdp_with_peak_mem_tracking.py', 'deepspeed_with_config_support.py', 'megatron_lm_gpt_pretraining.py', ] class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , a = None) -> Optional[int]: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = os.path.abspath(os.path.join('examples' , 'by_feature')) SCREAMING_SNAKE_CASE = os.path.abspath('examples') for item in os.listdir(a): if item not in EXCLUDE_EXAMPLES: SCREAMING_SNAKE_CASE = os.path.join(a , a) if os.path.isfile(a) and ".py" in item_path: with self.subTest( tested_script=a , feature_script=a , tested_section='main()' if parser_only else 'training_function()' , ): SCREAMING_SNAKE_CASE = compare_against_test( os.path.join(a , a) , a , a , a) SCREAMING_SNAKE_CASE = '\n'.join(a) if special_strings is not None: for string in special_strings: SCREAMING_SNAKE_CASE = diff.replace(a , '') self.assertEqual(a , '') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: self.one_complete_example('complete_nlp_example.py' , a) self.one_complete_example('complete_nlp_example.py' , a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = os.path.abspath(os.path.join('examples' , 'cv_example.py')) SCREAMING_SNAKE_CASE = [ ' ' * 16 + '{\n\n', ' ' * 20 + '"accuracy": eval_metric["accuracy"],\n\n', ' ' * 20 + '"f1": eval_metric["f1"],\n\n', ' ' * 20 + '"train_loss": total_loss.item() / len(train_dataloader),\n\n', ' ' * 20 + '"epoch": epoch,\n\n', ' ' * 16 + '},\n\n', ' ' * 16 + 'step=epoch,\n', ' ' * 12, ' ' * 8 + 'for step, batch in enumerate(active_dataloader):\n', ] self.one_complete_example('complete_cv_example.py' , a , a , a) self.one_complete_example('complete_cv_example.py' , a , a , a) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class _snake_case ( A__ ): _lowercase : int = False @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Union[str, Any]: super().setUpClass() SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = os.path.join(cls._tmpdir , 'default_config.yml') write_basic_config(save_location=cls.configPath) SCREAMING_SNAKE_CASE = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Dict: super().tearDownClass() shutil.rmtree(cls._tmpdir) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'epoch_0'))) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'step_2'))) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0')} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) self.assertNotIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2')} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) if torch.cuda.is_available(): SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: SCREAMING_SNAKE_CASE = 1 if num_processes > 1: self.assertNotIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) else: self.assertIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = '\n examples/by_feature/cross_validation.py\n --num_folds 2\n '.split() with mock.patch.dict(os.environ , {'TESTING_MOCKED_DATALOADERS': '0'}): SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) SCREAMING_SNAKE_CASE = re.findall('({.+})' , a) SCREAMING_SNAKE_CASE = [r for r in results if 'accuracy' in r][-1] SCREAMING_SNAKE_CASE = ast.literal_eval(a) self.assertGreaterEqual(results['accuracy'] , 0.75) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ['examples/by_feature/multi_process_metrics.py'] run_command(self._launch_args + testargs) @require_trackers @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'}) def SCREAMING_SNAKE_CASE__ ( self) -> Any: with tempfile.TemporaryDirectory() as tmpdir: SCREAMING_SNAKE_CASE = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(a , 'tracking'))) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = ['examples/by_feature/gradient_accumulation.py'] run_command(self._launch_args + testargs) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = ['examples/by_feature/local_sgd.py'] run_command(self._launch_args + testargs)
327
0
import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / 'utils')) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> int: # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE = mock.Mock() SCREAMING_SNAKE_CASE = 500 SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = HTTPError SCREAMING_SNAKE_CASE = {} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert') # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' , return_value=_lowerCamelCase) as mock_head: SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert') # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def SCREAMING_SNAKE_CASE__ ( self) -> int: # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE = mock.Mock() SCREAMING_SNAKE_CASE = 500 SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = HTTPError SCREAMING_SNAKE_CASE = {} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE = GPTaTokenizerFast.from_pretrained('gpt2') # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' , return_value=_lowerCamelCase) as mock_head: SCREAMING_SNAKE_CASE = GPTaTokenizerFast.from_pretrained('gpt2') # This check we did call the fake head request mock_head.assert_called() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: # This test is for deprecated behavior and can be removed in v5 try: SCREAMING_SNAKE_CASE = tempfile.mktemp() with open(_lowerCamelCase , 'wb') as f: http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' , _lowerCamelCase) SCREAMING_SNAKE_CASE = AlbertTokenizer.from_pretrained(_lowerCamelCase) finally: os.remove(_lowerCamelCase) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('tokenizer.json'): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('tokenizer.json' , 'wb') as f: http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json' , _lowerCamelCase) SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2') # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size , 1000) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('tokenizer.json') def SCREAMING_SNAKE_CASE__ ( self) -> Any: # This test is for deprecated behavior and can be removed in v5 SCREAMING_SNAKE_CASE = AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model') @is_staging_test class _snake_case ( unittest.TestCase ): _lowercase : List[Any] = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Optional[Any]: SCREAMING_SNAKE_CASE = TOKEN HfFolder.save_token(_lowerCamelCase) @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> int: try: delete_repo(token=cls._token , repo_id='test-tokenizer') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-tokenizer-org') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='test-dynamic-tokenizer') except HTTPError: pass def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = os.path.join(_lowerCamelCase , 'vocab.txt') with open(_lowerCamelCase , 'w' , encoding='utf-8') as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens])) SCREAMING_SNAKE_CASE = BertTokenizer(_lowerCamelCase) tokenizer.push_to_hub('test-tokenizer' , use_auth_token=self._token) SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''') self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab) # Reset repo delete_repo(token=self._token , repo_id='test-tokenizer') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(_lowerCamelCase , repo_id='test-tokenizer' , push_to_hub=_lowerCamelCase , use_auth_token=self._token) SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''') self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = os.path.join(_lowerCamelCase , 'vocab.txt') with open(_lowerCamelCase , 'w' , encoding='utf-8') as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens])) SCREAMING_SNAKE_CASE = BertTokenizer(_lowerCamelCase) tokenizer.push_to_hub('valid_org/test-tokenizer-org' , use_auth_token=self._token) SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained('valid_org/test-tokenizer-org') self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-tokenizer-org') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( _lowerCamelCase , repo_id='valid_org/test-tokenizer-org' , push_to_hub=_lowerCamelCase , use_auth_token=self._token) SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained('valid_org/test-tokenizer-org') self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab) @require_tokenizers def SCREAMING_SNAKE_CASE__ ( self) -> int: CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = os.path.join(_lowerCamelCase , 'vocab.txt') with open(_lowerCamelCase , 'w' , encoding='utf-8') as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens])) SCREAMING_SNAKE_CASE = CustomTokenizer(_lowerCamelCase) # No fast custom tokenizer tokenizer.push_to_hub('test-dynamic-tokenizer' , use_auth_token=self._token) SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=_lowerCamelCase) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , 'CustomTokenizer') # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE = os.path.join(_lowerCamelCase , 'vocab.txt') with open(_lowerCamelCase , 'w' , encoding='utf-8') as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens])) SCREAMING_SNAKE_CASE = BertTokenizerFast.from_pretrained(_lowerCamelCase) bert_tokenizer.save_pretrained(_lowerCamelCase) SCREAMING_SNAKE_CASE = CustomTokenizerFast.from_pretrained(_lowerCamelCase) tokenizer.push_to_hub('test-dynamic-tokenizer' , use_auth_token=self._token) SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=_lowerCamelCase) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , 'CustomTokenizerFast') SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( f'''{USER}/test-dynamic-tokenizer''' , use_fast=_lowerCamelCase , trust_remote_code=_lowerCamelCase) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , 'CustomTokenizer') class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = Trie() trie.add('Hello 友達') self.assertEqual(trie.data , {'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}}) trie.add('Hello') trie.data self.assertEqual(trie.data , {'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}}) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = Trie() self.assertEqual(trie.split('[CLS] This is a extra_id_100') , ['[CLS] This is a extra_id_100']) trie.add('[CLS]') trie.add('extra_id_1') trie.add('extra_id_100') self.assertEqual(trie.split('[CLS] This is a extra_id_100') , ['[CLS]', ' This is a ', 'extra_id_100']) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = Trie() trie.add('A') self.assertEqual(trie.split('ABC') , ['A', 'BC']) self.assertEqual(trie.split('BCA') , ['BC', 'A']) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = Trie() trie.add('TOKEN]') trie.add('[SPECIAL_TOKEN]') self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]') , ['This is something ', '[SPECIAL_TOKEN]']) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = Trie() trie.add('A') trie.add('P') trie.add('[SPECIAL_TOKEN]') self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]') , ['This is something ', '[SPECIAL_TOKEN]']) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = Trie() trie.add('AB') trie.add('B') trie.add('C') self.assertEqual(trie.split('ABC') , ['AB', 'C']) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = Trie() trie.add('ABC') trie.add('B') trie.add('CD') self.assertEqual(trie.split('ABCD') , ['ABC', 'D']) def SCREAMING_SNAKE_CASE__ ( self) -> Any: # Even if the offsets are wrong, we necessarily output correct string # parts. SCREAMING_SNAKE_CASE = Trie() SCREAMING_SNAKE_CASE = trie.cut_text('ABC' , [0, 0, 2, 1, 2, 3]) self.assertEqual(_lowerCamelCase , ['AB', 'C'])
369
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _snake_case : def __init__( self , a , a=3 , a=32 , a=3 , a=10 , a=[10, 20, 30, 40] , a=[1, 1, 2, 1] , a=True , a=True , a="relu" , a=3 , a=None , ) -> Union[str, Any]: 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 SCREAMING_SNAKE_CASE__ ( self) -> List[str]: 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 SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return ResNetConfig( 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 , image_size=self.image_size , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Any: SCREAMING_SNAKE_CASE = TFResNetModel(config=a) 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 SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> int: SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = TFResNetForImageClassification(a) SCREAMING_SNAKE_CASE = model(a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: 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_tf class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () _lowercase : Dict = ( {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification} if is_tf_available() else {} ) _lowercase : Union[str, Any] = False _lowercase : Any = False _lowercase : List[str] = False _lowercase : str = False _lowercase : int = False def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = TFResNetModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , has_text_modality=a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return @unittest.skip(reason='ResNet does not use inputs_embeds') def SCREAMING_SNAKE_CASE__ ( self) -> int: pass @unittest.skip(reason='ResNet does not support input and output embeddings') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: pass def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: 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.call) # 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 SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: def check_hidden_states_output(a , a , a): SCREAMING_SNAKE_CASE = model_class(a) 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) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 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 SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> str: for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = TFResNetModel.from_pretrained(a) self.assertIsNotNone(a) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') return image @require_tf @require_vision class _snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = image_processor(images=a , return_tensors='tf') # forward pass SCREAMING_SNAKE_CASE = model(**a) # verify the logits SCREAMING_SNAKE_CASE = tf.TensorShape((1, 1000)) self.assertEqual(outputs.logits.shape , a) SCREAMING_SNAKE_CASE = tf.constant([-11.10_69, -9.78_77, -8.37_77]) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , a , atol=1E-4))
327
0
import os import re import sys import traceback import warnings from pathlib import Path from typing import Dict, Optional, Union from uuid import uuida from huggingface_hub import HfFolder, ModelCard, ModelCardData, hf_hub_download, whoami from huggingface_hub.file_download import REGEX_COMMIT_HASH from huggingface_hub.utils import ( EntryNotFoundError, RepositoryNotFoundError, RevisionNotFoundError, is_jinja_available, ) from packaging import version from requests import HTTPError from .. import __version__ from .constants import ( DEPRECATED_REVISION_ARGS, DIFFUSERS_CACHE, HUGGINGFACE_CO_RESOLVE_ENDPOINT, SAFETENSORS_WEIGHTS_NAME, WEIGHTS_NAME, ) from .import_utils import ( ENV_VARS_TRUE_VALUES, _flax_version, _jax_version, _onnxruntime_version, _torch_version, is_flax_available, is_onnx_available, is_torch_available, ) from .logging import get_logger a_ : Optional[Any] = get_logger(__name__) a_ : Optional[Any] = Path(__file__).parent / 'model_card_template.md' a_ : str = uuida().hex a_ : Optional[int] = os.getenv('HF_HUB_OFFLINE', '').upper() in ENV_VARS_TRUE_VALUES a_ : Optional[Any] = os.getenv('DISABLE_TELEMETRY', '').upper() in ENV_VARS_TRUE_VALUES a_ : List[Any] = HUGGINGFACE_CO_RESOLVE_ENDPOINT + '/api/telemetry/' def lowerCamelCase__ (_UpperCAmelCase = None): SCREAMING_SNAKE_CASE = F'''diffusers/{__version__}; python/{sys.version.split()[0]}; session_id/{SESSION_ID}''' if DISABLE_TELEMETRY or HF_HUB_OFFLINE: return ua + "; telemetry/off" if is_torch_available(): ua += F'''; torch/{_torch_version}''' if is_flax_available(): ua += F'''; jax/{_jax_version}''' ua += F'''; flax/{_flax_version}''' if is_onnx_available(): ua += F'''; onnxruntime/{_onnxruntime_version}''' # CI will set this value to True if os.environ.get('DIFFUSERS_IS_CI' , '').upper() in ENV_VARS_TRUE_VALUES: ua += "; is_ci/true" if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE): ua += "; " + "; ".join(F'''{k}/{v}''' for k, v in user_agent.items()) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE): ua += "; " + user_agent return ua def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = None , _UpperCAmelCase = None): if token is None: SCREAMING_SNAKE_CASE = HfFolder.get_token() if organization is None: SCREAMING_SNAKE_CASE = whoami(__SCREAMING_SNAKE_CASE)["""name"""] return F'''{username}/{model_id}''' else: return F'''{organization}/{model_id}''' def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): if not is_jinja_available(): raise ValueError( 'Modelcard rendering is based on Jinja templates.' ' Please make sure to have `jinja` installed before using `create_model_card`.' ' To install it, please run `pip install Jinja2`.') if hasattr(__SCREAMING_SNAKE_CASE , 'local_rank') and args.local_rank not in [-1, 0]: return SCREAMING_SNAKE_CASE = args.hub_token if hasattr(__SCREAMING_SNAKE_CASE , 'hub_token') else None SCREAMING_SNAKE_CASE = get_full_repo_name(__SCREAMING_SNAKE_CASE , token=__SCREAMING_SNAKE_CASE) SCREAMING_SNAKE_CASE = ModelCard.from_template( card_data=ModelCardData( # Card metadata object that will be converted to YAML block language='en' , license='apache-2.0' , library_name='diffusers' , tags=[] , datasets=args.dataset_name , metrics=[] , ) , template_path=__SCREAMING_SNAKE_CASE , model_name=__SCREAMING_SNAKE_CASE , repo_name=__SCREAMING_SNAKE_CASE , dataset_name=args.dataset_name if hasattr(__SCREAMING_SNAKE_CASE , 'dataset_name') else None , learning_rate=args.learning_rate , train_batch_size=args.train_batch_size , eval_batch_size=args.eval_batch_size , gradient_accumulation_steps=( args.gradient_accumulation_steps if hasattr(__SCREAMING_SNAKE_CASE , 'gradient_accumulation_steps') else None ) , adam_betaa=args.adam_betaa if hasattr(__SCREAMING_SNAKE_CASE , 'adam_beta1') else None , adam_betaa=args.adam_betaa if hasattr(__SCREAMING_SNAKE_CASE , 'adam_beta2') else None , adam_weight_decay=args.adam_weight_decay if hasattr(__SCREAMING_SNAKE_CASE , 'adam_weight_decay') else None , adam_epsilon=args.adam_epsilon if hasattr(__SCREAMING_SNAKE_CASE , 'adam_epsilon') else None , lr_scheduler=args.lr_scheduler if hasattr(__SCREAMING_SNAKE_CASE , 'lr_scheduler') else None , lr_warmup_steps=args.lr_warmup_steps if hasattr(__SCREAMING_SNAKE_CASE , 'lr_warmup_steps') else None , ema_inv_gamma=args.ema_inv_gamma if hasattr(__SCREAMING_SNAKE_CASE , 'ema_inv_gamma') else None , ema_power=args.ema_power if hasattr(__SCREAMING_SNAKE_CASE , 'ema_power') else None , ema_max_decay=args.ema_max_decay if hasattr(__SCREAMING_SNAKE_CASE , 'ema_max_decay') else None , mixed_precision=args.mixed_precision , ) SCREAMING_SNAKE_CASE = os.path.join(args.output_dir , 'README.md') model_card.save(__SCREAMING_SNAKE_CASE) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = None): if resolved_file is None or commit_hash is not None: return commit_hash SCREAMING_SNAKE_CASE = str(Path(__SCREAMING_SNAKE_CASE).as_posix()) SCREAMING_SNAKE_CASE = re.search(R'snapshots/([^/]+)/' , __SCREAMING_SNAKE_CASE) if search is None: return None SCREAMING_SNAKE_CASE = search.groups()[0] return commit_hash if REGEX_COMMIT_HASH.match(__SCREAMING_SNAKE_CASE) else None # Old default cache path, potentially to be migrated. # This logic was more or less taken from `transformers`, with the following differences: # - Diffusers doesn't use custom environment variables to specify the cache path. # - There is no need to migrate the cache format, just move the files to the new location. a_ : Tuple = os.path.expanduser( os.getenv('HF_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'huggingface')) ) a_ : Optional[Any] = os.path.join(hf_cache_home, 'diffusers') def lowerCamelCase__ (_UpperCAmelCase = None , _UpperCAmelCase = None): if new_cache_dir is None: SCREAMING_SNAKE_CASE = DIFFUSERS_CACHE if old_cache_dir is None: SCREAMING_SNAKE_CASE = old_diffusers_cache SCREAMING_SNAKE_CASE = Path(__SCREAMING_SNAKE_CASE).expanduser() SCREAMING_SNAKE_CASE = Path(__SCREAMING_SNAKE_CASE).expanduser() for old_blob_path in old_cache_dir.glob('**/blobs/*'): if old_blob_path.is_file() and not old_blob_path.is_symlink(): SCREAMING_SNAKE_CASE = new_cache_dir / old_blob_path.relative_to(__SCREAMING_SNAKE_CASE) new_blob_path.parent.mkdir(parents=__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE) os.replace(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) try: os.symlink(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) except OSError: logger.warning( 'Could not create symlink between old cache and new cache. If you use an older version of diffusers again, files will be re-downloaded.') # At this point, old_cache_dir contains symlinks to the new cache (it can still be used). a_ : Optional[int] = os.path.join(DIFFUSERS_CACHE, 'version_diffusers_cache.txt') if not os.path.isfile(cache_version_file): a_ : int = 0 else: with open(cache_version_file) as f: try: a_ : List[Any] = int(f.read()) except ValueError: a_ : Optional[int] = 0 if cache_version < 1: a_ : Optional[Any] = os.path.isdir(old_diffusers_cache) and len(os.listdir(old_diffusers_cache)) > 0 if old_cache_is_not_empty: logger.warning( 'The cache for model files in Diffusers v0.14.0 has moved to a new location. Moving your ' 'existing cached models. This is a one-time operation, you can interrupt it or run it ' 'later by calling `diffusers.utils.hub_utils.move_cache()`.' ) try: move_cache() except Exception as e: a_ : Union[str, Any] = '\n'.join(traceback.format_tb(e.__traceback__)) logger.error( f"""There was a problem when trying to move your cache:\n\n{trace}\n{e.__class__.__name__}: {e}\n\nPlease """ 'file an issue at https://github.com/huggingface/diffusers/issues/new/choose, copy paste this whole ' 'message and we will do our best to help.' ) if cache_version < 1: try: os.makedirs(DIFFUSERS_CACHE, exist_ok=True) with open(cache_version_file, 'w') as f: f.write('1') except Exception: logger.warning( f"""There was a problem when trying to write in your cache folder ({DIFFUSERS_CACHE}). Please, ensure """ 'the directory exists and can be written to.' ) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = None): if variant is not None: SCREAMING_SNAKE_CASE = weights_name.split('.') SCREAMING_SNAKE_CASE = splits[:-1] + [variant] + splits[-1:] SCREAMING_SNAKE_CASE = """.""".join(__SCREAMING_SNAKE_CASE) return weights_name def lowerCamelCase__ (_UpperCAmelCase , *, _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , ): SCREAMING_SNAKE_CASE = str(__SCREAMING_SNAKE_CASE) if os.path.isfile(__SCREAMING_SNAKE_CASE): return pretrained_model_name_or_path elif os.path.isdir(__SCREAMING_SNAKE_CASE): if os.path.isfile(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE)): # Load from a PyTorch checkpoint SCREAMING_SNAKE_CASE = os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) return model_file elif subfolder is not None and os.path.isfile( os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE)): SCREAMING_SNAKE_CASE = os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) return model_file else: raise EnvironmentError( F'''Error no file named {weights_name} found in directory {pretrained_model_name_or_path}.''') else: # 1. First check if deprecated way of loading from branches is used if ( revision in DEPRECATED_REVISION_ARGS and (weights_name == WEIGHTS_NAME or weights_name == SAFETENSORS_WEIGHTS_NAME) and version.parse(version.parse(__SCREAMING_SNAKE_CASE).base_version) >= version.parse('0.20.0') ): try: SCREAMING_SNAKE_CASE = hf_hub_download( __SCREAMING_SNAKE_CASE , filename=_add_variant(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , user_agent=__SCREAMING_SNAKE_CASE , subfolder=__SCREAMING_SNAKE_CASE , revision=revision or commit_hash , ) warnings.warn( F'''Loading the variant {revision} from {pretrained_model_name_or_path} via `revision=\'{revision}\'` is deprecated. Loading instead from `revision=\'main\'` with `variant={revision}`. Loading model variants via `revision=\'{revision}\'` will be removed in diffusers v1. Please use `variant=\'{revision}\'` instead.''' , __SCREAMING_SNAKE_CASE , ) return model_file except: # noqa: E722 warnings.warn( F'''You are loading the variant {revision} from {pretrained_model_name_or_path} via `revision=\'{revision}\'`. This behavior is deprecated and will be removed in diffusers v1. One should use `variant=\'{revision}\'` instead. However, it appears that {pretrained_model_name_or_path} currently does not have a {_add_variant(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE)} file in the \'main\' branch of {pretrained_model_name_or_path}. \n The Diffusers team and community would be very grateful if you could open an issue: https://github.com/huggingface/diffusers/issues/new with the title \'{pretrained_model_name_or_path} is missing {_add_variant(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE)}\' so that the correct variant file can be added.''' , __SCREAMING_SNAKE_CASE , ) try: # 2. Load model file as usual SCREAMING_SNAKE_CASE = hf_hub_download( __SCREAMING_SNAKE_CASE , filename=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , user_agent=__SCREAMING_SNAKE_CASE , subfolder=__SCREAMING_SNAKE_CASE , revision=revision or commit_hash , ) return model_file except RepositoryNotFoundError: raise EnvironmentError( F'''{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier ''' 'listed on \'https://huggingface.co/models\'\nIf this is a private repository, make sure to pass a ' 'token having permission to this repo with `use_auth_token` or log in with `huggingface-cli ' 'login`.') except RevisionNotFoundError: raise EnvironmentError( F'''{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for ''' 'this model name. Check the model page at ' F'''\'https://huggingface.co/{pretrained_model_name_or_path}\' for available revisions.''') except EntryNotFoundError: raise EnvironmentError( F'''{pretrained_model_name_or_path} does not appear to have a file named {weights_name}.''') except HTTPError as err: raise EnvironmentError( F'''There was a specific connection error when trying to load {pretrained_model_name_or_path}:\n{err}''') except ValueError: raise EnvironmentError( F'''We couldn\'t connect to \'{HUGGINGFACE_CO_RESOLVE_ENDPOINT}\' to load this model, couldn\'t find it''' F''' in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a''' F''' directory containing a file named {weights_name} or''' ' \nCheckout your internet connection or see how to run the library in' ' offline mode at \'https://huggingface.co/docs/diffusers/installation#offline-mode\'.') except EnvironmentError: raise EnvironmentError( F'''Can\'t load the model for \'{pretrained_model_name_or_path}\'. If you were trying to load it from ''' '\'https://huggingface.co/models\', make sure you don\'t have a local directory with the same name. ' F'''Otherwise, make sure \'{pretrained_model_name_or_path}\' is the correct path to a directory ''' F'''containing a file named {weights_name}''')
370
from math import isqrt def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [True] * max_number for i in range(2 , isqrt(max_number - 1) + 1): if is_prime[i]: for j in range(i**2 , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = False return [i for i in range(2 , _UpperCAmelCase) if is_prime[i]] def lowerCamelCase__ (_UpperCAmelCase = 10**8): SCREAMING_SNAKE_CASE = calculate_prime_numbers(max_number // 2) SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(f"""{solution() = }""")
327
0
import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a_ : Optional[Any] = 16 a_ : Any = 32 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = 16): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc') def tokenize_function(_UpperCAmelCase): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=UpperCAmelCase__ , max_length=UpperCAmelCase__) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = datasets.map( UpperCAmelCase__ , batched=UpperCAmelCase__ , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE = 8 else: SCREAMING_SNAKE_CASE = None return tokenizer.pad( UpperCAmelCase__ , padding='longest' , max_length=UpperCAmelCase__ , pad_to_multiple_of=UpperCAmelCase__ , return_tensors='pt' , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['train'] , shuffle=UpperCAmelCase__ , collate_fn=UpperCAmelCase__ , batch_size=UpperCAmelCase__ , drop_last=UpperCAmelCase__) SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['validation'] , shuffle=UpperCAmelCase__ , collate_fn=UpperCAmelCase__ , batch_size=UpperCAmelCase__ , drop_last=(accelerator.mixed_precision == 'fp8') , ) return train_dataloader, eval_dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Initialize accelerator SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE = config["""lr"""] SCREAMING_SNAKE_CASE = int(config['num_epochs']) SCREAMING_SNAKE_CASE = int(config['seed']) SCREAMING_SNAKE_CASE = int(config['batch_size']) SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') # If the batch size is too big we use gradient accumulation SCREAMING_SNAKE_CASE = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: SCREAMING_SNAKE_CASE = batch_size // MAX_GPU_BATCH_SIZE SCREAMING_SNAKE_CASE = MAX_GPU_BATCH_SIZE set_seed(UpperCAmelCase__) SCREAMING_SNAKE_CASE = get_dataloaders(UpperCAmelCase__ , UpperCAmelCase__) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=UpperCAmelCase__) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE = model.to(accelerator.device) # Instantiate optimizer SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=UpperCAmelCase__) # Instantiate scheduler SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=UpperCAmelCase__ , num_warmup_steps=100 , num_training_steps=(len(UpperCAmelCase__) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE = accelerator.prepare( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) # Now we train the model for epoch in range(UpperCAmelCase__): model.train() for step, batch in enumerate(UpperCAmelCase__): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__) SCREAMING_SNAKE_CASE = outputs.loss SCREAMING_SNAKE_CASE = loss / gradient_accumulation_steps accelerator.backward(UpperCAmelCase__) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(UpperCAmelCase__): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch['labels'])) metric.add_batch( predictions=UpperCAmelCase__ , references=UpperCAmelCase__ , ) SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , UpperCAmelCase__) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description='Simple example of training script.') parser.add_argument( '--mixed_precision' , type=UpperCAmelCase__ , default=UpperCAmelCase__ , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.') SCREAMING_SNAKE_CASE = parser.parse_args() SCREAMING_SNAKE_CASE = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(UpperCAmelCase__ , UpperCAmelCase__) if __name__ == "__main__": main()
371
import baseaa def lowerCamelCase__ (_UpperCAmelCase): return baseaa.aaaencode(string.encode('utf-8')) def lowerCamelCase__ (_UpperCAmelCase): return baseaa.aaadecode(_UpperCAmelCase).decode('utf-8') if __name__ == "__main__": import doctest doctest.testmod()
327
0
import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class _snake_case ( __lowercase ): _lowercase : str = '''''' _lowercase : Union[str, Any] = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) _lowercase : List[Any] = None # compression type in fsspec. ex: "gzip" _lowercase : int = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__( self , a = "" , a = None , a = None , **a) -> str: super().__init__(self , **_a) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode SCREAMING_SNAKE_CASE = fsspec.open( _a , mode='rb' , protocol=_a , compression=self.compression , client_kwargs={ 'requote_redirect_url': False, # see https://github.com/huggingface/datasets/pull/5459 'trust_env': True, # Enable reading proxy env variables. **(target_options or {}).pop('client_kwargs' , {}), # To avoid issues if it was already passed. } , **(target_options or {}) , ) SCREAMING_SNAKE_CASE = os.path.basename(self.file.path.split('::')[0]) SCREAMING_SNAKE_CASE = ( self.compressed_name[: self.compressed_name.rindex('.')] if '.' in self.compressed_name else self.compressed_name ) SCREAMING_SNAKE_CASE = None @classmethod def SCREAMING_SNAKE_CASE__ ( cls , a) -> Optional[Any]: # compressed file paths are always relative to the archive root return super()._strip_protocol(_a).lstrip('/') def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: if self.dir_cache is None: SCREAMING_SNAKE_CASE = {**self.file.fs.info(self.file.path), 'name': self.uncompressed_name} SCREAMING_SNAKE_CASE = {f['name']: f} def SCREAMING_SNAKE_CASE__ ( self , a) -> List[str]: return self.file.open().read() def SCREAMING_SNAKE_CASE__ ( self , a , a = "rb" , a=None , a=True , a=None , **a , ) -> str: SCREAMING_SNAKE_CASE = self._strip_protocol(_a) if mode != "rb": raise ValueError(f'''Tried to read with mode {mode} on file {self.file.path} opened with mode \'rb\'''') return self.file.open() class _snake_case ( __lowercase ): _lowercase : List[str] = '''bz2''' _lowercase : Union[str, Any] = '''bz2''' _lowercase : Any = '''.bz2''' class _snake_case ( __lowercase ): _lowercase : Optional[int] = '''gzip''' _lowercase : str = '''gzip''' _lowercase : Optional[int] = '''.gz''' class _snake_case ( __lowercase ): _lowercase : int = '''lz4''' _lowercase : Optional[int] = '''lz4''' _lowercase : Optional[int] = '''.lz4''' class _snake_case ( __lowercase ): _lowercase : Any = '''xz''' _lowercase : List[Any] = '''xz''' _lowercase : Optional[Any] = '''.xz''' class _snake_case ( __lowercase ): _lowercase : Dict = '''zstd''' _lowercase : Union[str, Any] = '''zstd''' _lowercase : Dict = '''.zst''' def __init__( self , a , a = "rb" , a = None , a = None , a = DEFAULT_BLOCK_SIZE , **a , ) -> Optional[Any]: super().__init__( fo=_a , mode=_a , target_protocol=_a , target_options=_a , block_size=_a , **_a , ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 SCREAMING_SNAKE_CASE = self.file.__enter__ class _snake_case : def __init__( self , a) -> int: SCREAMING_SNAKE_CASE = file_ def __enter__( self) -> Dict: self._file.__enter__() return self def __exit__( self , *a , **a) -> Dict: self._file.__exit__(*_a , **_a) def __iter__( self) -> Optional[Any]: return iter(self._file) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: return next(self._file) def __getattr__( self , a) -> Union[str, Any]: return getattr(self._file , _a) def fixed_enter(*a , **a): return WrappedFile(_enter(*_a , **_a)) SCREAMING_SNAKE_CASE = fixed_enter
350
import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(_UpperCAmelCase , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = emb.weight.shape SCREAMING_SNAKE_CASE = nn.Linear(_UpperCAmelCase , _UpperCAmelCase , bias=_UpperCAmelCase) SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = mam_aaa['args'] or mam_aaa['cfg']['model'] SCREAMING_SNAKE_CASE = mam_aaa['model'] remove_ignore_keys_(_UpperCAmelCase) SCREAMING_SNAKE_CASE = state_dict['encoder.embed_tokens.weight'].shape[0] SCREAMING_SNAKE_CASE = MaMaaaConfig( vocab_size=_UpperCAmelCase , max_position_embeddings=1024 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='relu' , ) SCREAMING_SNAKE_CASE = state_dict['decoder.embed_tokens.weight'] SCREAMING_SNAKE_CASE = MaMaaaForConditionalGeneration(_UpperCAmelCase) model.model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase) SCREAMING_SNAKE_CASE = make_linear_from_emb(model.model.shared) return model if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') a_ : List[str] = parser.parse_args() a_ : Dict = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
327
0
import argparse import torch from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt if __name__ == "__main__": a_ : Optional[Any] = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) # !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml parser.add_argument( '--original_config_file', default=None, type=str, help='The YAML config file corresponding to the original architecture.', ) parser.add_argument( '--num_in_channels', default=None, type=int, help='The number of input channels. If `None` number of input channels will be automatically inferred.', ) parser.add_argument( '--scheduler_type', default='pndm', type=str, help='Type of scheduler to use. Should be one of [\'pndm\', \'lms\', \'ddim\', \'euler\', \'euler-ancestral\', \'dpm\']', ) parser.add_argument( '--pipeline_type', default=None, type=str, help=( 'The pipeline type. One of \'FrozenOpenCLIPEmbedder\', \'FrozenCLIPEmbedder\', \'PaintByExample\'' '. If `None` pipeline will be automatically inferred.' ), ) parser.add_argument( '--image_size', default=None, type=int, help=( 'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2' ' Base. Use 768 for Stable Diffusion v2.' ), ) parser.add_argument( '--prediction_type', default=None, type=str, help=( 'The prediction type that the model was trained on. Use \'epsilon\' for Stable Diffusion v1.X and Stable' ' Diffusion v2 Base. Use \'v_prediction\' for Stable Diffusion v2.' ), ) parser.add_argument( '--extract_ema', action='store_true', help=( 'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights' ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield' ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.' ), ) parser.add_argument( '--upcast_attention', action='store_true', help=( 'Whether the attention computation should always be upcasted. This is necessary when running stable' ' diffusion 2.1.' ), ) parser.add_argument( '--from_safetensors', action='store_true', help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.', ) parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') parser.add_argument( '--stable_unclip', type=str, default=None, required=False, help='Set if this is a stable unCLIP model. One of \'txt2img\' or \'img2img\'.', ) parser.add_argument( '--stable_unclip_prior', type=str, default=None, required=False, help='Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.', ) parser.add_argument( '--clip_stats_path', type=str, help='Path to the clip stats file. Only required if the stable unclip model\'s config specifies `model.params.noise_aug_config.params.clip_stats_path`.', required=False, ) parser.add_argument( '--controlnet', action='store_true', default=None, help='Set flag if this is a controlnet checkpoint.' ) parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--vae_path', type=str, default=None, required=False, help='Set to a path, hub id to an already converted vae to not convert it again.', ) a_ : List[Any] = parser.parse_args() a_ : Union[str, Any] = download_from_original_stable_diffusion_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, prediction_type=args.prediction_type, model_type=args.pipeline_type, extract_ema=args.extract_ema, scheduler_type=args.scheduler_type, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, stable_unclip=args.stable_unclip, stable_unclip_prior=args.stable_unclip_prior, clip_stats_path=args.clip_stats_path, controlnet=args.controlnet, vae_path=args.vae_path, ) if args.half: pipe.to(torch_dtype=torch.floataa) if args.controlnet: # only save the controlnet model pipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors) else: pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
351
import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = 'laion/clap-htsat-unfused' SCREAMING_SNAKE_CASE = tempfile.mkdtemp() def SCREAMING_SNAKE_CASE__ ( self , **a) -> Optional[Any]: return RobertaTokenizer.from_pretrained(self.checkpoint , **a) def SCREAMING_SNAKE_CASE__ ( self , **a) -> Union[str, Any]: return ClapFeatureExtractor.from_pretrained(self.checkpoint , **a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = ClapProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) self.assertIsInstance(processor.tokenizer , a) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor()) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)') SCREAMING_SNAKE_CASE = self.get_feature_extractor(do_normalize=a , padding_value=1.0) SCREAMING_SNAKE_CASE = ClapProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=a , padding_value=1.0) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) self.assertIsInstance(processor.tokenizer , a) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = floats_list((3, 1000)) SCREAMING_SNAKE_CASE = feature_extractor(a , return_tensors='np') SCREAMING_SNAKE_CASE = processor(audios=a , return_tensors='np') for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = 'This is a test string' SCREAMING_SNAKE_CASE = processor(text=a) SCREAMING_SNAKE_CASE = tokenizer(a) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE = processor.batch_decode(a) SCREAMING_SNAKE_CASE = tokenizer.batch_decode(a) self.assertListEqual(a , a) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , )
327
0
import random import timeit from functools import wraps from typing import Callable, Optional from ..configuration_utils import PretrainedConfig from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING from ..utils import is_pyanvml_available, is_tf_available, logging from .benchmark_utils import ( Benchmark, Memory, MemorySummary, measure_peak_memory_cpu, start_memory_tracing, stop_memory_tracing, ) if is_tf_available(): import tensorflow as tf from tensorflow.python.framework.errors_impl import ResourceExhaustedError from .benchmark_args_tf import TensorFlowBenchmarkArguments if is_pyanvml_available(): import pyanvml.pyanvml as nvml a_ : Dict = logging.get_logger(__name__) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): def run_func(_UpperCAmelCase): @wraps(_snake_case) def run_in_eager_mode(*_UpperCAmelCase , **_UpperCAmelCase): return func(*_snake_case , **_snake_case) @wraps(_snake_case) @tf.function(experimental_compile=_snake_case) def run_in_graph_mode(*_UpperCAmelCase , **_UpperCAmelCase): return func(*_snake_case , **_snake_case) if do_eager_mode is True: if use_xla is not False: raise ValueError( 'Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`.') return run_in_eager_mode else: return run_in_graph_mode return run_func def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = random.Random() SCREAMING_SNAKE_CASE = [rng.randint(0 , vocab_size - 1) for i in range(batch_size * sequence_length)] return tf.constant(_snake_case , shape=(batch_size, sequence_length) , dtype=tf.intaa) class _snake_case ( __snake_case ): _lowercase : int = 42 _lowercase : List[str] = 42 _lowercase : List[Any] = '''TensorFlow''' @property def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: return tf.__version__ def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> List[str]: SCREAMING_SNAKE_CASE = self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.') SCREAMING_SNAKE_CASE = self._prepare_inference_func(a_ , a_ , a_) return self._measure_speed(_inference) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Tuple: SCREAMING_SNAKE_CASE = self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.') SCREAMING_SNAKE_CASE = self._prepare_train_func(a_ , a_ , a_) return self._measure_speed(_train) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Optional[Any]: if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , a_) SCREAMING_SNAKE_CASE = self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.') SCREAMING_SNAKE_CASE = self._prepare_inference_func(a_ , a_ , a_) return self._measure_memory(_inference) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Optional[int]: if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , a_) SCREAMING_SNAKE_CASE = self.args.strategy if strategy is None: raise ValueError('A device strategy has to be initialized before using TensorFlow.') SCREAMING_SNAKE_CASE = self._prepare_train_func(a_ , a_ , a_) return self._measure_memory(_train) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> List[Any]: SCREAMING_SNAKE_CASE = self.config_dict[model_name] if self.args.fpaa: raise NotImplementedError('Mixed precision is currently not supported.') SCREAMING_SNAKE_CASE = ( hasattr(a_ , 'architectures') and isinstance(config.architectures , a_) and len(config.architectures) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: SCREAMING_SNAKE_CASE = '''TF''' + config.architectures[0] # prepend 'TF' for tensorflow model SCREAMING_SNAKE_CASE = __import__('transformers' , fromlist=[model_class]) SCREAMING_SNAKE_CASE = getattr(a_ , a_) SCREAMING_SNAKE_CASE = model_cls(a_) except ImportError: raise ImportError( f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to''' ' set `--only_pretrain_model` or `args.only_pretrain_model=True`.') else: SCREAMING_SNAKE_CASE = TF_MODEL_MAPPING[config.__class__](a_) # encoder-decoder has vocab size saved differently SCREAMING_SNAKE_CASE = config.vocab_size if hasattr(a_ , 'vocab_size') else config.encoder.vocab_size SCREAMING_SNAKE_CASE = random_input_ids(a_ , a_ , a_) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla) def encoder_decoder_forward(): return model(a_ , decoder_input_ids=a_ , training=a_) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla) def encoder_forward(): return model(a_ , training=a_) SCREAMING_SNAKE_CASE = encoder_decoder_forward if config.is_encoder_decoder else encoder_forward return _inference def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> str: SCREAMING_SNAKE_CASE = self.config_dict[model_name] if self.args.eager_mode is not False: raise ValueError('Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.') if self.args.fpaa: raise NotImplementedError('Mixed precision is currently not supported.') SCREAMING_SNAKE_CASE = ( hasattr(a_ , 'architectures') and isinstance(config.architectures , a_) and len(config.architectures) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: SCREAMING_SNAKE_CASE = '''TF''' + config.architectures[0] # prepend 'TF' for tensorflow model SCREAMING_SNAKE_CASE = __import__('transformers' , fromlist=[model_class]) SCREAMING_SNAKE_CASE = getattr(a_ , a_) SCREAMING_SNAKE_CASE = model_cls(a_) except ImportError: raise ImportError( f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to''' ' set `--only_pretrain_model` or `args.only_pretrain_model=True`.') else: SCREAMING_SNAKE_CASE = TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](a_) # encoder-decoder has vocab size saved differently SCREAMING_SNAKE_CASE = config.vocab_size if hasattr(a_ , 'vocab_size') else config.encoder.vocab_size SCREAMING_SNAKE_CASE = random_input_ids(a_ , a_ , a_) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla) def encoder_decoder_train(): SCREAMING_SNAKE_CASE = model(a_ , decoder_input_ids=a_ , labels=a_ , training=a_)[0] SCREAMING_SNAKE_CASE = tf.gradients(a_ , model.trainable_variables) return gradients @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla) def encoder_train(): SCREAMING_SNAKE_CASE = model(a_ , labels=a_ , training=a_)[0] SCREAMING_SNAKE_CASE = tf.gradients(a_ , model.trainable_variables) return gradients SCREAMING_SNAKE_CASE = encoder_decoder_train if config.is_encoder_decoder else encoder_train return _train def SCREAMING_SNAKE_CASE__ ( self , a) -> Tuple: with self.args.strategy.scope(): try: if self.args.is_tpu or self.args.use_xla: # run additional 10 times to stabilize compilation for tpu logger.info('Do inference on TPU. Running model 5 times to stabilize compilation') timeit.repeat(a_ , repeat=1 , number=5) # as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average SCREAMING_SNAKE_CASE = timeit.repeat( a_ , repeat=self.args.repeat , number=10 , ) return min(a_) / 10.0 except ResourceExhaustedError as e: self.print_fn(f'''Doesn\'t fit on GPU. {e}''') def SCREAMING_SNAKE_CASE__ ( self , a) -> Any: logger.info( 'Note that TensorFlow allocates more memory than ' 'it might need to speed up computation. ' 'The memory reported here corresponds to the memory ' 'reported by `nvidia-smi`, which can vary depending ' 'on total available memory on the GPU that is used.') with self.args.strategy.scope(): try: if self.args.trace_memory_line_by_line: if not self.args.eager_mode: raise ValueError( '`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory' ' consumption line by line.') SCREAMING_SNAKE_CASE = start_memory_tracing('transformers') if self.args.is_tpu: # tpu raise NotImplementedError( 'Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking' ' with `args.memory=False`') elif self.args.is_gpu: # gpu if not is_pyanvml_available(): logger.warning( 'py3nvml not installed, we won\'t log GPU memory usage. ' 'Install py3nvml (pip install py3nvml) to log information about GPU.') SCREAMING_SNAKE_CASE = '''N/A''' else: logger.info( 'Measuring total GPU usage on GPU device. Make sure to not have additional processes' ' running on the same GPU.') # init nvml nvml.nvmlInit() func() SCREAMING_SNAKE_CASE = nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx) SCREAMING_SNAKE_CASE = nvml.nvmlDeviceGetMemoryInfo(a_) SCREAMING_SNAKE_CASE = meminfo.used SCREAMING_SNAKE_CASE = Memory(a_) # shutdown nvml nvml.nvmlShutdown() else: # cpu if self.args.trace_memory_line_by_line: logger.info( 'When enabling line by line tracing, the max peak memory for CPU is inaccurate in' ' TensorFlow.') SCREAMING_SNAKE_CASE = None else: SCREAMING_SNAKE_CASE = measure_peak_memory_cpu(a_) SCREAMING_SNAKE_CASE = Memory(a_) if isinstance(a_ , a_) else memory_bytes if self.args.trace_memory_line_by_line: SCREAMING_SNAKE_CASE = stop_memory_tracing(a_) if memory is None: SCREAMING_SNAKE_CASE = summary.total else: SCREAMING_SNAKE_CASE = None return memory, summary except ResourceExhaustedError as e: self.print_fn(f'''Doesn\'t fit on GPU. {e}''') return "N/A", None
352
import argparse import datetime def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = { '0': 'Sunday', '1': 'Monday', '2': 'Tuesday', '3': 'Wednesday', '4': 'Thursday', '5': 'Friday', '6': 'Saturday', } SCREAMING_SNAKE_CASE = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(_UpperCAmelCase) < 11: raise ValueError('Must be 10 characters long') # Get month SCREAMING_SNAKE_CASE = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 13: raise ValueError('Month must be between 1 - 12') SCREAMING_SNAKE_CASE = date_input[2] # Validate if sep_a not in ["-", "/"]: raise ValueError('Date separator must be \'-\' or \'/\'') # Get day SCREAMING_SNAKE_CASE = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 32: raise ValueError('Date must be between 1 - 31') # Get second separator SCREAMING_SNAKE_CASE = date_input[5] # Validate if sep_a not in ["-", "/"]: raise ValueError('Date separator must be \'-\' or \'/\'') # Get year SCREAMING_SNAKE_CASE = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 45 < y < 8500: raise ValueError( 'Year out of range. There has to be some sort of limit...right?') # Get datetime obj for validation SCREAMING_SNAKE_CASE = datetime.date(int(_UpperCAmelCase) , int(_UpperCAmelCase) , int(_UpperCAmelCase)) # Start math if m <= 2: SCREAMING_SNAKE_CASE = y - 1 SCREAMING_SNAKE_CASE = m + 12 # maths var SCREAMING_SNAKE_CASE = int(str(_UpperCAmelCase)[:2]) SCREAMING_SNAKE_CASE = int(str(_UpperCAmelCase)[2:]) SCREAMING_SNAKE_CASE = int(2.6 * m - 5.39) SCREAMING_SNAKE_CASE = int(c / 4) SCREAMING_SNAKE_CASE = int(k / 4) SCREAMING_SNAKE_CASE = int(d + k) SCREAMING_SNAKE_CASE = int(t + u + v + x) SCREAMING_SNAKE_CASE = int(z - (2 * c)) SCREAMING_SNAKE_CASE = round(w % 7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError('The date was evaluated incorrectly. Contact developer.') # Response SCREAMING_SNAKE_CASE = F'''Your date {date_input}, is a {days[str(_UpperCAmelCase)]}!''' return response if __name__ == "__main__": import doctest doctest.testmod() a_ : Tuple = argparse.ArgumentParser( description=( 'Find out what day of the week nearly any date is or was. Enter ' 'date as a string in the mm-dd-yyyy or mm/dd/yyyy format' ) ) parser.add_argument( 'date_input', type=str, help='Date as a string (mm-dd-yyyy or mm/dd/yyyy)' ) a_ : Any = parser.parse_args() zeller(args.date_input)
327
0
"""simple docstring""" from string import ascii_lowercase, ascii_uppercase def lowerCamelCase__ (_UpperCAmelCase): if not sentence: return "" SCREAMING_SNAKE_CASE = dict(zip(_A , _A)) return lower_to_upper.get(sentence[0] , sentence[0]) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
353
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 convert_to_rgb, 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 if is_vision_available(): import PIL a_ : Optional[Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : Optional[int] = ['''pixel_values'''] def __init__( self , a = True , a = None , a = PILImageResampling.BICUBIC , a = True , a = 1 / 255 , a = True , a = None , a = None , a = True , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = size if size is not None else {'height': 384, 'width': 384} SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) SCREAMING_SNAKE_CASE = do_resize SCREAMING_SNAKE_CASE = size SCREAMING_SNAKE_CASE = resample 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 SCREAMING_SNAKE_CASE__ ( self , a , a , a = PILImageResampling.BICUBIC , a = None , **a , ) -> np.ndarray: SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}''') SCREAMING_SNAKE_CASE = (size['height'], size['width']) return resize(a , size=a , resample=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a , ) -> Optional[Any]: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a = None , **a , ) -> np.ndarray: return normalize(a , mean=a , std=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> PIL.Image.Image: SCREAMING_SNAKE_CASE = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE = resample if resample is not None else self.resample 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 = size if size is not None else self.size SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) 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 or resample is None: raise ValueError('Size and resample must be specified if do_resize 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_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 = BatchFeature(data={'pixel_values': images} , tensor_type=a) return encoded_outputs
327
0
def lowerCamelCase__ (_UpperCAmelCase): if not isinstance(_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = F'''Input value of [number={number}] must be an integer''' raise TypeError(_UpperCAmelCase) if number < 0: return False SCREAMING_SNAKE_CASE = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
354
class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = val SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None def SCREAMING_SNAKE_CASE__ ( self , a) -> str: if self.val: if val < self.val: if self.left is None: SCREAMING_SNAKE_CASE = Node(a) else: self.left.insert(a) elif val > self.val: if self.right is None: SCREAMING_SNAKE_CASE = Node(a) else: self.right.insert(a) else: SCREAMING_SNAKE_CASE = val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Recursive traversal if root: inorder(root.left , _UpperCAmelCase) res.append(root.val) inorder(root.right , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): # Build BST if len(_UpperCAmelCase) == 0: return arr SCREAMING_SNAKE_CASE = Node(arr[0]) for i in range(1 , len(_UpperCAmelCase)): root.insert(arr[i]) # Traverse BST in order. SCREAMING_SNAKE_CASE = [] inorder(_UpperCAmelCase , _UpperCAmelCase) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
327
0
import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip a_ : List[str] = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def lowerCamelCase__ (_UpperCAmelCase): """simple docstring""" if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): """simple docstring""" return max(metric_fn(snake_case_ , snake_case_) for gt in ground_truths) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): """simple docstring""" SCREAMING_SNAKE_CASE = [line.strip() for line in open(snake_case_ , 'r').readlines()] SCREAMING_SNAKE_CASE = [] if args.gold_data_mode == "qa": SCREAMING_SNAKE_CASE = pd.read_csv(snake_case_ , sep='\t' , header=snake_case_) for answer_list in data[1]: SCREAMING_SNAKE_CASE = ast.literal_eval(snake_case_) answers.append(snake_case_) else: SCREAMING_SNAKE_CASE = [line.strip() for line in open(snake_case_ , 'r').readlines()] SCREAMING_SNAKE_CASE = [[reference] for reference in references] SCREAMING_SNAKE_CASE = 0 for prediction, ground_truths in zip(snake_case_ , snake_case_): total += 1 em += metric_max_over_ground_truths(snake_case_ , snake_case_ , snake_case_) fa += metric_max_over_ground_truths(snake_case_ , snake_case_ , snake_case_) SCREAMING_SNAKE_CASE = 1_00.0 * em / total SCREAMING_SNAKE_CASE = 1_00.0 * fa / total logger.info(F'''F1: {fa:.2f}''') logger.info(F'''EM: {em:.2f}''') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): """simple docstring""" SCREAMING_SNAKE_CASE = args.k SCREAMING_SNAKE_CASE = [line.strip() for line in open(snake_case_ , 'r').readlines()] SCREAMING_SNAKE_CASE = [line.strip() for line in open(snake_case_ , 'r').readlines()] SCREAMING_SNAKE_CASE = 0 for hypo, reference in zip(snake_case_ , snake_case_): SCREAMING_SNAKE_CASE = set(hypo.split('\t')[:k]) SCREAMING_SNAKE_CASE = set(reference.split('\t')) total += 1 em += len(hypo_provenance & ref_provenance) / k SCREAMING_SNAKE_CASE = 1_00.0 * em / total logger.info(F'''Precision@{k}: {em: .2f}''') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): """simple docstring""" def strip_title(_UpperCAmelCase): if title.startswith('\"'): SCREAMING_SNAKE_CASE = title[1:] if title.endswith('\"'): SCREAMING_SNAKE_CASE = title[:-1] return title SCREAMING_SNAKE_CASE = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( snake_case_ , return_tensors='pt' , padding=snake_case_ , truncation=snake_case_ , )["""input_ids"""].to(args.device) SCREAMING_SNAKE_CASE = rag_model.rag.question_encoder(snake_case_) SCREAMING_SNAKE_CASE = question_enc_outputs[0] SCREAMING_SNAKE_CASE = rag_model.retriever( snake_case_ , question_enc_pool_output.cpu().detach().to(torch.floataa).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors='pt' , ) SCREAMING_SNAKE_CASE = rag_model.retriever.index.get_doc_dicts(result.doc_ids) SCREAMING_SNAKE_CASE = [] for docs in all_docs: SCREAMING_SNAKE_CASE = [strip_title(snake_case_) for title in docs["""title"""]] provenance_strings.append('\t'.join(snake_case_)) return provenance_strings def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): """simple docstring""" with torch.no_grad(): SCREAMING_SNAKE_CASE = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( snake_case_ , return_tensors='pt' , padding=snake_case_ , truncation=snake_case_) SCREAMING_SNAKE_CASE = inputs_dict.input_ids.to(args.device) SCREAMING_SNAKE_CASE = inputs_dict.attention_mask.to(args.device) SCREAMING_SNAKE_CASE = rag_model.generate( # rag_model overwrites generate snake_case_ , attention_mask=snake_case_ , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=snake_case_ , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) SCREAMING_SNAKE_CASE = rag_model.retriever.generator_tokenizer.batch_decode(snake_case_ , skip_special_tokens=snake_case_) if args.print_predictions: for q, a in zip(snake_case_ , snake_case_): logger.info('Q: {} - A: {}'.format(snake_case_ , snake_case_)) return answers def lowerCamelCase__ (): """simple docstring""" SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument( '--model_type' , choices=['rag_sequence', 'rag_token', 'bart'] , type=snake_case_ , help=( 'RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the' ' model_name_or_path' ) , ) parser.add_argument( '--index_name' , default=snake_case_ , choices=['exact', 'compressed', 'legacy'] , type=snake_case_ , help='RAG model retriever type' , ) parser.add_argument( '--index_path' , default=snake_case_ , type=snake_case_ , help='Path to the retrieval index' , ) parser.add_argument('--n_docs' , default=5 , type=snake_case_ , help='Number of retrieved docs') parser.add_argument( '--model_name_or_path' , default=snake_case_ , type=snake_case_ , required=snake_case_ , help='Path to pretrained checkpoints or model identifier from huggingface.co/models' , ) parser.add_argument( '--eval_mode' , choices=['e2e', 'retrieval'] , default='e2e' , type=snake_case_ , help=( 'Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates' ' precision@k.' ) , ) parser.add_argument('--k' , default=1 , type=snake_case_ , help='k for the precision@k calculation') parser.add_argument( '--evaluation_set' , default=snake_case_ , type=snake_case_ , required=snake_case_ , help='Path to a file containing evaluation samples' , ) parser.add_argument( '--gold_data_path' , default=snake_case_ , type=snake_case_ , required=snake_case_ , help='Path to a tab-separated file with gold samples' , ) parser.add_argument( '--gold_data_mode' , default='qa' , type=snake_case_ , choices=['qa', 'ans'] , help=( 'Format of the gold data file' 'qa - a single line in the following format: question [tab] answer_list' 'ans - a single line of the gold file contains the expected answer string' ) , ) parser.add_argument( '--predictions_path' , type=snake_case_ , default='predictions.txt' , help='Name of the predictions file, to be stored in the checkpoints directory' , ) parser.add_argument( '--eval_all_checkpoints' , action='store_true' , help='Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number' , ) parser.add_argument( '--eval_batch_size' , default=8 , type=snake_case_ , help='Batch size per GPU/CPU for evaluation.' , ) parser.add_argument( '--recalculate' , help='Recalculate predictions even if the prediction file exists' , action='store_true' , ) parser.add_argument( '--num_beams' , default=4 , type=snake_case_ , help='Number of beams to be used when generating answers' , ) parser.add_argument('--min_length' , default=1 , type=snake_case_ , help='Min length of the generated answers') parser.add_argument('--max_length' , default=50 , type=snake_case_ , help='Max length of the generated answers') parser.add_argument( '--print_predictions' , action='store_true' , help='If True, prints predictions while evaluating.' , ) parser.add_argument( '--print_docs' , action='store_true' , help='If True, prints docs retried while generating.' , ) SCREAMING_SNAKE_CASE = parser.parse_args() SCREAMING_SNAKE_CASE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') return args def lowerCamelCase__ (_UpperCAmelCase): """simple docstring""" SCREAMING_SNAKE_CASE = {} if args.model_type is None: SCREAMING_SNAKE_CASE = infer_model_type(args.model_name_or_path) assert args.model_type is not None if args.model_type.startswith('rag'): SCREAMING_SNAKE_CASE = RagTokenForGeneration if args.model_type == """rag_token""" else RagSequenceForGeneration SCREAMING_SNAKE_CASE = args.n_docs if args.index_name is not None: SCREAMING_SNAKE_CASE = args.index_name if args.index_path is not None: SCREAMING_SNAKE_CASE = args.index_path else: SCREAMING_SNAKE_CASE = BartForConditionalGeneration SCREAMING_SNAKE_CASE = ( [f.path for f in os.scandir(args.model_name_or_path) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info('Evaluate the following checkpoints: %s' , snake_case_) SCREAMING_SNAKE_CASE = get_scores if args.eval_mode == """e2e""" else get_precision_at_k SCREAMING_SNAKE_CASE = evaluate_batch_eae if args.eval_mode == """e2e""" else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path) and (not args.recalculate): logger.info('Calculating metrics based on an existing predictions file: {}'.format(args.predictions_path)) score_fn(snake_case_ , args.predictions_path , args.gold_data_path) continue logger.info('***** Running evaluation for {} *****'.format(snake_case_)) logger.info(' Batch size = %d' , args.eval_batch_size) logger.info(' Predictions will be stored under {}'.format(args.predictions_path)) if args.model_type.startswith('rag'): SCREAMING_SNAKE_CASE = RagRetriever.from_pretrained(snake_case_ , **snake_case_) SCREAMING_SNAKE_CASE = model_class.from_pretrained(snake_case_ , retriever=snake_case_ , **snake_case_) model.retriever.init_retrieval() else: SCREAMING_SNAKE_CASE = model_class.from_pretrained(snake_case_ , **snake_case_) model.to(args.device) with open(args.evaluation_set , 'r') as eval_file, open(args.predictions_path , 'w') as preds_file: SCREAMING_SNAKE_CASE = [] for line in tqdm(snake_case_): questions.append(line.strip()) if len(snake_case_) == args.eval_batch_size: SCREAMING_SNAKE_CASE = evaluate_batch_fn(snake_case_ , snake_case_ , snake_case_) preds_file.write('\n'.join(snake_case_) + '\n') preds_file.flush() SCREAMING_SNAKE_CASE = [] if len(snake_case_) > 0: SCREAMING_SNAKE_CASE = evaluate_batch_fn(snake_case_ , snake_case_ , snake_case_) preds_file.write('\n'.join(snake_case_)) preds_file.flush() score_fn(snake_case_ , args.predictions_path , args.gold_data_path) if __name__ == "__main__": a_ : Tuple = get_args() main(args)
355
import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint a_ : Optional[int] = { '169M': 12, '430M': 24, '1B5': 24, '3B': 32, '7B': 32, '14B': 40, } a_ : Optional[int] = { '169M': 7_68, '430M': 10_24, '1B5': 20_48, '3B': 25_60, '7B': 40_96, '14B': 51_20, } def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = list(state_dict.keys()) for name in state_dict_keys: SCREAMING_SNAKE_CASE = state_dict.pop(_UpperCAmelCase) # emb -> embedding if name.startswith('emb.'): SCREAMING_SNAKE_CASE = name.replace('emb.' , 'embeddings.') # ln_0 -> pre_ln (only present at block 0) if name.startswith('blocks.0.ln0'): SCREAMING_SNAKE_CASE = name.replace('blocks.0.ln0' , 'blocks.0.pre_ln') # att -> attention SCREAMING_SNAKE_CASE = re.sub(R'blocks\.(\d+)\.att' , R'blocks.\1.attention' , _UpperCAmelCase) # ffn -> feed_forward SCREAMING_SNAKE_CASE = re.sub(R'blocks\.(\d+)\.ffn' , R'blocks.\1.feed_forward' , _UpperCAmelCase) # time_mix_k -> time_mix_key and reshape if name.endswith('.time_mix_k'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_k' , '.time_mix_key') # time_mix_v -> time_mix_value and reshape if name.endswith('.time_mix_v'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_v' , '.time_mix_value') # time_mix_r -> time_mix_key and reshape if name.endswith('.time_mix_r'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_r' , '.time_mix_receptance') if name != "head.weight": SCREAMING_SNAKE_CASE = 'rwkv.' + name SCREAMING_SNAKE_CASE = weight return state_dict def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=False , _UpperCAmelCase=None): # 1. If possible, build the tokenizer. if tokenizer_file is None: print('No `--tokenizer_file` provided, we will use the default tokenizer.') SCREAMING_SNAKE_CASE = 5_0277 SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('EleutherAI/gpt-neox-20b') else: SCREAMING_SNAKE_CASE = PreTrainedTokenizerFast(tokenizer_file=_UpperCAmelCase) SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) tokenizer.save_pretrained(_UpperCAmelCase) # 2. Build the config SCREAMING_SNAKE_CASE = list(NUM_HIDDEN_LAYERS_MAPPING.keys()) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: SCREAMING_SNAKE_CASE = candidate break if size is None: raise ValueError('Could not infer the size, please provide it with the `--size` argument.') if size not in possible_sizes: raise ValueError(F'''`size` should be one of {possible_sizes}, got {size}.''') SCREAMING_SNAKE_CASE = RwkvConfig( vocab_size=_UpperCAmelCase , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(_UpperCAmelCase) # 3. Download model file then convert state_dict SCREAMING_SNAKE_CASE = hf_hub_download(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = convert_state_dict(_UpperCAmelCase) # 4. Split in shards and save SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = shard_checkpoint(_UpperCAmelCase) for shard_file, shard in shards.items(): torch.save(_UpperCAmelCase , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) if index is not None: SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , _UpperCAmelCase) # Save the index as well with open(_UpperCAmelCase , 'w' , encoding='utf-8') as f: SCREAMING_SNAKE_CASE = json.dumps(_UpperCAmelCase , indent=2 , sort_keys=_UpperCAmelCase) + '\n' f.write(_UpperCAmelCase) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( 'Cleaning up shards. This may error with an OOM error, it this is the case don\'t worry you still have converted the model.') SCREAMING_SNAKE_CASE = list(shards.keys()) del state_dict del shards gc.collect() for shard_file in shard_files: SCREAMING_SNAKE_CASE = torch.load(os.path.join(_UpperCAmelCase , _UpperCAmelCase)) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError('Please provide a `model_name` to push the model to the Hub.') SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(_UpperCAmelCase) model.push_to_hub(_UpperCAmelCase , max_shard_size='2GB') tokenizer.push_to_hub(_UpperCAmelCase) if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--repo_id', default=None, type=str, required=True, help='Repo ID from which to pull the checkpoint.' ) parser.add_argument( '--checkpoint_file', default=None, type=str, required=True, help='Name of the checkpoint file in the repo.' ) parser.add_argument( '--output_dir', default=None, type=str, required=True, help='Where to save the converted model.' ) parser.add_argument( '--tokenizer_file', default=None, type=str, help='Path to the tokenizer file to use (if not provided, only the model is converted).', ) parser.add_argument( '--size', default=None, type=str, help='Size of the model. Will be inferred from the `checkpoint_file` if not passed.', ) parser.add_argument( '--push_to_hub', action='store_true', help='Push to the Hub the converted model.', ) parser.add_argument( '--model_name', default=None, type=str, help='Name of the pushed model on the Hub, including the username / organization.', ) a_ : Tuple = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
327
0
from __future__ import annotations from typing import Any class _snake_case : def __init__( self , a = 6) -> int: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None self.create_linked_list(a) def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[int]: 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 SCREAMING_SNAKE_CASE__ ( self) -> Any: return ( self.front == self.rear and self.front is not None and self.front.data is None ) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: self.check_can_perform_operation() return self.front.data if self.front else None def SCREAMING_SNAKE_CASE__ ( self , a) -> Union[str, Any]: 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 SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: 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 SCREAMING_SNAKE_CASE__ ( self) -> Tuple: if self.is_empty(): raise Exception('Empty Queue') def SCREAMING_SNAKE_CASE__ ( self) -> int: if self.rear and self.rear.next == self.front: raise Exception('Full Queue') class _snake_case : def __init__( self) -> Tuple: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None if __name__ == "__main__": import doctest doctest.testmod()
356
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def lowerCamelCase__ (_UpperCAmelCase): monkeypatch.setattr('datasets.utils.deprecation_utils._emitted_deprecation_warnings' , set()) @pytest.fixture def lowerCamelCase__ (_UpperCAmelCase): class _snake_case : def __init__( self , a) -> List[Any]: SCREAMING_SNAKE_CASE = metric_id class _snake_case : _lowercase : Optional[Any] = [MetricMock(A__ ) for metric_id in ['''accuracy''', '''mse''', '''precision''', '''codeparrot/apps_metric''']] def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: return self._metrics monkeypatch.setattr('datasets.inspect.huggingface_hub' , HfhMock()) @pytest.mark.parametrize( 'func, args' , [(load_metric, ('metrics/mse',)), (list_metrics, ()), (inspect_metric, ('metrics/mse', 'tmp_path'))]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if "tmp_path" in args: SCREAMING_SNAKE_CASE = tuple(arg if arg != 'tmp_path' else tmp_path for arg in args) with pytest.warns(_UpperCAmelCase , match='https://huggingface.co/docs/evaluate'): func(*_UpperCAmelCase)
327
0
"""simple docstring""" from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) a_ : str = logging.get_logger(__name__) # pylint: disable=invalid-name a_ : Dict = '\n Examples:\n ```py\n >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline\n >>> from diffusers.utils import load_image\n >>> import torch\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior.to("cuda")\n\n >>> prompt = "A red cartoon frog, 4k"\n >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)\n\n >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16\n ... )\n >>> pipe.to("cuda")\n\n >>> init_image = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/frog.png"\n ... )\n\n >>> image = pipe(\n ... image=init_image,\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=100,\n ... strength=0.2,\n ... ).images\n\n >>> image[0].save("red_frog.png")\n ```\n' def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=8): SCREAMING_SNAKE_CASE = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 SCREAMING_SNAKE_CASE = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=512 , _UpperCAmelCase=512): SCREAMING_SNAKE_CASE = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1) SCREAMING_SNAKE_CASE = np.array(pil_image.convert('RGB')) SCREAMING_SNAKE_CASE = arr.astype(np.floataa) / 1_27.5 - 1 SCREAMING_SNAKE_CASE = np.transpose(A__ , [2, 0, 1]) SCREAMING_SNAKE_CASE = torch.from_numpy(A__).unsqueeze(0) return image class _snake_case ( __lowerCamelCase ): def __init__( self , a , a , a , ) -> Any: super().__init__() self.register_modules( unet=UpperCamelCase_ , scheduler=UpperCamelCase_ , movq=UpperCamelCase_ , ) SCREAMING_SNAKE_CASE = 2 ** (len(self.movq.config.block_out_channels) - 1) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> List[str]: # get the original timestep using init_timestep SCREAMING_SNAKE_CASE = min(int(num_inference_steps * strength) , UpperCamelCase_) SCREAMING_SNAKE_CASE = max(num_inference_steps - init_timestep , 0) SCREAMING_SNAKE_CASE = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a=None) -> Dict: if not isinstance(UpperCamelCase_ , (torch.Tensor, PIL.Image.Image, list)): raise ValueError( f'''`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(UpperCamelCase_)}''') SCREAMING_SNAKE_CASE = image.to(device=UpperCamelCase_ , dtype=UpperCamelCase_) SCREAMING_SNAKE_CASE = batch_size * num_images_per_prompt if image.shape[1] == 4: SCREAMING_SNAKE_CASE = image else: if isinstance(UpperCamelCase_ , UpperCamelCase_) and len(UpperCamelCase_) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(UpperCamelCase_)}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''') elif isinstance(UpperCamelCase_ , UpperCamelCase_): SCREAMING_SNAKE_CASE = [ self.movq.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(UpperCamelCase_) ] SCREAMING_SNAKE_CASE = torch.cat(UpperCamelCase_ , dim=0) else: SCREAMING_SNAKE_CASE = self.movq.encode(UpperCamelCase_).latent_dist.sample(UpperCamelCase_) SCREAMING_SNAKE_CASE = self.movq.config.scaling_factor * init_latents SCREAMING_SNAKE_CASE = torch.cat([init_latents] , dim=0) SCREAMING_SNAKE_CASE = init_latents.shape SCREAMING_SNAKE_CASE = randn_tensor(UpperCamelCase_ , generator=UpperCamelCase_ , device=UpperCamelCase_ , dtype=UpperCamelCase_) # get latents SCREAMING_SNAKE_CASE = self.scheduler.add_noise(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_) SCREAMING_SNAKE_CASE = init_latents return latents def SCREAMING_SNAKE_CASE__ ( self , a=0) -> List[str]: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`') SCREAMING_SNAKE_CASE = torch.device(f'''cuda:{gpu_id}''') SCREAMING_SNAKE_CASE = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(UpperCamelCase_ , UpperCamelCase_) def SCREAMING_SNAKE_CASE__ ( self , a=0) -> str: if is_accelerate_available() and is_accelerate_version('>=' , '0.17.0.dev0'): from accelerate import cpu_offload_with_hook else: raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.') SCREAMING_SNAKE_CASE = torch.device(f'''cuda:{gpu_id}''') if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=UpperCamelCase_) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) SCREAMING_SNAKE_CASE = None for cpu_offloaded_model in [self.unet, self.movq]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = cpu_offload_with_hook(UpperCamelCase_ , UpperCamelCase_ , prev_module_hook=UpperCamelCase_) # We'll offload the last model manually. SCREAMING_SNAKE_CASE = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def SCREAMING_SNAKE_CASE__ ( self) -> int: if not hasattr(self.unet , '_hf_hook'): return self.device for module in self.unet.modules(): if ( hasattr(UpperCamelCase_ , '_hf_hook') and hasattr(module._hf_hook , 'execution_device') and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device) return self.device @torch.no_grad() @replace_example_docstring(UpperCamelCase_) def __call__( self , a , a , a , a = 512 , a = 512 , a = 100 , a = 4.0 , a = 0.3 , a = 1 , a = None , a = "pil" , a = True , ) -> Optional[int]: SCREAMING_SNAKE_CASE = self._execution_device SCREAMING_SNAKE_CASE = guidance_scale > 1.0 if isinstance(UpperCamelCase_ , UpperCamelCase_): SCREAMING_SNAKE_CASE = torch.cat(UpperCamelCase_ , dim=0) SCREAMING_SNAKE_CASE = image_embeds.shape[0] if isinstance(UpperCamelCase_ , UpperCamelCase_): SCREAMING_SNAKE_CASE = torch.cat(UpperCamelCase_ , dim=0) if do_classifier_free_guidance: SCREAMING_SNAKE_CASE = image_embeds.repeat_interleave(UpperCamelCase_ , dim=0) SCREAMING_SNAKE_CASE = negative_image_embeds.repeat_interleave(UpperCamelCase_ , dim=0) SCREAMING_SNAKE_CASE = torch.cat([negative_image_embeds, image_embeds] , dim=0).to(dtype=self.unet.dtype , device=UpperCamelCase_) if not isinstance(UpperCamelCase_ , UpperCamelCase_): SCREAMING_SNAKE_CASE = [image] if not all(isinstance(UpperCamelCase_ , (PIL.Image.Image, torch.Tensor)) for i in image): raise ValueError( f'''Input is in incorrect format: {[type(UpperCamelCase_) for i in image]}. Currently, we only support PIL image and pytorch tensor''') SCREAMING_SNAKE_CASE = torch.cat([prepare_image(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_) for i in image] , dim=0) SCREAMING_SNAKE_CASE = image.to(dtype=image_embeds.dtype , device=UpperCamelCase_) SCREAMING_SNAKE_CASE = self.movq.encode(UpperCamelCase_)['latents'] SCREAMING_SNAKE_CASE = latents.repeat_interleave(UpperCamelCase_ , dim=0) self.scheduler.set_timesteps(UpperCamelCase_ , device=UpperCamelCase_) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.get_timesteps(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_) SCREAMING_SNAKE_CASE = timesteps[:1].repeat(batch_size * num_images_per_prompt) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = downscale_height_and_width(UpperCamelCase_ , UpperCamelCase_ , self.movq_scale_factor) SCREAMING_SNAKE_CASE = self.prepare_latents( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , image_embeds.dtype , UpperCamelCase_ , UpperCamelCase_) for i, t in enumerate(self.progress_bar(UpperCamelCase_)): # expand the latents if we are doing classifier free guidance SCREAMING_SNAKE_CASE = torch.cat([latents] * 2) if do_classifier_free_guidance else latents SCREAMING_SNAKE_CASE = {'image_embeds': image_embeds} SCREAMING_SNAKE_CASE = self.unet( sample=UpperCamelCase_ , timestep=UpperCamelCase_ , encoder_hidden_states=UpperCamelCase_ , added_cond_kwargs=UpperCamelCase_ , return_dict=UpperCamelCase_ , )[0] if do_classifier_free_guidance: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = noise_pred.split(latents.shape[1] , dim=1) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = noise_pred.chunk(2) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = variance_pred.chunk(2) SCREAMING_SNAKE_CASE = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) SCREAMING_SNAKE_CASE = torch.cat([noise_pred, variance_pred_text] , dim=1) if not ( hasattr(self.scheduler.config , 'variance_type') and self.scheduler.config.variance_type in ["learned", "learned_range"] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = noise_pred.split(latents.shape[1] , dim=1) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE = self.scheduler.step( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , generator=UpperCamelCase_ , )[0] # post-processing SCREAMING_SNAKE_CASE = self.movq.decode(UpperCamelCase_ , force_not_quantize=UpperCamelCase_)['sample'] if output_type not in ["pt", "np", "pil"]: raise ValueError(f'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}''') if output_type in ["np", "pil"]: SCREAMING_SNAKE_CASE = image * 0.5 + 0.5 SCREAMING_SNAKE_CASE = image.clamp(0 , 1) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1).float().numpy() if output_type == "pil": SCREAMING_SNAKE_CASE = self.numpy_to_pil(UpperCamelCase_) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCamelCase_)
357
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : Any = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Dict = ['MLukeTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys a_ : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
327
0
def lowerCamelCase__ (_UpperCAmelCase): if upper_limit < 0: raise ValueError('Limit for the Catalan sequence must be ≥ 0') SCREAMING_SNAKE_CASE = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 SCREAMING_SNAKE_CASE = 1 if upper_limit > 0: SCREAMING_SNAKE_CASE = 1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1): for j in range(_UpperCAmelCase): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print('\n********* Catalan Numbers Using Dynamic Programming ************\n') print('\n*** Enter -1 at any time to quit ***') print('\nEnter the upper limit (≥ 0) for the Catalan number sequence: ', end='') try: while True: a_ : Optional[int] = int(input().strip()) if N < 0: print('\n********* Goodbye!! ************') break else: print(f"""The Catalan numbers from 0 through {N} are:""") print(catalan_numbers(N)) print('Try another upper limit for the sequence: ', end='') except (NameError, ValueError): print('\n********* Invalid input, goodbye! ************\n') import doctest doctest.testmod()
358
from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer a_ : List[Any] = logging.get_logger(__name__) a_ : Union[str, Any] = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} a_ : str = { 'vocab_file': { 'allegro/herbert-base-cased': 'https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json' }, 'merges_file': { 'allegro/herbert-base-cased': 'https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt' }, } a_ : List[Any] = {'allegro/herbert-base-cased': 5_14} a_ : Dict = {} class _snake_case ( A__ ): _lowercase : Dict = VOCAB_FILES_NAMES _lowercase : int = PRETRAINED_VOCAB_FILES_MAP _lowercase : Any = PRETRAINED_INIT_CONFIGURATION _lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : Any = HerbertTokenizer def __init__( self , a=None , a=None , a=None , a="<s>" , a="<unk>" , a="<pad>" , a="<mask>" , a="</s>" , **a , ) -> Dict: super().__init__( a , a , tokenizer_file=a , cls_token=a , unk_token=a , pad_token=a , mask_token=a , sep_token=a , **a , ) def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: SCREAMING_SNAKE_CASE = [self.cls_token_id] SCREAMING_SNAKE_CASE = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = False) -> List[int]: 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] + ([0] * len(a)) + [1] def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: 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 SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> Tuple[str]: SCREAMING_SNAKE_CASE = self._tokenizer.model.save(a , name=a) return tuple(a)
327
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) a_ : Tuple = { "configuration_mobilevit": ["MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileViTConfig", "MobileViTOnnxConfig"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : int = ["MobileViTFeatureExtractor"] a_ : Union[str, Any] = ["MobileViTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Any = [ "MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "MobileViTForImageClassification", "MobileViTForSemanticSegmentation", "MobileViTModel", "MobileViTPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Dict = [ "TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFMobileViTForImageClassification", "TFMobileViTForSemanticSegmentation", "TFMobileViTModel", "TFMobileViTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilevit import MobileViTFeatureExtractor from .image_processing_mobilevit import MobileViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilevit import ( MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel, MobileViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilevit import ( TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel, TFMobileViTPreTrainedModel, ) else: import sys a_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
359
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput a_ : Dict = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class _snake_case ( A__ ): def __init__( self , *a , a=None , a=None , a=None , **a) -> List[Any]: super().__init__(*a , **a) SCREAMING_SNAKE_CASE = eval_examples SCREAMING_SNAKE_CASE = post_process_function SCREAMING_SNAKE_CASE = quant_trainer_args SCREAMING_SNAKE_CASE = 128 # default number of calibration samples def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Union[str, Any]: if calib_dataset is None and self.calib_dataset is None: raise ValueError('Trainer: calibration requires an calib_dataset.') SCREAMING_SNAKE_CASE = calib_dataset if calib_dataset is not None else self.calib_dataset SCREAMING_SNAKE_CASE = self._remove_unused_columns(a , description='Calibration') return DataLoader( a , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=a , ) def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.train_dataset if calib_dataset is None else calib_dataset SCREAMING_SNAKE_CASE = self.get_calib_dataloader(a) SCREAMING_SNAKE_CASE = self.model quant_trainer.configure_model(a , self.quant_trainer_args , calib=a) model.eval() quant_trainer.enable_calibration(a) logger.info('***** Running calibration *****') logger.info(f''' Num examples = {self.calib_num}''') logger.info(f''' Batch size = {calib_dataloader.batch_size}''') for step, inputs in enumerate(a): # Prediction step SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.prediction_step(a , a , prediction_loss_only=a) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = model def SCREAMING_SNAKE_CASE__ ( self , a=None , a=None , a=None , a = "eval") -> str: 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 = 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 , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions) 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) self.log(a) else: SCREAMING_SNAKE_CASE = {} 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 SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a = "test") -> Optional[Any]: 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 = 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 , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions , '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) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=a) def SCREAMING_SNAKE_CASE__ ( self , a="./") -> List[Any]: SCREAMING_SNAKE_CASE = self.eval_dataset SCREAMING_SNAKE_CASE = self.get_eval_dataloader(a) SCREAMING_SNAKE_CASE = next(iter(a)) # saving device - to make it consistent SCREAMING_SNAKE_CASE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # convert to tuple SCREAMING_SNAKE_CASE = tuple(v.to(a) for k, v in batch.items()) logger.info('Converting model to be onnx compatible') from pytorch_quantization.nn import TensorQuantizer SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = self.model.to(a) model.eval() model.float() SCREAMING_SNAKE_CASE = model.module if hasattr(a , 'module') else model quant_trainer.configure_model(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = os.path.join(a , 'model.onnx') logger.info(f'''exporting model to {output_model_file}''') SCREAMING_SNAKE_CASE = {0: 'batch_size', 1: 'seq_len'} torch.onnx.export( a , a , a , export_params=a , opset_version=13 , do_constant_folding=a , input_names=['input_ids', 'attention_mask', 'token_type_ids'] , output_names=['output_start_logits', 'output_end_logits'] , dynamic_axes={ 'input_ids': axes, 'attention_mask': axes, 'token_type_ids': axes, 'output_start_logits': axes, 'output_end_logits': axes, } , verbose=a , ) logger.info('onnx export finished')
327
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_chinese_clip import ChineseCLIPImageProcessor a_ : int = logging.get_logger(__name__) class _snake_case ( A__ ): def __init__( self , *a , **a) -> Dict: warnings.warn( 'The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use ChineseCLIPImageProcessor instead.' , __lowerCAmelCase , ) super().__init__(*__lowerCAmelCase , **__lowerCAmelCase)
360
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging a_ : Union[str, Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : List[str] = ['''pixel_values'''] def __init__( self , a = True , a = 1 / 255 , a = True , a = 8 , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = do_rescale SCREAMING_SNAKE_CASE = rescale_factor SCREAMING_SNAKE_CASE = do_pad SCREAMING_SNAKE_CASE = pad_size def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a) -> np.ndarray: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_image_size(a) SCREAMING_SNAKE_CASE = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE = (old_width // size + 1) * size - old_width return pad(a , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> List[str]: 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_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE = pad_size if pad_size is not None else self.pad_size 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_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE = [to_numpy_array(a) for image in images] if do_rescale: SCREAMING_SNAKE_CASE = [self.rescale(image=a , scale=a) for image in images] if do_pad: SCREAMING_SNAKE_CASE = [self.pad(a , size=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)
327
0
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, 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 numpy as np import tensorflow as tf from transformers import ( TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST, FlaubertConfig, TFFlaubertForMultipleChoice, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForSequenceClassification, TFFlaubertForTokenClassification, TFFlaubertModel, TFFlaubertWithLMHeadModel, ) class _snake_case : def __init__( self , a , ) -> Union[str, Any]: 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 = True SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = 99 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 32 SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = 4 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 = 'last' SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] , dtype=tf.floataa) SCREAMING_SNAKE_CASE = None if self.use_input_lengths: SCREAMING_SNAKE_CASE = ( ids_tensor([self.batch_size] , vocab_size=2) + self.seq_length - 2 ) # small variation of seq_length SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.n_langs) 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] , 2 , dtype=tf.floataa) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices) SCREAMING_SNAKE_CASE = FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , bos_token_id=self.bos_token_id , ) return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> Tuple: SCREAMING_SNAKE_CASE = TFFlaubertModel(config=_snake_case) SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'lengths': input_lengths, 'langs': token_type_ids} SCREAMING_SNAKE_CASE = model(_snake_case) SCREAMING_SNAKE_CASE = [input_ids, input_mask] SCREAMING_SNAKE_CASE = model(_snake_case) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE = TFFlaubertWithLMHeadModel(_snake_case) SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'lengths': input_lengths, 'langs': token_type_ids} SCREAMING_SNAKE_CASE = model(_snake_case) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> List[str]: SCREAMING_SNAKE_CASE = TFFlaubertForQuestionAnsweringSimple(_snake_case) SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'lengths': input_lengths} SCREAMING_SNAKE_CASE = model(_snake_case) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> int: SCREAMING_SNAKE_CASE = TFFlaubertForSequenceClassification(_snake_case) SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'lengths': input_lengths} SCREAMING_SNAKE_CASE = model(_snake_case) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> int: SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = TFFlaubertForTokenClassification(config=_snake_case) SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} SCREAMING_SNAKE_CASE = model(_snake_case) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> List[Any]: SCREAMING_SNAKE_CASE = self.num_choices SCREAMING_SNAKE_CASE = TFFlaubertForMultipleChoice(config=_snake_case) SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(_snake_case , 1) , (1, self.num_choices, 1)) SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(_snake_case , 1) , (1, self.num_choices, 1)) SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(_snake_case , 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(_snake_case) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def SCREAMING_SNAKE_CASE__ ( self) -> Any: 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 ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) = config_and_inputs SCREAMING_SNAKE_CASE = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'langs': token_type_ids, 'lengths': input_lengths, } return config, inputs_dict @require_tf class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : Dict = ( ( TFFlaubertModel, TFFlaubertWithLMHeadModel, TFFlaubertForSequenceClassification, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForTokenClassification, TFFlaubertForMultipleChoice, ) if is_tf_available() else () ) _lowercase : int = ( (TFFlaubertWithLMHeadModel,) if is_tf_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable _lowercase : str = ( { '''feature-extraction''': TFFlaubertModel, '''fill-mask''': TFFlaubertWithLMHeadModel, '''question-answering''': TFFlaubertForQuestionAnsweringSimple, '''text-classification''': TFFlaubertForSequenceClassification, '''token-classification''': TFFlaubertForTokenClassification, '''zero-shot''': TFFlaubertForSequenceClassification, } if is_tf_available() else {} ) _lowercase : Any = False _lowercase : Any = False def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a) -> Any: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('Fast') ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = TFFlaubertModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=_snake_case , emb_dim=37) def SCREAMING_SNAKE_CASE__ ( self) -> str: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*_snake_case) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*_snake_case) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*_snake_case) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*_snake_case) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_token_classification(*_snake_case) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_multiple_choice(*_snake_case) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: for model_name in TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = TFFlaubertModel.from_pretrained(_snake_case) self.assertIsNotNone(_snake_case) @require_tf @require_sentencepiece @require_tokenizers class _snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = TFFlaubertModel.from_pretrained('jplu/tf-flaubert-small-cased') SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[0, 158, 735, 2592, 1424, 6727, 82, 1]] , dtype=tf.intaa , ) # "J'aime flaubert !" SCREAMING_SNAKE_CASE = model(_snake_case)[0] SCREAMING_SNAKE_CASE = tf.TensorShape((1, 8, 512)) self.assertEqual(output.shape , _snake_case) # compare the actual values for a slice. SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [ [ [-1.8_76_87_73, -1.56_65_55, 0.27_07_24_18], [-1.6_92_00_38, -0.5_87_35_05, 1.9_32_95_99], [-2.9_56_39_85, -1.6_99_38_35, 1.7_97_20_52], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4))
361
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class _snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = TFCamembertModel.from_pretrained('jplu/tf-camembert-base') SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 2_5543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" SCREAMING_SNAKE_CASE = model(a)['last_hidden_state'] SCREAMING_SNAKE_CASE = tf.TensorShape((1, 10, 768)) self.assertEqual(output.shape , a) # compare the actual values for a slice. SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[[-0.02_54, 0.02_35, 0.10_27], [0.06_06, -0.18_11, -0.04_18], [-0.15_61, -0.11_27, 0.26_87]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4))
327
0
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging a_ : str = logging.get_logger(__name__) a_ : Optional[int] = { 'EleutherAI/gpt-j-6B': 'https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json', # See all GPT-J models at https://huggingface.co/models?filter=gpt_j } class _snake_case ( __snake_case ): _lowercase : Dict = 'gptj' _lowercase : int = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , a=5_0400 , a=2048 , a=4096 , a=28 , a=16 , a=64 , a=None , a="gelu_new" , a=0.0 , a=0.0 , a=0.0 , a=1E-5 , a=0.02 , a=True , a=5_0256 , a=5_0256 , a=False , **a , ) -> int: SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = n_positions SCREAMING_SNAKE_CASE = n_embd SCREAMING_SNAKE_CASE = n_layer SCREAMING_SNAKE_CASE = n_head SCREAMING_SNAKE_CASE = n_inner SCREAMING_SNAKE_CASE = rotary_dim SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_pdrop SCREAMING_SNAKE_CASE = embd_pdrop SCREAMING_SNAKE_CASE = attn_pdrop SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id super().__init__( bos_token_id=a , eos_token_id=a , tie_word_embeddings=a , **a) class _snake_case ( __snake_case ): def __init__( self , a , a = "default" , a = None , a = False , ) -> Union[str, Any]: super().__init__(a , task=a , patching_specs=a , use_past=a) if not getattr(self._config , 'pad_token_id' , a): # TODO: how to do that better? SCREAMING_SNAKE_CASE = 0 @property def SCREAMING_SNAKE_CASE__ ( self) -> Mapping[str, Mapping[int, str]]: SCREAMING_SNAKE_CASE = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}) if self.use_past: self.fill_with_past_key_values_(a , direction='inputs') SCREAMING_SNAKE_CASE = {0: 'batch', 1: 'past_sequence + sequence'} else: SCREAMING_SNAKE_CASE = {0: 'batch', 1: 'sequence'} return common_inputs @property def SCREAMING_SNAKE_CASE__ ( self) -> int: return self._config.n_layer @property def SCREAMING_SNAKE_CASE__ ( self) -> int: return self._config.n_head def SCREAMING_SNAKE_CASE__ ( self , a , a = -1 , a = -1 , a = False , a = None , ) -> Mapping[str, Any]: SCREAMING_SNAKE_CASE = super(a , self).generate_dummy_inputs( a , batch_size=a , seq_length=a , is_pair=a , framework=a) # We need to order the input in the way they appears in the forward() SCREAMING_SNAKE_CASE = OrderedDict({'input_ids': common_inputs['input_ids']}) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.') else: import torch SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = common_inputs['input_ids'].shape # Not using the same length for past_key_values SCREAMING_SNAKE_CASE = seqlen + 2 SCREAMING_SNAKE_CASE = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) SCREAMING_SNAKE_CASE = [ (torch.zeros(a), torch.zeros(a)) for _ in range(self.num_layers) ] SCREAMING_SNAKE_CASE = common_inputs['attention_mask'] if self.use_past: SCREAMING_SNAKE_CASE = ordered_inputs['attention_mask'].dtype SCREAMING_SNAKE_CASE = torch.cat( [ordered_inputs['attention_mask'], torch.ones(a , a , dtype=a)] , dim=1) return ordered_inputs @property def SCREAMING_SNAKE_CASE__ ( self) -> int: return 13
362
from scipy.stats import pearsonr import datasets a_ : Optional[int] = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n' a_ : Optional[int] = '\nArgs:\n predictions (`list` of `int`): Predicted class labels, as returned by a model.\n references (`list` of `int`): Ground truth labels.\n return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n Example 1-A simple example using only predictions and references.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n\n Example 2-The same as Example 1, but that also returns the `p-value`.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n >>> print(sorted(list(results.keys())))\n [\'p-value\', \'pearsonr\']\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n >>> print(round(results[\'p-value\'], 2))\n 0.15\n' a_ : Any = '\n@article{2020SciPy-NMeth,\nauthor = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Antonio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\njournal = {Nature Methods},\nyear = {2020},\nvolume = {17},\npages = {261--272},\nadsurl = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('float'), 'references': datasets.Value('float'), }) , reference_urls=['https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=False) -> Optional[Any]: if return_pvalue: SCREAMING_SNAKE_CASE = pearsonr(a , a) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(a , a)[0])}
327
0
from collections.abc import Sequence def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = False): if not arr: return 0 SCREAMING_SNAKE_CASE = 0 if allow_empty_subarrays else float('-inf') SCREAMING_SNAKE_CASE = 0.0 for num in arr: SCREAMING_SNAKE_CASE = max(0 if allow_empty_subarrays else num , curr_sum + num) SCREAMING_SNAKE_CASE = max(UpperCamelCase__ , UpperCamelCase__) return max_sum if __name__ == "__main__": from doctest import testmod testmod() a_ : Optional[Any] = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(f"""{max_subarray_sum(nums) = }""")
363
import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class _snake_case ( unittest.TestCase ): _lowercase : List[Any] = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING _lowercase : int = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Any: SCREAMING_SNAKE_CASE = TextaTextGenerationPipeline(model=a , tokenizer=a) return generator, ["Something to write", "Something else"] def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Any: SCREAMING_SNAKE_CASE = generator('Something there') self.assertEqual(a , [{'generated_text': ANY(a)}]) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]['generated_text'].startswith('Something there')) SCREAMING_SNAKE_CASE = generator(['This is great !', 'Something else'] , num_return_sequences=2 , do_sample=a) self.assertEqual( a , [ [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], ] , ) SCREAMING_SNAKE_CASE = generator( ['This is great !', 'Something else'] , num_return_sequences=2 , batch_size=2 , do_sample=a) self.assertEqual( a , [ [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], ] , ) with self.assertRaises(a): generator(4) @require_torch def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='pt') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE = generator('Something there' , do_sample=a) self.assertEqual(a , [{'generated_text': ''}]) SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = generator( 'Something there' , num_return_sequences=a , num_beams=a , ) SCREAMING_SNAKE_CASE = [ {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': ''}, ] self.assertEqual(a , a) SCREAMING_SNAKE_CASE = generator('This is a test' , do_sample=a , num_return_sequences=2 , return_tensors=a) self.assertEqual( a , [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ] , ) SCREAMING_SNAKE_CASE = generator.model.config.eos_token_id SCREAMING_SNAKE_CASE = '<pad>' SCREAMING_SNAKE_CASE = generator( ['This is a test', 'This is a second test'] , do_sample=a , num_return_sequences=2 , batch_size=2 , return_tensors=a , ) self.assertEqual( a , [ [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ], [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ], ] , ) @require_tf def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='tf') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE = generator('Something there' , do_sample=a) self.assertEqual(a , [{'generated_text': ''}])
327
0
def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if height >= 1: move_tower(height - 1 , _a , _a , _a) move_disk(_a , _a) move_tower(height - 1 , _a , _a , _a) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): print('moving disk from' , _a , 'to' , _a) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = int(input('Height of hanoi: ').strip()) move_tower(_a , 'A' , 'B' , 'C') if __name__ == "__main__": main()
364
import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights SCREAMING_SNAKE_CASE = FlaxDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=a , cache_dir=a) SCREAMING_SNAKE_CASE = [t[-1] for t in os.walk(os.path.join(a , os.listdir(a)[0] , 'snapshots'))] SCREAMING_SNAKE_CASE = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith('.bin') for f in files) @slow @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 4 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 4.1_51_47_45) < 1E-3 assert np.abs(np.abs(a , dtype=np.floataa).sum() - 4_99_47.8_75) < 5E-1 SCREAMING_SNAKE_CASE = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]))) assert len(a) == num_samples def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='flax' , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.05_65_24_01)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_38_38_08.2)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_00_39_06)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_37_35_16.75)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_00_39_06)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_37_35_16.75)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = FlaxDDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , set_alpha_to_one=a , steps_offset=1 , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , scheduler=a , safety_checker=a , ) SCREAMING_SNAKE_CASE = scheduler.create_state() SCREAMING_SNAKE_CASE = scheduler_state SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.0_45_04_39_45)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_34_76_93.5)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = jax.random.split(jax.random.PRNGKey(0) , a) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a , ) SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) SCREAMING_SNAKE_CASE = images[2, 0, 256, 10:17, 1] # With memory efficient attention SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a , use_memory_efficient_attention=a , ) SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , jit=a).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) SCREAMING_SNAKE_CASE = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice).max() < 1E-2
327
0
def lowerCamelCase__ (_UpperCAmelCase = "The quick brown fox jumps over the lazy dog" , ): SCREAMING_SNAKE_CASE = set() # Replace all the whitespace in our sentence SCREAMING_SNAKE_CASE = input_str.replace(' ' , '') for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower()) return len(_UpperCAmelCase) == 26 def lowerCamelCase__ (_UpperCAmelCase = "The quick brown fox jumps over the lazy dog" , ): SCREAMING_SNAKE_CASE = [False] * 26 for char in input_str: if char.islower(): SCREAMING_SNAKE_CASE = True elif char.isupper(): SCREAMING_SNAKE_CASE = True return all(_UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase = "The quick brown fox jumps over the lazy dog" , ): return len({char for char in input_str.lower() if char.isalpha()}) == 26 def lowerCamelCase__ (): from timeit import timeit SCREAMING_SNAKE_CASE = "from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest" print(timeit('is_pangram()' , setup=_UpperCAmelCase)) print(timeit('is_pangram_faster()' , setup=_UpperCAmelCase)) print(timeit('is_pangram_fastest()' , setup=_UpperCAmelCase)) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
365
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets a_ : Tuple = '\\n@inproceedings{lin-2004-rouge,\n title = "{ROUGE}: A Package for Automatic Evaluation of Summaries",\n author = "Lin, Chin-Yew",\n booktitle = "Text Summarization Branches Out",\n month = jul,\n year = "2004",\n address = "Barcelona, Spain",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W04-1013",\n pages = "74--81",\n}\n' a_ : List[Any] = '\\nROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for\nevaluating automatic summarization and machine translation software in natural language processing.\nThe metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.\n\nNote that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.\n\nThis metrics is a wrapper around Google Research reimplementation of ROUGE:\nhttps://github.com/google-research/google-research/tree/master/rouge\n' a_ : List[str] = '\nCalculates average rouge scores for a list of hypotheses and 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 rouge_types: A list of rouge types to calculate.\n Valid names:\n `"rouge{n}"` (e.g. `"rouge1"`, `"rouge2"`) where: {n} is the n-gram based scoring,\n `"rougeL"`: Longest common subsequence based scoring.\n `"rougeLSum"`: rougeLsum splits text using `"\n"`.\n See details in https://github.com/huggingface/datasets/issues/617\n use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.\n use_aggregator: Return aggregates if this is set to True\nReturns:\n rouge1: rouge_1 (precision, recall, f1),\n rouge2: rouge_2 (precision, recall, f1),\n rougeL: rouge_l (precision, recall, f1),\n rougeLsum: rouge_lsum (precision, recall, f1)\nExamples:\n\n >>> rouge = datasets.load_metric(\'rouge\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> results = rouge.compute(predictions=predictions, references=references)\n >>> print(list(results.keys()))\n [\'rouge1\', \'rouge2\', \'rougeL\', \'rougeLsum\']\n >>> print(results["rouge1"])\n AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))\n >>> print(results["rouge1"].mid.fmeasure)\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence'), 'references': datasets.Value('string' , id='sequence'), }) , codebase_urls=['https://github.com/google-research/google-research/tree/master/rouge'] , reference_urls=[ 'https://en.wikipedia.org/wiki/ROUGE_(metric)', 'https://github.com/google-research/google-research/tree/master/rouge', ] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a=True , a=False) -> Optional[Any]: if rouge_types is None: SCREAMING_SNAKE_CASE = ['rouge1', 'rouge2', 'rougeL', 'rougeLsum'] SCREAMING_SNAKE_CASE = rouge_scorer.RougeScorer(rouge_types=a , use_stemmer=a) if use_aggregator: SCREAMING_SNAKE_CASE = scoring.BootstrapAggregator() else: SCREAMING_SNAKE_CASE = [] for ref, pred in zip(a , a): SCREAMING_SNAKE_CASE = scorer.score(a , a) if use_aggregator: aggregator.add_scores(a) else: scores.append(a) if use_aggregator: SCREAMING_SNAKE_CASE = aggregator.aggregate() else: SCREAMING_SNAKE_CASE = {} for key in scores[0]: SCREAMING_SNAKE_CASE = [score[key] for score in scores] return result
327
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ : Dict = { 'configuration_xlm_roberta_xl': [ 'XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLMRobertaXLConfig', 'XLMRobertaXLOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST', 'XLMRobertaXLForCausalLM', 'XLMRobertaXLForMaskedLM', 'XLMRobertaXLForMultipleChoice', 'XLMRobertaXLForQuestionAnswering', 'XLMRobertaXLForSequenceClassification', 'XLMRobertaXLForTokenClassification', 'XLMRobertaXLModel', 'XLMRobertaXLPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaXLConfig, XLMRobertaXLOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaXLForCausalLM, XLMRobertaXLForMaskedLM, XLMRobertaXLForMultipleChoice, XLMRobertaXLForQuestionAnswering, XLMRobertaXLForSequenceClassification, XLMRobertaXLForTokenClassification, XLMRobertaXLModel, XLMRobertaXLPreTrainedModel, ) else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure)
366
import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def lowerCamelCase__ (_UpperCAmelCase): if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class _snake_case ( nn.Module ): def __init__( self , a , a) -> Union[str, Any]: super().__init__() SCREAMING_SNAKE_CASE = module SCREAMING_SNAKE_CASE = nn.Sequential( nn.Linear(module.in_features , a , bias=a) , nn.Linear(a , module.out_features , bias=a) , ) SCREAMING_SNAKE_CASE = (2.0 / (5 * min(module.in_features , module.out_features))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=a) nn.init.zeros_(self.adapter[1].weight) self.adapter.to(module.weight.device) def SCREAMING_SNAKE_CASE__ ( self , a , *a , **a) -> Any: return self.module(a , *a , **a) + self.adapter(a) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): # We keep the constants inside the init function and model loading inside setUp function # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) # Therefore here we use only bloom-1b3 to test our module _lowercase : Union[str, Any] = '''bigscience/bloom-1b7''' # Constant values _lowercase : str = 2.109_6595_5269_2574 _lowercase : Any = '''Hello my name is''' _lowercase : Any = set() EXPECTED_OUTPUTS.add('''Hello my name is John and I am a professional photographer. I''' ) EXPECTED_OUTPUTS.add('''Hello my name is John.\nI am a friend of your father.\n''' ) EXPECTED_OUTPUTS.add('''Hello my name is John Doe, I am a student at the University''' ) _lowercase : Union[str, Any] = 10 def SCREAMING_SNAKE_CASE__ ( self) -> Any: # Models and tokenizer SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(self.model_name) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: super().setUp() # Models and tokenizer SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map='auto') SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_abit.config self.assertTrue(hasattr(a , 'quantization_config')) SCREAMING_SNAKE_CASE = config.to_dict() SCREAMING_SNAKE_CASE = config.to_diff_dict() SCREAMING_SNAKE_CASE = config.to_json_string() def SCREAMING_SNAKE_CASE__ ( self) -> Any: from bitsandbytes.nn import Paramsabit SCREAMING_SNAKE_CASE = self.model_fpaa.get_memory_footprint() SCREAMING_SNAKE_CASE = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE) SCREAMING_SNAKE_CASE = get_some_linear_layer(self.model_abit) self.assertTrue(linear.weight.__class__ == Paramsabit) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(a , torch.nn.Linear): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = self.model_abit.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = BitsAndBytesConfig() SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = model_abit_from_config.generate( input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) def SCREAMING_SNAKE_CASE__ ( self) -> str: with self.assertRaises(a), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = BitsAndBytesConfig() with self.assertRaises(a): SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=a , load_in_abit=a , device_map='auto' , bnb_abit_quant_type='nf4' , ) def SCREAMING_SNAKE_CASE__ ( self) -> int: with self.assertRaises(a): # Tries with `str` self.model_abit.to('cpu') with self.assertRaises(a): # Tries with a `dtype`` self.model_abit.to(torch.floataa) with self.assertRaises(a): # Tries with a `device` self.model_abit.to(torch.device('cuda:0')) with self.assertRaises(a): # Tries with a `device` self.model_abit.float() with self.assertRaises(a): # Tries with a `device` self.model_abit.half() # Test if we did not break anything SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = self.model_fpaa.to(torch.floataa) SCREAMING_SNAKE_CASE = self.model_fpaa.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.to('cpu') # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.half() # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.float() def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained('t5-small' , load_in_abit=a , device_map='auto') self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Tuple: SCREAMING_SNAKE_CASE = 't5-small' SCREAMING_SNAKE_CASE = 'google/flan-t5-small' # flan-t5 uses dense-act instead of dense-relu-dense SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(cls.model_name) SCREAMING_SNAKE_CASE = 'Translate in German: Hello, my dog is cute' def SCREAMING_SNAKE_CASE__ ( self) -> Dict: gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: from transformers import TaForConditionalGeneration SCREAMING_SNAKE_CASE = TaForConditionalGeneration._keep_in_fpaa_modules SCREAMING_SNAKE_CASE = None # test with `t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) # test with `flan-t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) SCREAMING_SNAKE_CASE = modules def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit)) SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) # test with `flan-t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> str: super().setUp() # model_name SCREAMING_SNAKE_CASE = 'bigscience/bloom-560m' SCREAMING_SNAKE_CASE = 't5-small' # Different types of model SCREAMING_SNAKE_CASE = AutoModel.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # Sequence classification model SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=a , device_map='auto') # CausalLM model SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # Seq2seq model SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=a , device_map='auto') def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Dict: del self.pipe gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = pipeline( 'text-generation' , model=self.model_name , model_kwargs={'device_map': 'auto', 'load_in_4bit': True, 'torch_dtype': torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass SCREAMING_SNAKE_CASE = self.pipe(self.input_text) self.assertIn(pipeline_output[0]['generated_text'] , self.EXPECTED_OUTPUTS) @require_torch_multi_gpu class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> int: super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=a , device_map='balanced') # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values()) , {0, 1}) # Check that inference pass works on the model SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') # Second real batch SCREAMING_SNAKE_CASE = model_parallel.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = 'facebook/opt-350m' super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Any: if version.parse(importlib.metadata.version('bitsandbytes')) < version.parse('0.37.0'): return # Step 1: freeze all parameters SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a) self.assertEqual(set(model.hf_device_map.values()) , {torch.cuda.current_device()}) for param in model.parameters(): SCREAMING_SNAKE_CASE = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability SCREAMING_SNAKE_CASE = param.data.to(torch.floataa) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(a)): SCREAMING_SNAKE_CASE = LoRALayer(module.q_proj , rank=16) SCREAMING_SNAKE_CASE = LoRALayer(module.k_proj , rank=16) SCREAMING_SNAKE_CASE = LoRALayer(module.v_proj , rank=16) # Step 3: dummy batch SCREAMING_SNAKE_CASE = self.tokenizer('Test batch ' , return_tensors='pt').to(0) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): SCREAMING_SNAKE_CASE = model.forward(**a) out.logits.norm().backward() for module in model.modules(): if isinstance(a , a): self.assertTrue(module.adapter[1].weight.grad is not None) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0) elif isinstance(a , nn.Embedding): self.assertTrue(module.weight.grad is None) class _snake_case ( A__ ): _lowercase : str = '''gpt2-xl''' _lowercase : Union[str, Any] = 3.3191_8548_5415_2187
327
0
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a_ : List[str] = logging.get_logger(__name__) a_ : List[str] = '▁' a_ : str = {'vocab_file': 'sentencepiece.bpe.model'} a_ : Dict = { 'vocab_file': { 'facebook/xglm-564M': 'https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model', } } a_ : List[Any] = { 'facebook/xglm-564M': 20_48, } class _snake_case ( UpperCamelCase__ ): _lowercase : int = VOCAB_FILES_NAMES _lowercase : Tuple = PRETRAINED_VOCAB_FILES_MAP _lowercase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : Union[str, Any] = ['''input_ids''', '''attention_mask'''] def __init__( self , a , a="<s>" , a="</s>" , a="</s>" , a="<s>" , a="<unk>" , a="<pad>" , a = None , **a , ) -> Tuple: SCREAMING_SNAKE_CASE = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer SCREAMING_SNAKE_CASE = 7 SCREAMING_SNAKE_CASE = [f'''<madeupword{i}>''' for i in range(self.num_madeup_words)] SCREAMING_SNAKE_CASE = kwargs.get('additional_special_tokens' , []) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , unk_token=__lowerCamelCase , sep_token=__lowerCamelCase , cls_token=__lowerCamelCase , pad_token=__lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **__lowerCamelCase , ) SCREAMING_SNAKE_CASE = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(__lowerCamelCase)) SCREAMING_SNAKE_CASE = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE = 1 # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} SCREAMING_SNAKE_CASE = len(self.sp_model) SCREAMING_SNAKE_CASE = {f'''<madeupword{i}>''': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words)} self.fairseq_tokens_to_ids.update(__lowerCamelCase) SCREAMING_SNAKE_CASE = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.__dict__.copy() SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = self.sp_model.serialized_model_proto() return state def __setstate__( self , a) -> List[Any]: 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.LoadFromSerializedProto(self.sp_model_proto) def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> str: if token_ids_a is None: return [self.sep_token_id] + token_ids_a SCREAMING_SNAKE_CASE = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = False) -> List[str]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCamelCase , token_ids_a=__lowerCamelCase , already_has_special_tokens=__lowerCamelCase) if token_ids_a is None: return [1] + ([0] * len(__lowerCamelCase)) return [1] + ([0] * len(__lowerCamelCase)) + [1, 1] + ([0] * len(__lowerCamelCase)) def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> Optional[Any]: SCREAMING_SNAKE_CASE = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a) * [0] @property def SCREAMING_SNAKE_CASE__ ( self) -> str: return len(self.sp_model) + self.fairseq_offset + self.num_madeup_words def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = {self.convert_ids_to_tokens(__lowerCamelCase): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def SCREAMING_SNAKE_CASE__ ( self , a) -> List[Any]: return self.sp_model.encode(__lowerCamelCase , out_type=__lowerCamelCase) def SCREAMING_SNAKE_CASE__ ( self , a) -> int: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE = self.sp_model.PieceToId(__lowerCamelCase) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE__ ( self , a) -> Dict: 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 SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = ''.join(__lowerCamelCase).replace(__lowerCamelCase , ' ').strip() return out_string def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> Optional[int]: if not os.path.isdir(__lowerCamelCase): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''') return SCREAMING_SNAKE_CASE = os.path.join( __lowerCamelCase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(__lowerCamelCase) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , __lowerCamelCase) elif not os.path.isfile(self.vocab_file): with open(__lowerCamelCase , 'wb') as fi: SCREAMING_SNAKE_CASE = self.sp_model.serialized_model_proto() fi.write(__lowerCamelCase) return (out_vocab_file,)
367
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : Optional[Any] = { 'configuration_efficientnet': [ 'EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'EfficientNetConfig', 'EfficientNetOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[str] = ['EfficientNetImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = [ 'EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'EfficientNetForImageClassification', 'EfficientNetModel', 'EfficientNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure)
327
0
def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return 1 if input_a == input_a else 0 def lowerCamelCase__ (): assert xnor_gate(0 , 0) == 1 assert xnor_gate(0 , 1) == 0 assert xnor_gate(1 , 0) == 0 assert xnor_gate(1 , 1) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
368
import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) a_ : Dict = [ 'cross_validation.py', 'gradient_accumulation.py', 'local_sgd.py', 'multi_process_metrics.py', 'memory.py', 'automatic_gradient_accumulation.py', 'fsdp_with_peak_mem_tracking.py', 'deepspeed_with_config_support.py', 'megatron_lm_gpt_pretraining.py', ] class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , a = None) -> Optional[int]: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = os.path.abspath(os.path.join('examples' , 'by_feature')) SCREAMING_SNAKE_CASE = os.path.abspath('examples') for item in os.listdir(a): if item not in EXCLUDE_EXAMPLES: SCREAMING_SNAKE_CASE = os.path.join(a , a) if os.path.isfile(a) and ".py" in item_path: with self.subTest( tested_script=a , feature_script=a , tested_section='main()' if parser_only else 'training_function()' , ): SCREAMING_SNAKE_CASE = compare_against_test( os.path.join(a , a) , a , a , a) SCREAMING_SNAKE_CASE = '\n'.join(a) if special_strings is not None: for string in special_strings: SCREAMING_SNAKE_CASE = diff.replace(a , '') self.assertEqual(a , '') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: self.one_complete_example('complete_nlp_example.py' , a) self.one_complete_example('complete_nlp_example.py' , a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = os.path.abspath(os.path.join('examples' , 'cv_example.py')) SCREAMING_SNAKE_CASE = [ ' ' * 16 + '{\n\n', ' ' * 20 + '"accuracy": eval_metric["accuracy"],\n\n', ' ' * 20 + '"f1": eval_metric["f1"],\n\n', ' ' * 20 + '"train_loss": total_loss.item() / len(train_dataloader),\n\n', ' ' * 20 + '"epoch": epoch,\n\n', ' ' * 16 + '},\n\n', ' ' * 16 + 'step=epoch,\n', ' ' * 12, ' ' * 8 + 'for step, batch in enumerate(active_dataloader):\n', ] self.one_complete_example('complete_cv_example.py' , a , a , a) self.one_complete_example('complete_cv_example.py' , a , a , a) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class _snake_case ( A__ ): _lowercase : int = False @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Union[str, Any]: super().setUpClass() SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = os.path.join(cls._tmpdir , 'default_config.yml') write_basic_config(save_location=cls.configPath) SCREAMING_SNAKE_CASE = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Dict: super().tearDownClass() shutil.rmtree(cls._tmpdir) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'epoch_0'))) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'step_2'))) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0')} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) self.assertNotIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2')} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) if torch.cuda.is_available(): SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: SCREAMING_SNAKE_CASE = 1 if num_processes > 1: self.assertNotIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) else: self.assertIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = '\n examples/by_feature/cross_validation.py\n --num_folds 2\n '.split() with mock.patch.dict(os.environ , {'TESTING_MOCKED_DATALOADERS': '0'}): SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) SCREAMING_SNAKE_CASE = re.findall('({.+})' , a) SCREAMING_SNAKE_CASE = [r for r in results if 'accuracy' in r][-1] SCREAMING_SNAKE_CASE = ast.literal_eval(a) self.assertGreaterEqual(results['accuracy'] , 0.75) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ['examples/by_feature/multi_process_metrics.py'] run_command(self._launch_args + testargs) @require_trackers @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'}) def SCREAMING_SNAKE_CASE__ ( self) -> Any: with tempfile.TemporaryDirectory() as tmpdir: SCREAMING_SNAKE_CASE = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(a , 'tracking'))) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = ['examples/by_feature/gradient_accumulation.py'] run_command(self._launch_args + testargs) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = ['examples/by_feature/local_sgd.py'] run_command(self._launch_args + testargs)
327
0
import math import sys def lowerCamelCase__ (_UpperCAmelCase): if number != int(_snake_case): raise ValueError('the value of input must be a natural number') if number < 0: raise ValueError('the value of input must not be a negative number') if number == 0: return 1 SCREAMING_SNAKE_CASE = [-1] * (number + 1) SCREAMING_SNAKE_CASE = 0 for i in range(1 , number + 1): SCREAMING_SNAKE_CASE = sys.maxsize SCREAMING_SNAKE_CASE = int(math.sqrt(_snake_case)) for j in range(1 , root + 1): SCREAMING_SNAKE_CASE = 1 + answers[i - (j**2)] SCREAMING_SNAKE_CASE = min(_snake_case , _snake_case) SCREAMING_SNAKE_CASE = answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
369
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _snake_case : def __init__( self , a , a=3 , a=32 , a=3 , a=10 , a=[10, 20, 30, 40] , a=[1, 1, 2, 1] , a=True , a=True , a="relu" , a=3 , a=None , ) -> Union[str, Any]: 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 SCREAMING_SNAKE_CASE__ ( self) -> List[str]: 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 SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return ResNetConfig( 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 , image_size=self.image_size , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Any: SCREAMING_SNAKE_CASE = TFResNetModel(config=a) 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 SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> int: SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = TFResNetForImageClassification(a) SCREAMING_SNAKE_CASE = model(a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: 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_tf class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () _lowercase : Dict = ( {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification} if is_tf_available() else {} ) _lowercase : Union[str, Any] = False _lowercase : Any = False _lowercase : List[str] = False _lowercase : str = False _lowercase : int = False def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = TFResNetModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , has_text_modality=a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return @unittest.skip(reason='ResNet does not use inputs_embeds') def SCREAMING_SNAKE_CASE__ ( self) -> int: pass @unittest.skip(reason='ResNet does not support input and output embeddings') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: pass def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: 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.call) # 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 SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: def check_hidden_states_output(a , a , a): SCREAMING_SNAKE_CASE = model_class(a) 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) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 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 SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> str: for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = TFResNetModel.from_pretrained(a) self.assertIsNotNone(a) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') return image @require_tf @require_vision class _snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = image_processor(images=a , return_tensors='tf') # forward pass SCREAMING_SNAKE_CASE = model(**a) # verify the logits SCREAMING_SNAKE_CASE = tf.TensorShape((1, 1000)) self.assertEqual(outputs.logits.shape , a) SCREAMING_SNAKE_CASE = tf.constant([-11.10_69, -9.78_77, -8.37_77]) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , a , atol=1E-4))
327
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a_ : Tuple = { 'configuration_rembert': ['REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RemBertConfig', 'RemBertOnnxConfig'] } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Dict = ['RemBertTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Tuple = ['RemBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[str] = [ 'REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'RemBertForCausalLM', 'RemBertForMaskedLM', 'RemBertForMultipleChoice', 'RemBertForQuestionAnswering', 'RemBertForSequenceClassification', 'RemBertForTokenClassification', 'RemBertLayer', 'RemBertModel', 'RemBertPreTrainedModel', 'load_tf_weights_in_rembert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : int = [ 'TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFRemBertForCausalLM', 'TFRemBertForMaskedLM', 'TFRemBertForMultipleChoice', 'TFRemBertForQuestionAnswering', 'TFRemBertForSequenceClassification', 'TFRemBertForTokenClassification', 'TFRemBertLayer', 'TFRemBertModel', 'TFRemBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_rembert import REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RemBertConfig, RemBertOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_rembert import RemBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_rembert_fast import RemBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rembert import ( REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST, RemBertForCausalLM, RemBertForMaskedLM, RemBertForMultipleChoice, RemBertForQuestionAnswering, RemBertForSequenceClassification, RemBertForTokenClassification, RemBertLayer, RemBertModel, RemBertPreTrainedModel, load_tf_weights_in_rembert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rembert import ( TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFRemBertForCausalLM, TFRemBertForMaskedLM, TFRemBertForMultipleChoice, TFRemBertForQuestionAnswering, TFRemBertForSequenceClassification, TFRemBertForTokenClassification, TFRemBertLayer, TFRemBertModel, TFRemBertPreTrainedModel, ) else: import sys a_ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
370
from math import isqrt def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [True] * max_number for i in range(2 , isqrt(max_number - 1) + 1): if is_prime[i]: for j in range(i**2 , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = False return [i for i in range(2 , _UpperCAmelCase) if is_prime[i]] def lowerCamelCase__ (_UpperCAmelCase = 10**8): SCREAMING_SNAKE_CASE = calculate_prime_numbers(max_number // 2) SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(f"""{solution() = }""")
327
0
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar a_ : str = TypeVar('T') def lowerCamelCase__ (_UpperCAmelCase): return (position - 1) // 2 def lowerCamelCase__ (_UpperCAmelCase): return (2 * position) + 1 def lowerCamelCase__ (_UpperCAmelCase): return (2 * position) + 2 class _snake_case ( Generic[T] ): def __init__( self) -> int: SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = 0 def __len__( self) -> Union[str, Any]: return self.elements def __repr__( self) -> str: return str(self.heap) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: # Check if the priority queue is empty return self.elements == 0 def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Any: # Add an element with given priority to the queue self.heap.append((elem, weight)) SCREAMING_SNAKE_CASE = self.elements self.elements += 1 self._bubble_up(snake_case_) def SCREAMING_SNAKE_CASE__ ( self) -> str: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1) SCREAMING_SNAKE_CASE = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: SCREAMING_SNAKE_CASE = self.heap[0] self._bubble_down(snake_case_) return elem def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Optional[Any]: # Update the weight of the given key SCREAMING_SNAKE_CASE = self.position_map[elem] SCREAMING_SNAKE_CASE = (elem, weight) if position > 0: SCREAMING_SNAKE_CASE = get_parent_position(snake_case_) SCREAMING_SNAKE_CASE = self.heap[parent_position] if parent_weight > weight: self._bubble_up(snake_case_) else: self._bubble_down(snake_case_) else: self._bubble_down(snake_case_) def SCREAMING_SNAKE_CASE__ ( self , a) -> int: # Place a node at the proper position (upward movement) [to be used internally # only] SCREAMING_SNAKE_CASE = self.position_map[elem] if curr_pos == 0: return None SCREAMING_SNAKE_CASE = get_parent_position(snake_case_) SCREAMING_SNAKE_CASE = self.heap[curr_pos] SCREAMING_SNAKE_CASE = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(snake_case_ , snake_case_) return self._bubble_up(snake_case_) return None def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: # Place a node at the proper position (downward movement) [to be used # internally only] SCREAMING_SNAKE_CASE = self.position_map[elem] SCREAMING_SNAKE_CASE = self.heap[curr_pos] SCREAMING_SNAKE_CASE = get_child_left_position(snake_case_) SCREAMING_SNAKE_CASE = get_child_right_position(snake_case_) if child_left_position < self.elements and child_right_position < self.elements: SCREAMING_SNAKE_CASE = self.heap[child_left_position] SCREAMING_SNAKE_CASE = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(snake_case_ , snake_case_) return self._bubble_down(snake_case_) if child_left_position < self.elements: SCREAMING_SNAKE_CASE = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(snake_case_ , snake_case_) return self._bubble_down(snake_case_) else: return None if child_right_position < self.elements: SCREAMING_SNAKE_CASE = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(snake_case_ , snake_case_) return self._bubble_down(snake_case_) return None def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Any: # Swap the nodes at the given positions SCREAMING_SNAKE_CASE = self.heap[nodea_pos][0] SCREAMING_SNAKE_CASE = self.heap[nodea_pos][0] SCREAMING_SNAKE_CASE = ( self.heap[nodea_pos], self.heap[nodea_pos], ) SCREAMING_SNAKE_CASE = nodea_pos SCREAMING_SNAKE_CASE = nodea_pos class _snake_case ( Generic[T] ): def __init__( self) -> Dict: SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = 0 def __repr__( self) -> Union[str, Any]: return str(self.connections) def __len__( self) -> Union[str, Any]: return self.nodes def SCREAMING_SNAKE_CASE__ ( self , a) -> int: # Add a node in the graph if it is not in the graph if node not in self.connections: SCREAMING_SNAKE_CASE = {} self.nodes += 1 def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Optional[Any]: # Add an edge between 2 nodes in the graph self.add_node(snake_case_) self.add_node(snake_case_) SCREAMING_SNAKE_CASE = weight SCREAMING_SNAKE_CASE = weight def lowerCamelCase__ (_UpperCAmelCase , ): SCREAMING_SNAKE_CASE = {node: maxsize for node in graph.connections} SCREAMING_SNAKE_CASE = {node: None for node in graph.connections} SCREAMING_SNAKE_CASE = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(_lowerCAmelCase , _lowerCAmelCase) if priority_queue.is_empty(): return dist, parent # initialization SCREAMING_SNAKE_CASE = priority_queue.extract_min() SCREAMING_SNAKE_CASE = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: SCREAMING_SNAKE_CASE = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(_lowerCAmelCase , dist[neighbour]) SCREAMING_SNAKE_CASE = node # running prim's algorithm while not priority_queue.is_empty(): SCREAMING_SNAKE_CASE = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: SCREAMING_SNAKE_CASE = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(_lowerCAmelCase , dist[neighbour]) SCREAMING_SNAKE_CASE = node return dist, parent
371
import baseaa def lowerCamelCase__ (_UpperCAmelCase): return baseaa.aaaencode(string.encode('utf-8')) def lowerCamelCase__ (_UpperCAmelCase): return baseaa.aaadecode(_UpperCAmelCase).decode('utf-8') if __name__ == "__main__": import doctest doctest.testmod()
327
0
import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, PerceiverTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): a_ : Any = 'pt' elif is_tf_available(): a_ : List[str] = 'tf' else: a_ : int = 'jax' class _snake_case ( __lowerCamelCase , unittest.TestCase ): _lowercase : List[Any] = PerceiverTokenizer _lowercase : str = False def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: super().setUp() SCREAMING_SNAKE_CASE = PerceiverTokenizer() tokenizer.save_pretrained(self.tmpdirname) @cached_property def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: return PerceiverTokenizer.from_pretrained('deepmind/language-perceiver') def SCREAMING_SNAKE_CASE__ ( self , **a) -> Tuple: return self.tokenizer_class.from_pretrained(self.tmpdirname , **__lowercase) def SCREAMING_SNAKE_CASE__ ( self , a , a=False , a=20 , a=5) -> Dict: # XXX The default common tokenizer tests assume that every ID is decodable on its own. # This assumption is invalid for Perceiver because single bytes might not be # valid utf-8 (byte 128 for instance). # Here we're overriding the smallest possible method to provide # a clean sequence without making the same assumption. SCREAMING_SNAKE_CASE = [] for i in range(len(__lowercase)): try: SCREAMING_SNAKE_CASE = tokenizer.decode([i] , clean_up_tokenization_spaces=__lowercase) except UnicodeDecodeError: pass toks.append((i, tok)) SCREAMING_SNAKE_CASE = list(filter(lambda a: re.match(R'^[ a-zA-Z]+$' , t[1]) , __lowercase)) SCREAMING_SNAKE_CASE = list(filter(lambda a: [t[0]] == tokenizer.encode(t[1] , add_special_tokens=__lowercase) , __lowercase)) if max_length is not None and len(__lowercase) > max_length: SCREAMING_SNAKE_CASE = toks[:max_length] if min_length is not None and len(__lowercase) < min_length and len(__lowercase) > 0: while len(__lowercase) < 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(__lowercase , clean_up_tokenization_spaces=__lowercase) if " " not in output_txt and len(__lowercase) > 1: SCREAMING_SNAKE_CASE = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=__lowercase) + ''' ''' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=__lowercase) ) if with_prefix_space: SCREAMING_SNAKE_CASE = ''' ''' + output_txt SCREAMING_SNAKE_CASE = tokenizer.encode(__lowercase , add_special_tokens=__lowercase) return output_txt, output_ids def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.perceiver_tokenizer SCREAMING_SNAKE_CASE = '''Unicode €.''' SCREAMING_SNAKE_CASE = tokenizer(__lowercase) SCREAMING_SNAKE_CASE = [4, 91, 116, 111, 105, 117, 106, 107, 38, 232, 136, 178, 52, 5] self.assertEqual(encoded['input_ids'] , __lowercase) # decoding SCREAMING_SNAKE_CASE = tokenizer.decode(__lowercase) self.assertEqual(__lowercase , '[CLS]Unicode €.[SEP]') SCREAMING_SNAKE_CASE = tokenizer('e è é ê ë') SCREAMING_SNAKE_CASE = [4, 107, 38, 201, 174, 38, 201, 175, 38, 201, 176, 38, 201, 177, 5] self.assertEqual(encoded['input_ids'] , __lowercase) # decoding SCREAMING_SNAKE_CASE = tokenizer.decode(__lowercase) self.assertEqual(__lowercase , '[CLS]e è é ê ë[SEP]') # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('e è é ê ë')) , '[CLS]e è é ê ë[SEP]') def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = self.perceiver_tokenizer SCREAMING_SNAKE_CASE = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] # fmt: off SCREAMING_SNAKE_CASE = [4, 71, 38, 114, 117, 116, 109, 38, 118, 103, 120, 103, 109, 120, 103, 118, 110, 38, 108, 117, 120, 38, 121, 123, 115, 115, 103, 120, 111, 128, 103, 122, 111, 117, 116, 52, 5, 0] # fmt: on SCREAMING_SNAKE_CASE = tokenizer(__lowercase , padding=__lowercase , return_tensors=__lowercase) self.assertIsInstance(__lowercase , __lowercase) if FRAMEWORK != "jax": SCREAMING_SNAKE_CASE = list(batch.input_ids.numpy()[0]) else: SCREAMING_SNAKE_CASE = list(batch.input_ids.tolist()[0]) self.assertListEqual(__lowercase , __lowercase) self.assertEqual((2, 38) , batch.input_ids.shape) self.assertEqual((2, 38) , batch.attention_mask.shape) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.perceiver_tokenizer SCREAMING_SNAKE_CASE = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] SCREAMING_SNAKE_CASE = tokenizer(__lowercase , padding=__lowercase , return_tensors=__lowercase) # check if input_ids are returned and no decoder_input_ids self.assertIn('input_ids' , __lowercase) self.assertIn('attention_mask' , __lowercase) self.assertNotIn('decoder_input_ids' , __lowercase) self.assertNotIn('decoder_attention_mask' , __lowercase) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.perceiver_tokenizer SCREAMING_SNAKE_CASE = [ '''Summary of the text.''', '''Another summary.''', ] SCREAMING_SNAKE_CASE = tokenizer( text_target=__lowercase , max_length=32 , padding='max_length' , truncation=__lowercase , return_tensors=__lowercase) self.assertEqual(32 , targets['input_ids'].shape[1]) def SCREAMING_SNAKE_CASE__ ( self) -> int: # safety check on max_len default value so we are sure the test works 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(__lowercase , add_special_tokens=__lowercase) tokenizer.save_pretrained(__lowercase) SCREAMING_SNAKE_CASE = tokenizer.__class__.from_pretrained(__lowercase) SCREAMING_SNAKE_CASE = after_tokenizer.encode(__lowercase , add_special_tokens=__lowercase) self.assertListEqual(__lowercase , __lowercase) shutil.rmtree(__lowercase) 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(__lowercase , add_special_tokens=__lowercase) tokenizer.save_pretrained(__lowercase) SCREAMING_SNAKE_CASE = tokenizer.__class__.from_pretrained(__lowercase) SCREAMING_SNAKE_CASE = after_tokenizer.encode(__lowercase , add_special_tokens=__lowercase) self.assertListEqual(__lowercase , __lowercase) 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(__lowercase , model_max_length=43) self.assertEqual(tokenizer.model_max_length , 43) shutil.rmtree(__lowercase) def SCREAMING_SNAKE_CASE__ ( self) -> str: 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(__lowercase) with open(os.path.join(__lowercase , 'special_tokens_map.json') , encoding='utf-8') as json_file: SCREAMING_SNAKE_CASE = json.load(__lowercase) with open(os.path.join(__lowercase , 'tokenizer_config.json') , encoding='utf-8') as json_file: SCREAMING_SNAKE_CASE = json.load(__lowercase) 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(__lowercase , 'special_tokens_map.json') , 'w' , encoding='utf-8') as outfile: json.dump(__lowercase , __lowercase) with open(os.path.join(__lowercase , 'tokenizer_config.json') , 'w' , encoding='utf-8') as outfile: json.dump(__lowercase , __lowercase) # 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( __lowercase , ) self.assertIn( 'an_additional_special_token' , tokenizer_without_change_in_init.additional_special_tokens) 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=__lowercase)] SCREAMING_SNAKE_CASE = tokenizer_class.from_pretrained( __lowercase , additional_special_tokens=__lowercase , ) 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 SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = self.perceiver_tokenizer self.assertEqual(tokenizer.decode([178]) , '�') def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: pass def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: pass def SCREAMING_SNAKE_CASE__ ( self) -> int: pass def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: pass def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: # The default common tokenizer tests uses invalid tokens for Perceiver that can only accept one-character # strings and special added tokens as tokens SCREAMING_SNAKE_CASE = self.get_tokenizers(fast=__lowercase , do_lower_case=__lowercase) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}'''): SCREAMING_SNAKE_CASE = ['''[CLS]''', '''t''', '''h''', '''i''', '''s''', ''' ''', '''i''', '''s''', ''' ''', '''a''', ''' ''', '''t''', '''e''', '''s''', '''t''', '''[SEP]'''] SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_string(__lowercase) self.assertIsInstance(__lowercase , __lowercase)
350
import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(_UpperCAmelCase , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = emb.weight.shape SCREAMING_SNAKE_CASE = nn.Linear(_UpperCAmelCase , _UpperCAmelCase , bias=_UpperCAmelCase) SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = mam_aaa['args'] or mam_aaa['cfg']['model'] SCREAMING_SNAKE_CASE = mam_aaa['model'] remove_ignore_keys_(_UpperCAmelCase) SCREAMING_SNAKE_CASE = state_dict['encoder.embed_tokens.weight'].shape[0] SCREAMING_SNAKE_CASE = MaMaaaConfig( vocab_size=_UpperCAmelCase , max_position_embeddings=1024 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='relu' , ) SCREAMING_SNAKE_CASE = state_dict['decoder.embed_tokens.weight'] SCREAMING_SNAKE_CASE = MaMaaaForConditionalGeneration(_UpperCAmelCase) model.model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase) SCREAMING_SNAKE_CASE = make_linear_from_emb(model.model.shared) return model if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') a_ : List[str] = parser.parse_args() a_ : Dict = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
327
0
import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging a_ : Union[str, Any] = logging.get_logger(__name__) class _snake_case ( __UpperCamelCase ): def __init__( self , a) -> Optional[int]: super().__init__() SCREAMING_SNAKE_CASE = nn.ModuleList(a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a = None , a = None , a = None , a = None , a = False , a = True , ) -> Union[ControlNetOutput, Tuple]: for i, (image, scale, controlnet) in enumerate(zip(a , a , self.nets)): SCREAMING_SNAKE_CASE = controlnet( a , a , a , a , a , a , a , a , a , a , a , ) # merge samples if i == 0: SCREAMING_SNAKE_CASE = down_samples, mid_sample else: SCREAMING_SNAKE_CASE = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(a , a) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def SCREAMING_SNAKE_CASE__ ( self , a , a = True , a = None , a = False , a = None , ) -> List[str]: SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = save_directory for controlnet in self.nets: controlnet.save_pretrained( a , is_main_process=a , save_function=a , safe_serialization=a , variant=a , ) idx += 1 SCREAMING_SNAKE_CASE = model_path_to_save + f'''_{idx}''' @classmethod def SCREAMING_SNAKE_CASE__ ( cls , a , **a) -> Optional[Any]: SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = [] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... SCREAMING_SNAKE_CASE = pretrained_model_path while os.path.isdir(a): SCREAMING_SNAKE_CASE = ControlNetModel.from_pretrained(a , **a) controlnets.append(a) idx += 1 SCREAMING_SNAKE_CASE = pretrained_model_path + f'''_{idx}''' logger.info(f'''{len(a)} controlnets loaded from {pretrained_model_path}.''') if len(a) == 0: raise ValueError( f'''No ControlNets found under {os.path.dirname(a)}. Expected at least {pretrained_model_path + '_0'}.''') return cls(a)
351
import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = 'laion/clap-htsat-unfused' SCREAMING_SNAKE_CASE = tempfile.mkdtemp() def SCREAMING_SNAKE_CASE__ ( self , **a) -> Optional[Any]: return RobertaTokenizer.from_pretrained(self.checkpoint , **a) def SCREAMING_SNAKE_CASE__ ( self , **a) -> Union[str, Any]: return ClapFeatureExtractor.from_pretrained(self.checkpoint , **a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = ClapProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) self.assertIsInstance(processor.tokenizer , a) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor()) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)') SCREAMING_SNAKE_CASE = self.get_feature_extractor(do_normalize=a , padding_value=1.0) SCREAMING_SNAKE_CASE = ClapProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=a , padding_value=1.0) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) self.assertIsInstance(processor.tokenizer , a) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = floats_list((3, 1000)) SCREAMING_SNAKE_CASE = feature_extractor(a , return_tensors='np') SCREAMING_SNAKE_CASE = processor(audios=a , return_tensors='np') for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = 'This is a test string' SCREAMING_SNAKE_CASE = processor(text=a) SCREAMING_SNAKE_CASE = tokenizer(a) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE = processor.batch_decode(a) SCREAMING_SNAKE_CASE = tokenizer.batch_decode(a) self.assertListEqual(a , a) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , )
327
0
def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [False] * len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = [-1] * len(_UpperCAmelCase) def dfs(_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = c for u in graph[v]: if not visited[u]: dfs(_UpperCAmelCase , 1 - c) for i in range(len(_UpperCAmelCase)): if not visited[i]: dfs(_UpperCAmelCase , 0) for i in range(len(_UpperCAmelCase)): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph a_ : str = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
352
import argparse import datetime def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = { '0': 'Sunday', '1': 'Monday', '2': 'Tuesday', '3': 'Wednesday', '4': 'Thursday', '5': 'Friday', '6': 'Saturday', } SCREAMING_SNAKE_CASE = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(_UpperCAmelCase) < 11: raise ValueError('Must be 10 characters long') # Get month SCREAMING_SNAKE_CASE = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 13: raise ValueError('Month must be between 1 - 12') SCREAMING_SNAKE_CASE = date_input[2] # Validate if sep_a not in ["-", "/"]: raise ValueError('Date separator must be \'-\' or \'/\'') # Get day SCREAMING_SNAKE_CASE = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 32: raise ValueError('Date must be between 1 - 31') # Get second separator SCREAMING_SNAKE_CASE = date_input[5] # Validate if sep_a not in ["-", "/"]: raise ValueError('Date separator must be \'-\' or \'/\'') # Get year SCREAMING_SNAKE_CASE = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 45 < y < 8500: raise ValueError( 'Year out of range. There has to be some sort of limit...right?') # Get datetime obj for validation SCREAMING_SNAKE_CASE = datetime.date(int(_UpperCAmelCase) , int(_UpperCAmelCase) , int(_UpperCAmelCase)) # Start math if m <= 2: SCREAMING_SNAKE_CASE = y - 1 SCREAMING_SNAKE_CASE = m + 12 # maths var SCREAMING_SNAKE_CASE = int(str(_UpperCAmelCase)[:2]) SCREAMING_SNAKE_CASE = int(str(_UpperCAmelCase)[2:]) SCREAMING_SNAKE_CASE = int(2.6 * m - 5.39) SCREAMING_SNAKE_CASE = int(c / 4) SCREAMING_SNAKE_CASE = int(k / 4) SCREAMING_SNAKE_CASE = int(d + k) SCREAMING_SNAKE_CASE = int(t + u + v + x) SCREAMING_SNAKE_CASE = int(z - (2 * c)) SCREAMING_SNAKE_CASE = round(w % 7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError('The date was evaluated incorrectly. Contact developer.') # Response SCREAMING_SNAKE_CASE = F'''Your date {date_input}, is a {days[str(_UpperCAmelCase)]}!''' return response if __name__ == "__main__": import doctest doctest.testmod() a_ : Tuple = argparse.ArgumentParser( description=( 'Find out what day of the week nearly any date is or was. Enter ' 'date as a string in the mm-dd-yyyy or mm/dd/yyyy format' ) ) parser.add_argument( 'date_input', type=str, help='Date as a string (mm-dd-yyyy or mm/dd/yyyy)' ) a_ : Any = parser.parse_args() zeller(args.date_input)
327
0
"""simple docstring""" import json import logging import os import sys from pathlib import Path import finetune_rag from transformers.file_utils import is_apex_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, require_ray, require_torch_gpu, require_torch_multi_gpu, ) logging.basicConfig(level=logging.DEBUG) a_ : str = logging.getLogger() a_ : str = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class _snake_case ( snake_case_ ): def SCREAMING_SNAKE_CASE__ ( self , a) -> Union[str, Any]: os.makedirs(a , exist_ok=a) SCREAMING_SNAKE_CASE = {'source': 'What is love ?', 'target': 'life'} SCREAMING_SNAKE_CASE = {'train': 12, 'val': 2, 'test': 2} for split in ["train", "test", "val"]: for field in ["source", "target"]: SCREAMING_SNAKE_CASE = '\n'.join([contents[field]] * n_lines[split]) with open(os.path.join(a , f'''{split}.{field}''') , 'w') as f: f.write(a) def SCREAMING_SNAKE_CASE__ ( self , a , a = "pytorch") -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE = os.path.join(a , 'output') SCREAMING_SNAKE_CASE = os.path.join(a , 'data') self._create_dummy_data(data_dir=a) SCREAMING_SNAKE_CASE = f'''\n --data_dir {data_dir} \\n --output_dir {output_dir} \\n --model_name_or_path facebook/rag-sequence-base \\n --model_type rag_sequence \\n --do_train \\n --do_predict \\n --n_val -1 \\n --val_check_interval 1.0 \\n --train_batch_size 2 \\n --eval_batch_size 1 \\n --max_source_length 25 \\n --max_target_length 25 \\n --val_max_target_length 25 \\n --test_max_target_length 25 \\n --label_smoothing 0.1 \\n --dropout 0.1 \\n --attention_dropout 0.1 \\n --weight_decay 0.001 \\n --adam_epsilon 1e-08 \\n --max_grad_norm 0.1 \\n --lr_scheduler polynomial \\n --learning_rate 3e-04 \\n --num_train_epochs 1 \\n --warmup_steps 4 \\n --gradient_accumulation_steps 1 \\n --distributed-port 8787 \\n --use_dummy_dataset 1 \\n --distributed_retriever {distributed_retriever} \\n '''.split() if gpus > 0: testargs.append(f'''--gpus={gpus}''') if is_apex_available(): testargs.append('--fp16') else: testargs.append('--gpus=0') testargs.append('--distributed_backend=ddp_cpu') testargs.append('--num_processes=2') SCREAMING_SNAKE_CASE = [sys.executable, str(Path(finetune_rag.__file__).resolve())] + testargs execute_subprocess_async(a , env=self.get_env()) SCREAMING_SNAKE_CASE = os.path.join(a , 'metrics.json') with open(a) as f: SCREAMING_SNAKE_CASE = json.load(a) return result @require_torch_gpu def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self._run_finetune(gpus=1) self.assertGreaterEqual(result['test'][0]['test_avg_em'] , 0.2) @require_torch_multi_gpu def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self._run_finetune(gpus=2) self.assertGreaterEqual(result['test'][0]['test_avg_em'] , 0.2) @require_torch_gpu @require_ray def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self._run_finetune(gpus=1 , distributed_retriever='ray') self.assertGreaterEqual(result['test'][0]['test_avg_em'] , 0.2) @require_torch_multi_gpu @require_ray def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self._run_finetune(gpus=1 , distributed_retriever='ray') self.assertGreaterEqual(result['test'][0]['test_avg_em'] , 0.2)
353
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 convert_to_rgb, 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 if is_vision_available(): import PIL a_ : Optional[Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : Optional[int] = ['''pixel_values'''] def __init__( self , a = True , a = None , a = PILImageResampling.BICUBIC , a = True , a = 1 / 255 , a = True , a = None , a = None , a = True , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = size if size is not None else {'height': 384, 'width': 384} SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) SCREAMING_SNAKE_CASE = do_resize SCREAMING_SNAKE_CASE = size SCREAMING_SNAKE_CASE = resample 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 SCREAMING_SNAKE_CASE__ ( self , a , a , a = PILImageResampling.BICUBIC , a = None , **a , ) -> np.ndarray: SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}''') SCREAMING_SNAKE_CASE = (size['height'], size['width']) return resize(a , size=a , resample=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a , ) -> Optional[Any]: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a = None , **a , ) -> np.ndarray: return normalize(a , mean=a , std=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> PIL.Image.Image: SCREAMING_SNAKE_CASE = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE = resample if resample is not None else self.resample 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 = size if size is not None else self.size SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) 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 or resample is None: raise ValueError('Size and resample must be specified if do_resize 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_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 = BatchFeature(data={'pixel_values': images} , tensor_type=a) return encoded_outputs
327
0
from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers a_ : Tuple = [ 'python', 'tqdm', 'regex', 'requests', 'packaging', 'filelock', 'numpy', 'tokenizers', 'huggingface-hub', 'safetensors', 'accelerate', 'pyyaml', ] for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed elif pkg == "accelerate": # must be loaded here, or else tqdm check may fail from .utils import is_accelerate_available # Maybe switch to is_torch_available in the future here so that Accelerate is hard dep of # Transformers with PyTorch if not is_accelerate_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(f"""can't find {pkg} in {deps.keys()}, check dependency_versions_table.py""") def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=None): require_version(deps[pkg] , _lowerCAmelCase)
354
class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = val SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None def SCREAMING_SNAKE_CASE__ ( self , a) -> str: if self.val: if val < self.val: if self.left is None: SCREAMING_SNAKE_CASE = Node(a) else: self.left.insert(a) elif val > self.val: if self.right is None: SCREAMING_SNAKE_CASE = Node(a) else: self.right.insert(a) else: SCREAMING_SNAKE_CASE = val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Recursive traversal if root: inorder(root.left , _UpperCAmelCase) res.append(root.val) inorder(root.right , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): # Build BST if len(_UpperCAmelCase) == 0: return arr SCREAMING_SNAKE_CASE = Node(arr[0]) for i in range(1 , len(_UpperCAmelCase)): root.insert(arr[i]) # Traverse BST in order. SCREAMING_SNAKE_CASE = [] inorder(_UpperCAmelCase , _UpperCAmelCase) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
327
0
from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, FEATURE_EXTRACTOR_NAME, FLAX_WEIGHTS_NAME, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, MODEL_CARD_NAME, MULTIPLE_CHOICE_DUMMY_INPUTS, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, SENTENCEPIECE_UNDERLINE, SPIECE_UNDERLINE, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME, TORCH_FX_REQUIRED_VERSION, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, USE_JAX, USE_TF, USE_TORCH, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ContextManagers, DummyObject, EntryNotFoundError, ExplicitEnum, ModelOutput, PaddingStrategy, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, TensorType, _LazyModule, add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, cached_property, copy_func, default_cache_path, define_sagemaker_information, get_cached_models, get_file_from_repo, get_full_repo_name, get_torch_version, has_file, http_user_agent, is_apex_available, is_bsa_available, is_coloredlogs_available, is_datasets_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_librosa_available, is_offline_mode, is_onnx_available, is_pandas_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytorch_quantization_available, is_rjieba_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_tensor, is_tensorflow_probability_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_training_run_on_sagemaker, is_vision_available, replace_return_docstrings, requires_backends, to_numpy, to_py_obj, torch_only_method, )
355
import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint a_ : Optional[int] = { '169M': 12, '430M': 24, '1B5': 24, '3B': 32, '7B': 32, '14B': 40, } a_ : Optional[int] = { '169M': 7_68, '430M': 10_24, '1B5': 20_48, '3B': 25_60, '7B': 40_96, '14B': 51_20, } def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = list(state_dict.keys()) for name in state_dict_keys: SCREAMING_SNAKE_CASE = state_dict.pop(_UpperCAmelCase) # emb -> embedding if name.startswith('emb.'): SCREAMING_SNAKE_CASE = name.replace('emb.' , 'embeddings.') # ln_0 -> pre_ln (only present at block 0) if name.startswith('blocks.0.ln0'): SCREAMING_SNAKE_CASE = name.replace('blocks.0.ln0' , 'blocks.0.pre_ln') # att -> attention SCREAMING_SNAKE_CASE = re.sub(R'blocks\.(\d+)\.att' , R'blocks.\1.attention' , _UpperCAmelCase) # ffn -> feed_forward SCREAMING_SNAKE_CASE = re.sub(R'blocks\.(\d+)\.ffn' , R'blocks.\1.feed_forward' , _UpperCAmelCase) # time_mix_k -> time_mix_key and reshape if name.endswith('.time_mix_k'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_k' , '.time_mix_key') # time_mix_v -> time_mix_value and reshape if name.endswith('.time_mix_v'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_v' , '.time_mix_value') # time_mix_r -> time_mix_key and reshape if name.endswith('.time_mix_r'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_r' , '.time_mix_receptance') if name != "head.weight": SCREAMING_SNAKE_CASE = 'rwkv.' + name SCREAMING_SNAKE_CASE = weight return state_dict def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=False , _UpperCAmelCase=None): # 1. If possible, build the tokenizer. if tokenizer_file is None: print('No `--tokenizer_file` provided, we will use the default tokenizer.') SCREAMING_SNAKE_CASE = 5_0277 SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('EleutherAI/gpt-neox-20b') else: SCREAMING_SNAKE_CASE = PreTrainedTokenizerFast(tokenizer_file=_UpperCAmelCase) SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) tokenizer.save_pretrained(_UpperCAmelCase) # 2. Build the config SCREAMING_SNAKE_CASE = list(NUM_HIDDEN_LAYERS_MAPPING.keys()) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: SCREAMING_SNAKE_CASE = candidate break if size is None: raise ValueError('Could not infer the size, please provide it with the `--size` argument.') if size not in possible_sizes: raise ValueError(F'''`size` should be one of {possible_sizes}, got {size}.''') SCREAMING_SNAKE_CASE = RwkvConfig( vocab_size=_UpperCAmelCase , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(_UpperCAmelCase) # 3. Download model file then convert state_dict SCREAMING_SNAKE_CASE = hf_hub_download(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = convert_state_dict(_UpperCAmelCase) # 4. Split in shards and save SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = shard_checkpoint(_UpperCAmelCase) for shard_file, shard in shards.items(): torch.save(_UpperCAmelCase , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) if index is not None: SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , _UpperCAmelCase) # Save the index as well with open(_UpperCAmelCase , 'w' , encoding='utf-8') as f: SCREAMING_SNAKE_CASE = json.dumps(_UpperCAmelCase , indent=2 , sort_keys=_UpperCAmelCase) + '\n' f.write(_UpperCAmelCase) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( 'Cleaning up shards. This may error with an OOM error, it this is the case don\'t worry you still have converted the model.') SCREAMING_SNAKE_CASE = list(shards.keys()) del state_dict del shards gc.collect() for shard_file in shard_files: SCREAMING_SNAKE_CASE = torch.load(os.path.join(_UpperCAmelCase , _UpperCAmelCase)) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError('Please provide a `model_name` to push the model to the Hub.') SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(_UpperCAmelCase) model.push_to_hub(_UpperCAmelCase , max_shard_size='2GB') tokenizer.push_to_hub(_UpperCAmelCase) if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--repo_id', default=None, type=str, required=True, help='Repo ID from which to pull the checkpoint.' ) parser.add_argument( '--checkpoint_file', default=None, type=str, required=True, help='Name of the checkpoint file in the repo.' ) parser.add_argument( '--output_dir', default=None, type=str, required=True, help='Where to save the converted model.' ) parser.add_argument( '--tokenizer_file', default=None, type=str, help='Path to the tokenizer file to use (if not provided, only the model is converted).', ) parser.add_argument( '--size', default=None, type=str, help='Size of the model. Will be inferred from the `checkpoint_file` if not passed.', ) parser.add_argument( '--push_to_hub', action='store_true', help='Push to the Hub the converted model.', ) parser.add_argument( '--model_name', default=None, type=str, help='Name of the pushed model on the Hub, including the username / organization.', ) a_ : Tuple = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
327
0
def lowerCamelCase__ (_UpperCAmelCase = 100_0000): SCREAMING_SNAKE_CASE = limit + 1 SCREAMING_SNAKE_CASE = [0] * limit for first_term in range(1 , _UpperCAmelCase): for n in range(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = first_term + n / first_term if common_difference % 4: # d must be divisble by 4 continue else: common_difference /= 4 if ( first_term > common_difference and first_term < 4 * common_difference ): # since x,y,z are positive integers frequency[n] += 1 # so z>0 and a>d ,also 4d<a SCREAMING_SNAKE_CASE = sum(1 for x in frequency[1:limit] if x == 10) return count if __name__ == "__main__": print(f"""{solution() = }""")
356
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def lowerCamelCase__ (_UpperCAmelCase): monkeypatch.setattr('datasets.utils.deprecation_utils._emitted_deprecation_warnings' , set()) @pytest.fixture def lowerCamelCase__ (_UpperCAmelCase): class _snake_case : def __init__( self , a) -> List[Any]: SCREAMING_SNAKE_CASE = metric_id class _snake_case : _lowercase : Optional[Any] = [MetricMock(A__ ) for metric_id in ['''accuracy''', '''mse''', '''precision''', '''codeparrot/apps_metric''']] def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: return self._metrics monkeypatch.setattr('datasets.inspect.huggingface_hub' , HfhMock()) @pytest.mark.parametrize( 'func, args' , [(load_metric, ('metrics/mse',)), (list_metrics, ()), (inspect_metric, ('metrics/mse', 'tmp_path'))]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if "tmp_path" in args: SCREAMING_SNAKE_CASE = tuple(arg if arg != 'tmp_path' else tmp_path for arg in args) with pytest.warns(_UpperCAmelCase , match='https://huggingface.co/docs/evaluate'): func(*_UpperCAmelCase)
327
0
"""simple docstring""" from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar a_ : int = TypeVar('T') class _snake_case ( Generic[T] ): _lowercase : deque[T] # Cache store of keys _lowercase : set[T] # References of the keys in cache _lowercase : int = 10 # Maximum capacity of cache def __init__( self , a) -> None: SCREAMING_SNAKE_CASE = deque() SCREAMING_SNAKE_CASE = set() if not n: SCREAMING_SNAKE_CASE = sys.maxsize elif n < 0: raise ValueError('n should be an integer greater than 0.') else: SCREAMING_SNAKE_CASE = n def SCREAMING_SNAKE_CASE__ ( self , a) -> None: if x not in self.key_reference: if len(self.dq_store) == LRUCache._MAX_CAPACITY: SCREAMING_SNAKE_CASE = self.dq_store.pop() self.key_reference.remove(lowerCamelCase__) else: self.dq_store.remove(lowerCamelCase__) self.dq_store.appendleft(lowerCamelCase__) self.key_reference.add(lowerCamelCase__) def SCREAMING_SNAKE_CASE__ ( self) -> None: for k in self.dq_store: print(lowerCamelCase__) def __repr__( self) -> str: return f'''LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store)}''' if __name__ == "__main__": import doctest doctest.testmod() a_ : LRUCache[str | int] = LRUCache(4) lru_cache.refer('A') lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer('A') lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
357
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : Any = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Dict = ['MLukeTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys a_ : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
327
0
from __future__ import annotations import unittest from transformers import FunnelConfig, is_tf_available from transformers.testing_utils import require_tf 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 ( TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, ) class _snake_case : def __init__( self , a , a=13 , a=7 , a=True , a=True , a=True , a=True , a=99 , a=[1, 1, 2] , a=1 , a=32 , a=4 , a=8 , a=37 , a="gelu_new" , a=0.1 , a=0.1 , a=0.0 , a=512 , a=3 , a=0.02 , a=3 , a=4 , a=None , a=False , ) -> int: 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 = block_sizes SCREAMING_SNAKE_CASE = num_decoder_layers SCREAMING_SNAKE_CASE = d_model SCREAMING_SNAKE_CASE = n_head SCREAMING_SNAKE_CASE = d_head SCREAMING_SNAKE_CASE = d_inner SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = activation_dropout SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = num_choices SCREAMING_SNAKE_CASE = scope SCREAMING_SNAKE_CASE = initializer_std # Used in the tests to check the size of the first attention layer SCREAMING_SNAKE_CASE = n_head # Used in the tests to check the size of the first hidden state SCREAMING_SNAKE_CASE = self.d_model # Used in the tests to check the number of output hidden states/attentions SCREAMING_SNAKE_CASE = sum(self.block_sizes) + (0 if base else self.num_decoder_layers) # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with # the last hidden state of the first block (which is the first hidden state of the decoder). if not base: SCREAMING_SNAKE_CASE = self.num_hidden_layers + 2 def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: 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 = FunnelConfig( vocab_size=self.vocab_size , block_sizes=self.block_sizes , num_decoder_layers=self.num_decoder_layers , d_model=self.d_model , n_head=self.n_head , d_head=self.d_head , d_inner=self.d_inner , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , activation_dropout=self.activation_dropout , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_std=self.initializer_std , ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE = TFFunnelModel(config=lowercase__) SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} SCREAMING_SNAKE_CASE = model(lowercase__) SCREAMING_SNAKE_CASE = [input_ids, input_mask] SCREAMING_SNAKE_CASE = model(lowercase__) SCREAMING_SNAKE_CASE = model(lowercase__) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model)) SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = TFFunnelModel(config=lowercase__) SCREAMING_SNAKE_CASE = model(lowercase__) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model)) SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = TFFunnelModel(config=lowercase__) SCREAMING_SNAKE_CASE = model(lowercase__) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , ) -> Optional[Any]: SCREAMING_SNAKE_CASE = TFFunnelBaseModel(config=lowercase__) SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} SCREAMING_SNAKE_CASE = model(lowercase__) SCREAMING_SNAKE_CASE = [input_ids, input_mask] SCREAMING_SNAKE_CASE = model(lowercase__) SCREAMING_SNAKE_CASE = model(lowercase__) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model)) SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = TFFunnelBaseModel(config=lowercase__) SCREAMING_SNAKE_CASE = model(lowercase__) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 3, self.d_model)) SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = TFFunnelBaseModel(config=lowercase__) SCREAMING_SNAKE_CASE = model(lowercase__) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , ) -> str: SCREAMING_SNAKE_CASE = TFFunnelForPreTraining(config=lowercase__) SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} SCREAMING_SNAKE_CASE = model(lowercase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , ) -> List[str]: SCREAMING_SNAKE_CASE = TFFunnelForMaskedLM(config=lowercase__) SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} SCREAMING_SNAKE_CASE = model(lowercase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = TFFunnelForSequenceClassification(config=lowercase__) SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} SCREAMING_SNAKE_CASE = model(lowercase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , ) -> int: SCREAMING_SNAKE_CASE = self.num_choices SCREAMING_SNAKE_CASE = TFFunnelForMultipleChoice(config=lowercase__) SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(lowercase__ , 1) , (1, self.num_choices, 1)) SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(lowercase__ , 1) , (1, self.num_choices, 1)) SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(lowercase__ , 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(lowercase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , ) -> Any: SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = TFFunnelForTokenClassification(config=lowercase__) SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} SCREAMING_SNAKE_CASE = model(lowercase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , ) -> List[Any]: SCREAMING_SNAKE_CASE = TFFunnelForQuestionAnswering(config=lowercase__) SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} SCREAMING_SNAKE_CASE = model(lowercase__) 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 SCREAMING_SNAKE_CASE__ ( self) -> Tuple: 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 _snake_case ( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): _lowercase : Tuple = ( ( TFFunnelModel, TFFunnelForMaskedLM, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForTokenClassification, ) if is_tf_available() else () ) _lowercase : int = ( { 'feature-extraction': (TFFunnelBaseModel, TFFunnelModel), 'fill-mask': TFFunnelForMaskedLM, 'question-answering': TFFunnelForQuestionAnswering, 'text-classification': TFFunnelForSequenceClassification, 'token-classification': TFFunnelForTokenClassification, 'zero-shot': TFFunnelForSequenceClassification, } if is_tf_available() else {} ) _lowercase : Optional[Any] = False _lowercase : List[str] = False def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = TFFunnelModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=lowercase__) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase__) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*lowercase__) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowercase__) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase__) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase__) @require_tf class _snake_case ( lowerCamelCase__ , unittest.TestCase ): _lowercase : Any = ( (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else () ) _lowercase : Optional[int] = False _lowercase : Tuple = False def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = TFFunnelModelTester(self , base=lowercase__) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=lowercase__) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_base_model(*lowercase__) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowercase__) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*lowercase__)
358
from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer a_ : List[Any] = logging.get_logger(__name__) a_ : Union[str, Any] = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} a_ : str = { 'vocab_file': { 'allegro/herbert-base-cased': 'https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json' }, 'merges_file': { 'allegro/herbert-base-cased': 'https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt' }, } a_ : List[Any] = {'allegro/herbert-base-cased': 5_14} a_ : Dict = {} class _snake_case ( A__ ): _lowercase : Dict = VOCAB_FILES_NAMES _lowercase : int = PRETRAINED_VOCAB_FILES_MAP _lowercase : Any = PRETRAINED_INIT_CONFIGURATION _lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : Any = HerbertTokenizer def __init__( self , a=None , a=None , a=None , a="<s>" , a="<unk>" , a="<pad>" , a="<mask>" , a="</s>" , **a , ) -> Dict: super().__init__( a , a , tokenizer_file=a , cls_token=a , unk_token=a , pad_token=a , mask_token=a , sep_token=a , **a , ) def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: SCREAMING_SNAKE_CASE = [self.cls_token_id] SCREAMING_SNAKE_CASE = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = False) -> List[int]: 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] + ([0] * len(a)) + [1] def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: 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 SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> Tuple[str]: SCREAMING_SNAKE_CASE = self._tokenizer.model.save(a , name=a) return tuple(a)
327
0
import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class _snake_case ( SCREAMING_SNAKE_CASE__ ): _lowercase : List[Any] = '''naver-clova-ix/donut-base-finetuned-docvqa''' _lowercase : int = ( '''This is a tool that answers a question about an document (pdf). It takes an input named `document` which ''' '''should be the document containing the information, as well as a `question` that is the question about the ''' '''document. It returns a text that contains the answer to the question.''' ) _lowercase : List[Any] = '''document_qa''' _lowercase : List[str] = AutoProcessor _lowercase : str = VisionEncoderDecoderModel _lowercase : Optional[Any] = ['''image''', '''text'''] _lowercase : Tuple = ['''text'''] def __init__( self , *a , **a) -> List[str]: if not is_vision_available(): raise ValueError('Pillow must be installed to use the DocumentQuestionAnsweringTool.') super().__init__(*a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a) -> List[Any]: SCREAMING_SNAKE_CASE = '<s_docvqa><s_question>{user_input}</s_question><s_answer>' SCREAMING_SNAKE_CASE = task_prompt.replace('{user_input}' , a) SCREAMING_SNAKE_CASE = self.pre_processor.tokenizer( a , add_special_tokens=a , return_tensors='pt').input_ids SCREAMING_SNAKE_CASE = self.pre_processor(a , return_tensors='pt').pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def SCREAMING_SNAKE_CASE__ ( self , a) -> List[Any]: return self.model.generate( inputs['pixel_values'].to(self.device) , decoder_input_ids=inputs['decoder_input_ids'].to(self.device) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=a , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=a , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=a , ).sequences def SCREAMING_SNAKE_CASE__ ( self , a) -> str: SCREAMING_SNAKE_CASE = self.pre_processor.batch_decode(a)[0] SCREAMING_SNAKE_CASE = sequence.replace(self.pre_processor.tokenizer.eos_token , '') SCREAMING_SNAKE_CASE = sequence.replace(self.pre_processor.tokenizer.pad_token , '') SCREAMING_SNAKE_CASE = re.sub(R'<.*?>' , '' , a , count=1).strip() # remove first task start token SCREAMING_SNAKE_CASE = self.pre_processor.tokenajson(a) return sequence["answer"]
359
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput a_ : Dict = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class _snake_case ( A__ ): def __init__( self , *a , a=None , a=None , a=None , **a) -> List[Any]: super().__init__(*a , **a) SCREAMING_SNAKE_CASE = eval_examples SCREAMING_SNAKE_CASE = post_process_function SCREAMING_SNAKE_CASE = quant_trainer_args SCREAMING_SNAKE_CASE = 128 # default number of calibration samples def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Union[str, Any]: if calib_dataset is None and self.calib_dataset is None: raise ValueError('Trainer: calibration requires an calib_dataset.') SCREAMING_SNAKE_CASE = calib_dataset if calib_dataset is not None else self.calib_dataset SCREAMING_SNAKE_CASE = self._remove_unused_columns(a , description='Calibration') return DataLoader( a , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=a , ) def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.train_dataset if calib_dataset is None else calib_dataset SCREAMING_SNAKE_CASE = self.get_calib_dataloader(a) SCREAMING_SNAKE_CASE = self.model quant_trainer.configure_model(a , self.quant_trainer_args , calib=a) model.eval() quant_trainer.enable_calibration(a) logger.info('***** Running calibration *****') logger.info(f''' Num examples = {self.calib_num}''') logger.info(f''' Batch size = {calib_dataloader.batch_size}''') for step, inputs in enumerate(a): # Prediction step SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.prediction_step(a , a , prediction_loss_only=a) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = model def SCREAMING_SNAKE_CASE__ ( self , a=None , a=None , a=None , a = "eval") -> str: 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 = 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 , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions) 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) self.log(a) else: SCREAMING_SNAKE_CASE = {} 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 SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a = "test") -> Optional[Any]: 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 = 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 , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions , '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) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=a) def SCREAMING_SNAKE_CASE__ ( self , a="./") -> List[Any]: SCREAMING_SNAKE_CASE = self.eval_dataset SCREAMING_SNAKE_CASE = self.get_eval_dataloader(a) SCREAMING_SNAKE_CASE = next(iter(a)) # saving device - to make it consistent SCREAMING_SNAKE_CASE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # convert to tuple SCREAMING_SNAKE_CASE = tuple(v.to(a) for k, v in batch.items()) logger.info('Converting model to be onnx compatible') from pytorch_quantization.nn import TensorQuantizer SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = self.model.to(a) model.eval() model.float() SCREAMING_SNAKE_CASE = model.module if hasattr(a , 'module') else model quant_trainer.configure_model(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = os.path.join(a , 'model.onnx') logger.info(f'''exporting model to {output_model_file}''') SCREAMING_SNAKE_CASE = {0: 'batch_size', 1: 'seq_len'} torch.onnx.export( a , a , a , export_params=a , opset_version=13 , do_constant_folding=a , input_names=['input_ids', 'attention_mask', 'token_type_ids'] , output_names=['output_start_logits', 'output_end_logits'] , dynamic_axes={ 'input_ids': axes, 'attention_mask': axes, 'token_type_ids': axes, 'output_start_logits': axes, 'output_end_logits': axes, } , verbose=a , ) logger.info('onnx export finished')
327
0
"""simple docstring""" def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [False] * len(a__) SCREAMING_SNAKE_CASE = [-1] * len(a__) def dfs(_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = c for u in graph[v]: if not visited[u]: dfs(a__ , 1 - c) for i in range(len(a__)): if not visited[i]: dfs(a__ , 0) for i in range(len(a__)): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph a_ : Optional[Any] = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
360
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging a_ : Union[str, Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : List[str] = ['''pixel_values'''] def __init__( self , a = True , a = 1 / 255 , a = True , a = 8 , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = do_rescale SCREAMING_SNAKE_CASE = rescale_factor SCREAMING_SNAKE_CASE = do_pad SCREAMING_SNAKE_CASE = pad_size def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a) -> np.ndarray: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_image_size(a) SCREAMING_SNAKE_CASE = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE = (old_width // size + 1) * size - old_width return pad(a , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> List[str]: 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_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE = pad_size if pad_size is not None else self.pad_size 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_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE = [to_numpy_array(a) for image in images] if do_rescale: SCREAMING_SNAKE_CASE = [self.rescale(image=a , scale=a) for image in images] if do_pad: SCREAMING_SNAKE_CASE = [self.pad(a , size=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)
327
0
def lowerCamelCase__ (_UpperCAmelCase): if len(_UpperCAmelCase) < 2: return collection def circle_sort_util(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) -> bool: SCREAMING_SNAKE_CASE = False if low == high: return swapped SCREAMING_SNAKE_CASE = low SCREAMING_SNAKE_CASE = high while left < right: if collection[left] > collection[right]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = ( collection[right], collection[left], ) SCREAMING_SNAKE_CASE = True left += 1 right -= 1 if left == right and collection[left] > collection[right + 1]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = ( collection[right + 1], collection[left], ) SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = low + int((high - low) / 2) SCREAMING_SNAKE_CASE = circle_sort_util(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = circle_sort_util(_UpperCAmelCase , mid + 1 , _UpperCAmelCase) return swapped or left_swap or right_swap SCREAMING_SNAKE_CASE = True while is_not_sorted is True: SCREAMING_SNAKE_CASE = circle_sort_util(_UpperCAmelCase , 0 , len(_UpperCAmelCase) - 1) return collection if __name__ == "__main__": a_ : Dict = input('Enter numbers separated by a comma:\n').strip() a_ : List[str] = [int(item) for item in user_input.split(',')] print(circle_sort(unsorted))
361
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class _snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = TFCamembertModel.from_pretrained('jplu/tf-camembert-base') SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 2_5543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" SCREAMING_SNAKE_CASE = model(a)['last_hidden_state'] SCREAMING_SNAKE_CASE = tf.TensorShape((1, 10, 768)) self.assertEqual(output.shape , a) # compare the actual values for a slice. SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[[-0.02_54, 0.02_35, 0.10_27], [0.06_06, -0.18_11, -0.04_18], [-0.15_61, -0.11_27, 0.26_87]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4))
327
0
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=UpperCamelCase_ ) class _snake_case ( UpperCamelCase_ ): _lowercase : str = field(default='''automatic-speech-recognition''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) _lowercase : ClassVar[Features] = Features({'''audio''': Audio()} ) _lowercase : ClassVar[Features] = Features({'''transcription''': Value('''string''' )} ) _lowercase : str = "audio" _lowercase : str = "transcription" def SCREAMING_SNAKE_CASE__ ( self , a) -> Any: if self.audio_column not in features: raise ValueError(f'''Column {self.audio_column} is not present in features.''') if not isinstance(features[self.audio_column] , _a): raise ValueError(f'''Column {self.audio_column} is not an Audio type.''') SCREAMING_SNAKE_CASE = copy.deepcopy(self) SCREAMING_SNAKE_CASE = self.input_schema.copy() SCREAMING_SNAKE_CASE = features[self.audio_column] SCREAMING_SNAKE_CASE = input_schema return task_template @property def SCREAMING_SNAKE_CASE__ ( self) -> Dict[str, str]: return {self.audio_column: "audio", self.transcription_column: "transcription"}
362
from scipy.stats import pearsonr import datasets a_ : Optional[int] = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n' a_ : Optional[int] = '\nArgs:\n predictions (`list` of `int`): Predicted class labels, as returned by a model.\n references (`list` of `int`): Ground truth labels.\n return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n Example 1-A simple example using only predictions and references.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n\n Example 2-The same as Example 1, but that also returns the `p-value`.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n >>> print(sorted(list(results.keys())))\n [\'p-value\', \'pearsonr\']\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n >>> print(round(results[\'p-value\'], 2))\n 0.15\n' a_ : Any = '\n@article{2020SciPy-NMeth,\nauthor = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Antonio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\njournal = {Nature Methods},\nyear = {2020},\nvolume = {17},\npages = {261--272},\nadsurl = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('float'), 'references': datasets.Value('float'), }) , reference_urls=['https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=False) -> Optional[Any]: if return_pvalue: SCREAMING_SNAKE_CASE = pearsonr(a , a) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(a , a)[0])}
327
0
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments a_ : Union[str, Any] = logging.getLogger(__name__) @dataclass class _snake_case ( _A ): _lowercase : int = field( default=0.0 , metadata={'''help''': '''The label smoothing epsilon to apply (if not zero).'''} ) _lowercase : Optional[int] = field(default=_A , metadata={'''help''': '''Whether to SortishSamler or not.'''} ) _lowercase : Tuple = field( default=_A , metadata={'''help''': '''Whether to use generate to calculate generative metrics (ROUGE, BLEU).'''} ) _lowercase : int = field(default=_A , metadata={'''help''': '''whether to use adafactor'''} ) _lowercase : str = field( default=_A , metadata={'''help''': '''Encoder layer dropout probability. Goes into model.config.'''} ) _lowercase : Union[str, Any] = field( default=_A , metadata={'''help''': '''Decoder layer dropout probability. Goes into model.config.'''} ) _lowercase : List[str] = field(default=_A , metadata={'''help''': '''Dropout probability. Goes into model.config.'''} ) _lowercase : str = field( default=_A , metadata={'''help''': '''Attention dropout probability. Goes into model.config.'''} ) _lowercase : List[str] = field( default='''linear''' , metadata={'''help''': f'''Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'''} , )
363
import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class _snake_case ( unittest.TestCase ): _lowercase : List[Any] = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING _lowercase : int = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Any: SCREAMING_SNAKE_CASE = TextaTextGenerationPipeline(model=a , tokenizer=a) return generator, ["Something to write", "Something else"] def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Any: SCREAMING_SNAKE_CASE = generator('Something there') self.assertEqual(a , [{'generated_text': ANY(a)}]) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]['generated_text'].startswith('Something there')) SCREAMING_SNAKE_CASE = generator(['This is great !', 'Something else'] , num_return_sequences=2 , do_sample=a) self.assertEqual( a , [ [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], ] , ) SCREAMING_SNAKE_CASE = generator( ['This is great !', 'Something else'] , num_return_sequences=2 , batch_size=2 , do_sample=a) self.assertEqual( a , [ [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], ] , ) with self.assertRaises(a): generator(4) @require_torch def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='pt') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE = generator('Something there' , do_sample=a) self.assertEqual(a , [{'generated_text': ''}]) SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = generator( 'Something there' , num_return_sequences=a , num_beams=a , ) SCREAMING_SNAKE_CASE = [ {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': ''}, ] self.assertEqual(a , a) SCREAMING_SNAKE_CASE = generator('This is a test' , do_sample=a , num_return_sequences=2 , return_tensors=a) self.assertEqual( a , [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ] , ) SCREAMING_SNAKE_CASE = generator.model.config.eos_token_id SCREAMING_SNAKE_CASE = '<pad>' SCREAMING_SNAKE_CASE = generator( ['This is a test', 'This is a second test'] , do_sample=a , num_return_sequences=2 , batch_size=2 , return_tensors=a , ) self.assertEqual( a , [ [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ], [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ], ] , ) @require_tf def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='tf') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE = generator('Something there' , do_sample=a) self.assertEqual(a , [{'generated_text': ''}])
327
0
from collections.abc import Sequence def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = False): if not arr: return 0 SCREAMING_SNAKE_CASE = 0 if allow_empty_subarrays else float('-inf') SCREAMING_SNAKE_CASE = 0.0 for num in arr: SCREAMING_SNAKE_CASE = max(0 if allow_empty_subarrays else num , curr_sum + num) SCREAMING_SNAKE_CASE = max(__snake_case , __snake_case) return max_sum if __name__ == "__main__": from doctest import testmod testmod() a_ : int = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(f"""{max_subarray_sum(nums) = }""")
364
import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights SCREAMING_SNAKE_CASE = FlaxDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=a , cache_dir=a) SCREAMING_SNAKE_CASE = [t[-1] for t in os.walk(os.path.join(a , os.listdir(a)[0] , 'snapshots'))] SCREAMING_SNAKE_CASE = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith('.bin') for f in files) @slow @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 4 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 4.1_51_47_45) < 1E-3 assert np.abs(np.abs(a , dtype=np.floataa).sum() - 4_99_47.8_75) < 5E-1 SCREAMING_SNAKE_CASE = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]))) assert len(a) == num_samples def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='flax' , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.05_65_24_01)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_38_38_08.2)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_00_39_06)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_37_35_16.75)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_00_39_06)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_37_35_16.75)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = FlaxDDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , set_alpha_to_one=a , steps_offset=1 , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , scheduler=a , safety_checker=a , ) SCREAMING_SNAKE_CASE = scheduler.create_state() SCREAMING_SNAKE_CASE = scheduler_state SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.0_45_04_39_45)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_34_76_93.5)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = jax.random.split(jax.random.PRNGKey(0) , a) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a , ) SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) SCREAMING_SNAKE_CASE = images[2, 0, 256, 10:17, 1] # With memory efficient attention SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a , use_memory_efficient_attention=a , ) SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , jit=a).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) SCREAMING_SNAKE_CASE = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice).max() < 1E-2
327
0
import os from pathlib import Path def lowerCamelCase__ (): from torch.utils.cpp_extension import load SCREAMING_SNAKE_CASE = Path(_a).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' , _a , with_cuda=_a , extra_include_paths=[str(_a)] , 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
365
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets a_ : Tuple = '\\n@inproceedings{lin-2004-rouge,\n title = "{ROUGE}: A Package for Automatic Evaluation of Summaries",\n author = "Lin, Chin-Yew",\n booktitle = "Text Summarization Branches Out",\n month = jul,\n year = "2004",\n address = "Barcelona, Spain",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W04-1013",\n pages = "74--81",\n}\n' a_ : List[Any] = '\\nROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for\nevaluating automatic summarization and machine translation software in natural language processing.\nThe metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.\n\nNote that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.\n\nThis metrics is a wrapper around Google Research reimplementation of ROUGE:\nhttps://github.com/google-research/google-research/tree/master/rouge\n' a_ : List[str] = '\nCalculates average rouge scores for a list of hypotheses and 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 rouge_types: A list of rouge types to calculate.\n Valid names:\n `"rouge{n}"` (e.g. `"rouge1"`, `"rouge2"`) where: {n} is the n-gram based scoring,\n `"rougeL"`: Longest common subsequence based scoring.\n `"rougeLSum"`: rougeLsum splits text using `"\n"`.\n See details in https://github.com/huggingface/datasets/issues/617\n use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.\n use_aggregator: Return aggregates if this is set to True\nReturns:\n rouge1: rouge_1 (precision, recall, f1),\n rouge2: rouge_2 (precision, recall, f1),\n rougeL: rouge_l (precision, recall, f1),\n rougeLsum: rouge_lsum (precision, recall, f1)\nExamples:\n\n >>> rouge = datasets.load_metric(\'rouge\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> results = rouge.compute(predictions=predictions, references=references)\n >>> print(list(results.keys()))\n [\'rouge1\', \'rouge2\', \'rougeL\', \'rougeLsum\']\n >>> print(results["rouge1"])\n AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))\n >>> print(results["rouge1"].mid.fmeasure)\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence'), 'references': datasets.Value('string' , id='sequence'), }) , codebase_urls=['https://github.com/google-research/google-research/tree/master/rouge'] , reference_urls=[ 'https://en.wikipedia.org/wiki/ROUGE_(metric)', 'https://github.com/google-research/google-research/tree/master/rouge', ] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a=True , a=False) -> Optional[Any]: if rouge_types is None: SCREAMING_SNAKE_CASE = ['rouge1', 'rouge2', 'rougeL', 'rougeLsum'] SCREAMING_SNAKE_CASE = rouge_scorer.RougeScorer(rouge_types=a , use_stemmer=a) if use_aggregator: SCREAMING_SNAKE_CASE = scoring.BootstrapAggregator() else: SCREAMING_SNAKE_CASE = [] for ref, pred in zip(a , a): SCREAMING_SNAKE_CASE = scorer.score(a , a) if use_aggregator: aggregator.add_scores(a) else: scores.append(a) if use_aggregator: SCREAMING_SNAKE_CASE = aggregator.aggregate() else: SCREAMING_SNAKE_CASE = {} for key in scores[0]: SCREAMING_SNAKE_CASE = [score[key] for score in scores] return result
327
0
import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _snake_case ( A__ , unittest.TestCase ): _lowercase : Tuple = GPTSanJapaneseTokenizer _lowercase : List[Any] = False _lowercase : List[Any] = {"""do_clean_text""": False, """add_prefix_space""": False} def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: super().setUp() # fmt: off SCREAMING_SNAKE_CASE = ['こん', 'こんに', 'にちは', 'ばんは', '世界,㔺界', '、', '。', '<BR>', '<SP>', '<TAB>', '<URL>', '<EMAIL>', '<TEL>', '<DATE>', '<PRICE>', '<BLOCK>', '<KIGOU>', '<U2000U2BFF>', '<|emoji1|>', '<unk>', '<|bagoftoken|>', '<|endoftext|>'] # fmt: on SCREAMING_SNAKE_CASE = {'emoji': {'\ud83d\ude00': '<|emoji1|>'}, 'emoji_inv': {'<|emoji1|>': '\ud83d\ude00'}} # 😀 SCREAMING_SNAKE_CASE = {'unk_token': '<unk>'} SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file']) SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['emoji_file']) with open(self.vocab_file , 'w' , encoding='utf-8') as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens])) with open(self.emoji_file , 'w') as emoji_writer: emoji_writer.write(json.dumps(_lowercase)) def SCREAMING_SNAKE_CASE__ ( self , **a) -> List[Any]: kwargs.update(self.special_tokens_map) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **_lowercase) def SCREAMING_SNAKE_CASE__ ( self , a) -> List[Any]: SCREAMING_SNAKE_CASE = 'こんにちは、世界。 \nこんばんは、㔺界。😀' SCREAMING_SNAKE_CASE = 'こんにちは、世界。 \nこんばんは、世界。😀' return input_text, output_text def SCREAMING_SNAKE_CASE__ ( self , a) -> int: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.get_input_output_texts(_lowercase) SCREAMING_SNAKE_CASE = tokenizer.encode(_lowercase , add_special_tokens=_lowercase) SCREAMING_SNAKE_CASE = tokenizer.decode(_lowercase , clean_up_tokenization_spaces=_lowercase) return text, ids def SCREAMING_SNAKE_CASE__ ( self) -> Any: pass # TODO add if relevant def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: pass # TODO add if relevant def SCREAMING_SNAKE_CASE__ ( self) -> Dict: pass # TODO add if relevant def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_tokenizer() # Testing tokenization SCREAMING_SNAKE_CASE = 'こんにちは、世界。 こんばんは、㔺界。' SCREAMING_SNAKE_CASE = ['こん', 'にちは', '、', '世界', '。', '<SP>', 'こん', 'ばんは', '、', '㔺界', '。'] SCREAMING_SNAKE_CASE = tokenizer.tokenize(_lowercase) self.assertListEqual(_lowercase , _lowercase) # Testing conversion to ids without special tokens SCREAMING_SNAKE_CASE = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(_lowercase) self.assertListEqual(_lowercase , _lowercase) # Testing conversion to ids with special tokens SCREAMING_SNAKE_CASE = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19] SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(_lowercase) self.assertListEqual(_lowercase , _lowercase) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.get_tokenizer() # Testing tokenization SCREAMING_SNAKE_CASE = 'こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。' SCREAMING_SNAKE_CASE = 'こんにちは、、、、世界。こんばんは、、、、世界。' SCREAMING_SNAKE_CASE = tokenizer.encode(_lowercase) SCREAMING_SNAKE_CASE = tokenizer.decode(_lowercase) self.assertEqual(_lowercase , _lowercase) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese') # Testing tokenization SCREAMING_SNAKE_CASE = 'こんにちは、世界。' SCREAMING_SNAKE_CASE = 'こんばんは、㔺界。😀' SCREAMING_SNAKE_CASE = 'こんにちは、世界。こんばんは、世界。😀' SCREAMING_SNAKE_CASE = tokenizer.encode(prefix_text + input_text) SCREAMING_SNAKE_CASE = tokenizer.encode('' , prefix_text=prefix_text + input_text) SCREAMING_SNAKE_CASE = tokenizer.encode(_lowercase , prefix_text=_lowercase) SCREAMING_SNAKE_CASE = tokenizer.decode(_lowercase) SCREAMING_SNAKE_CASE = tokenizer.decode(_lowercase) SCREAMING_SNAKE_CASE = tokenizer.decode(_lowercase) self.assertEqual(_lowercase , _lowercase) self.assertEqual(_lowercase , _lowercase) self.assertEqual(_lowercase , _lowercase) @slow def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese') # Testing tokenization SCREAMING_SNAKE_CASE = 'こんにちは、世界。' SCREAMING_SNAKE_CASE = 'こんばんは、㔺界。😀' SCREAMING_SNAKE_CASE = len(tokenizer.encode(_lowercase)) - 2 SCREAMING_SNAKE_CASE = len(tokenizer.encode(_lowercase)) - 2 SCREAMING_SNAKE_CASE = [1] + [0] * (len_prefix + len_text + 1) SCREAMING_SNAKE_CASE = [1] * (len_prefix + len_text + 1) + [0] SCREAMING_SNAKE_CASE = [1] + [1] * (len_prefix) + [0] * (len_text + 1) SCREAMING_SNAKE_CASE = tokenizer(prefix_text + input_text).token_type_ids SCREAMING_SNAKE_CASE = tokenizer('' , prefix_text=prefix_text + input_text).token_type_ids SCREAMING_SNAKE_CASE = tokenizer(_lowercase , prefix_text=_lowercase).token_type_ids self.assertListEqual(_lowercase , _lowercase) self.assertListEqual(_lowercase , _lowercase) self.assertListEqual(_lowercase , _lowercase) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese') SCREAMING_SNAKE_CASE = tokenizer.encode('あンいワ') SCREAMING_SNAKE_CASE = tokenizer.encode('' , prefix_text='あンいワ') SCREAMING_SNAKE_CASE = tokenizer.encode('いワ' , prefix_text='あン') self.assertEqual(tokenizer.decode(_lowercase) , tokenizer.decode(_lowercase)) self.assertEqual(tokenizer.decode(_lowercase) , tokenizer.decode(_lowercase)) self.assertNotEqual(_lowercase , _lowercase) self.assertNotEqual(_lowercase , _lowercase) self.assertEqual(x_token_a[1] , x_token_a[-1]) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3]) # SEG token @slow def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese') SCREAMING_SNAKE_CASE = [['武田信玄', 'は、'], ['織田信長', 'の配下の、']] SCREAMING_SNAKE_CASE = tokenizer(_lowercase , padding=_lowercase) SCREAMING_SNAKE_CASE = tokenizer.batch_encode_plus(_lowercase , padding=_lowercase) # fmt: off SCREAMING_SNAKE_CASE = [[3_5993, 8640, 2_5948, 3_5998, 3_0647, 3_5675, 3_5999, 3_5999], [3_5993, 1_0382, 9868, 3_5998, 3_0646, 9459, 3_0646, 3_5675]] SCREAMING_SNAKE_CASE = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] SCREAMING_SNAKE_CASE = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , _lowercase) self.assertListEqual(x_token.token_type_ids , _lowercase) self.assertListEqual(x_token.attention_mask , _lowercase) self.assertListEqual(x_token_a.input_ids , _lowercase) self.assertListEqual(x_token_a.token_type_ids , _lowercase) self.assertListEqual(x_token_a.attention_mask , _lowercase) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: # Intentionally convert some words to accommodate character fluctuations unique to Japanese pass def SCREAMING_SNAKE_CASE__ ( self) -> Any: # tokenizer has no padding token pass
366
import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def lowerCamelCase__ (_UpperCAmelCase): if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class _snake_case ( nn.Module ): def __init__( self , a , a) -> Union[str, Any]: super().__init__() SCREAMING_SNAKE_CASE = module SCREAMING_SNAKE_CASE = nn.Sequential( nn.Linear(module.in_features , a , bias=a) , nn.Linear(a , module.out_features , bias=a) , ) SCREAMING_SNAKE_CASE = (2.0 / (5 * min(module.in_features , module.out_features))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=a) nn.init.zeros_(self.adapter[1].weight) self.adapter.to(module.weight.device) def SCREAMING_SNAKE_CASE__ ( self , a , *a , **a) -> Any: return self.module(a , *a , **a) + self.adapter(a) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): # We keep the constants inside the init function and model loading inside setUp function # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) # Therefore here we use only bloom-1b3 to test our module _lowercase : Union[str, Any] = '''bigscience/bloom-1b7''' # Constant values _lowercase : str = 2.109_6595_5269_2574 _lowercase : Any = '''Hello my name is''' _lowercase : Any = set() EXPECTED_OUTPUTS.add('''Hello my name is John and I am a professional photographer. I''' ) EXPECTED_OUTPUTS.add('''Hello my name is John.\nI am a friend of your father.\n''' ) EXPECTED_OUTPUTS.add('''Hello my name is John Doe, I am a student at the University''' ) _lowercase : Union[str, Any] = 10 def SCREAMING_SNAKE_CASE__ ( self) -> Any: # Models and tokenizer SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(self.model_name) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: super().setUp() # Models and tokenizer SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map='auto') SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_abit.config self.assertTrue(hasattr(a , 'quantization_config')) SCREAMING_SNAKE_CASE = config.to_dict() SCREAMING_SNAKE_CASE = config.to_diff_dict() SCREAMING_SNAKE_CASE = config.to_json_string() def SCREAMING_SNAKE_CASE__ ( self) -> Any: from bitsandbytes.nn import Paramsabit SCREAMING_SNAKE_CASE = self.model_fpaa.get_memory_footprint() SCREAMING_SNAKE_CASE = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE) SCREAMING_SNAKE_CASE = get_some_linear_layer(self.model_abit) self.assertTrue(linear.weight.__class__ == Paramsabit) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(a , torch.nn.Linear): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = self.model_abit.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = BitsAndBytesConfig() SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = model_abit_from_config.generate( input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) def SCREAMING_SNAKE_CASE__ ( self) -> str: with self.assertRaises(a), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = BitsAndBytesConfig() with self.assertRaises(a): SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=a , load_in_abit=a , device_map='auto' , bnb_abit_quant_type='nf4' , ) def SCREAMING_SNAKE_CASE__ ( self) -> int: with self.assertRaises(a): # Tries with `str` self.model_abit.to('cpu') with self.assertRaises(a): # Tries with a `dtype`` self.model_abit.to(torch.floataa) with self.assertRaises(a): # Tries with a `device` self.model_abit.to(torch.device('cuda:0')) with self.assertRaises(a): # Tries with a `device` self.model_abit.float() with self.assertRaises(a): # Tries with a `device` self.model_abit.half() # Test if we did not break anything SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = self.model_fpaa.to(torch.floataa) SCREAMING_SNAKE_CASE = self.model_fpaa.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.to('cpu') # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.half() # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.float() def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained('t5-small' , load_in_abit=a , device_map='auto') self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Tuple: SCREAMING_SNAKE_CASE = 't5-small' SCREAMING_SNAKE_CASE = 'google/flan-t5-small' # flan-t5 uses dense-act instead of dense-relu-dense SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(cls.model_name) SCREAMING_SNAKE_CASE = 'Translate in German: Hello, my dog is cute' def SCREAMING_SNAKE_CASE__ ( self) -> Dict: gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: from transformers import TaForConditionalGeneration SCREAMING_SNAKE_CASE = TaForConditionalGeneration._keep_in_fpaa_modules SCREAMING_SNAKE_CASE = None # test with `t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) # test with `flan-t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) SCREAMING_SNAKE_CASE = modules def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit)) SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) # test with `flan-t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> str: super().setUp() # model_name SCREAMING_SNAKE_CASE = 'bigscience/bloom-560m' SCREAMING_SNAKE_CASE = 't5-small' # Different types of model SCREAMING_SNAKE_CASE = AutoModel.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # Sequence classification model SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=a , device_map='auto') # CausalLM model SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # Seq2seq model SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=a , device_map='auto') def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Dict: del self.pipe gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = pipeline( 'text-generation' , model=self.model_name , model_kwargs={'device_map': 'auto', 'load_in_4bit': True, 'torch_dtype': torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass SCREAMING_SNAKE_CASE = self.pipe(self.input_text) self.assertIn(pipeline_output[0]['generated_text'] , self.EXPECTED_OUTPUTS) @require_torch_multi_gpu class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> int: super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=a , device_map='balanced') # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values()) , {0, 1}) # Check that inference pass works on the model SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') # Second real batch SCREAMING_SNAKE_CASE = model_parallel.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = 'facebook/opt-350m' super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Any: if version.parse(importlib.metadata.version('bitsandbytes')) < version.parse('0.37.0'): return # Step 1: freeze all parameters SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a) self.assertEqual(set(model.hf_device_map.values()) , {torch.cuda.current_device()}) for param in model.parameters(): SCREAMING_SNAKE_CASE = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability SCREAMING_SNAKE_CASE = param.data.to(torch.floataa) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(a)): SCREAMING_SNAKE_CASE = LoRALayer(module.q_proj , rank=16) SCREAMING_SNAKE_CASE = LoRALayer(module.k_proj , rank=16) SCREAMING_SNAKE_CASE = LoRALayer(module.v_proj , rank=16) # Step 3: dummy batch SCREAMING_SNAKE_CASE = self.tokenizer('Test batch ' , return_tensors='pt').to(0) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): SCREAMING_SNAKE_CASE = model.forward(**a) out.logits.norm().backward() for module in model.modules(): if isinstance(a , a): self.assertTrue(module.adapter[1].weight.grad is not None) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0) elif isinstance(a , nn.Embedding): self.assertTrue(module.weight.grad is None) class _snake_case ( A__ ): _lowercase : str = '''gpt2-xl''' _lowercase : Union[str, Any] = 3.3191_8548_5415_2187
327
0
import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class _snake_case ( lowerCamelCase_ ): _lowercase : Optional[int] = (DDIMParallelScheduler,) _lowercase : List[Any] = (("""eta""", 0.0), ("""num_inference_steps""", 50)) def SCREAMING_SNAKE_CASE__ ( self , **a) -> Union[str, Any]: SCREAMING_SNAKE_CASE = { 'num_train_timesteps': 1000, 'beta_start': 0.00_01, 'beta_end': 0.02, 'beta_schedule': 'linear', 'clip_sample': True, } config.update(**_UpperCAmelCase) return config def SCREAMING_SNAKE_CASE__ ( self , **a) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.scheduler_classes[0] SCREAMING_SNAKE_CASE = self.get_scheduler_config(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = scheduler_class(**_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 10, 0.0 SCREAMING_SNAKE_CASE = self.dummy_model() SCREAMING_SNAKE_CASE = self.dummy_sample_deter scheduler.set_timesteps(_UpperCAmelCase) for t in scheduler.timesteps: SCREAMING_SNAKE_CASE = model(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = scheduler.step(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase).prev_sample return sample def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: for timesteps in [100, 500, 1000]: self.check_over_configs(num_train_timesteps=_UpperCAmelCase) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: for steps_offset in [0, 1]: self.check_over_configs(steps_offset=_UpperCAmelCase) SCREAMING_SNAKE_CASE = self.scheduler_classes[0] SCREAMING_SNAKE_CASE = self.get_scheduler_config(steps_offset=1) SCREAMING_SNAKE_CASE = scheduler_class(**_UpperCAmelCase) scheduler.set_timesteps(5) assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1])) def SCREAMING_SNAKE_CASE__ ( self) -> Any: for beta_start, beta_end in zip([0.00_01, 0.0_01, 0.01, 0.1] , [0.0_02, 0.02, 0.2, 2]): self.check_over_configs(beta_start=_UpperCAmelCase , beta_end=_UpperCAmelCase) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=_UpperCAmelCase) def SCREAMING_SNAKE_CASE__ ( self) -> int: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_UpperCAmelCase) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: for clip_sample in [True, False]: self.check_over_configs(clip_sample=_UpperCAmelCase) def SCREAMING_SNAKE_CASE__ ( self) -> Any: for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=_UpperCAmelCase) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=_UpperCAmelCase) def SCREAMING_SNAKE_CASE__ ( self) -> Any: self.check_over_configs(thresholding=_UpperCAmelCase) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=_UpperCAmelCase , prediction_type=_UpperCAmelCase , sample_max_value=_UpperCAmelCase , ) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: for t in [1, 10, 49]: self.check_over_forward(time_step=_UpperCAmelCase) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500]): self.check_over_forward(time_step=_UpperCAmelCase , num_inference_steps=_UpperCAmelCase) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0]): self.check_over_forward(time_step=_UpperCAmelCase , eta=_UpperCAmelCase) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.scheduler_classes[0] SCREAMING_SNAKE_CASE = self.get_scheduler_config() SCREAMING_SNAKE_CASE = scheduler_class(**_UpperCAmelCase) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0) - 0.0)) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(420 , 400) - 0.1_47_71)) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(980 , 960) - 0.3_24_60)) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0) - 0.0)) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 , 486) - 0.0_09_79)) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 , 998) - 0.02)) < 1E-5 def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.scheduler_classes[0] SCREAMING_SNAKE_CASE = self.get_scheduler_config() SCREAMING_SNAKE_CASE = scheduler_class(**_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 10, 0.0 scheduler.set_timesteps(_UpperCAmelCase) SCREAMING_SNAKE_CASE = self.dummy_model() SCREAMING_SNAKE_CASE = self.dummy_sample_deter SCREAMING_SNAKE_CASE = self.dummy_sample_deter + 0.1 SCREAMING_SNAKE_CASE = self.dummy_sample_deter - 0.1 SCREAMING_SNAKE_CASE = samplea.shape[0] SCREAMING_SNAKE_CASE = torch.stack([samplea, samplea, samplea] , dim=0) SCREAMING_SNAKE_CASE = torch.arange(_UpperCAmelCase)[0:3, None].repeat(1 , _UpperCAmelCase) SCREAMING_SNAKE_CASE = model(samples.flatten(0 , 1) , timesteps.flatten(0 , 1)) SCREAMING_SNAKE_CASE = scheduler.batch_step_no_noise(_UpperCAmelCase , timesteps.flatten(0 , 1) , samples.flatten(0 , 1) , _UpperCAmelCase) SCREAMING_SNAKE_CASE = torch.sum(torch.abs(_UpperCAmelCase)) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(_UpperCAmelCase)) assert abs(result_sum.item() - 11_47.79_04) < 1E-2 assert abs(result_mean.item() - 0.49_82) < 1E-3 def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.full_loop() SCREAMING_SNAKE_CASE = torch.sum(torch.abs(_UpperCAmelCase)) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(_UpperCAmelCase)) assert abs(result_sum.item() - 1_72.00_67) < 1E-2 assert abs(result_mean.item() - 0.22_39_67) < 1E-3 def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.full_loop(prediction_type='v_prediction') SCREAMING_SNAKE_CASE = torch.sum(torch.abs(_UpperCAmelCase)) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(_UpperCAmelCase)) assert abs(result_sum.item() - 52.53_02) < 1E-2 assert abs(result_mean.item() - 0.06_84) < 1E-3 def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = self.full_loop(set_alpha_to_one=_UpperCAmelCase , beta_start=0.01) SCREAMING_SNAKE_CASE = torch.sum(torch.abs(_UpperCAmelCase)) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(_UpperCAmelCase)) assert abs(result_sum.item() - 1_49.82_95) < 1E-2 assert abs(result_mean.item() - 0.19_51) < 1E-3 def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.full_loop(set_alpha_to_one=_UpperCAmelCase , beta_start=0.01) SCREAMING_SNAKE_CASE = torch.sum(torch.abs(_UpperCAmelCase)) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(_UpperCAmelCase)) assert abs(result_sum.item() - 1_49.07_84) < 1E-2 assert abs(result_mean.item() - 0.19_41) < 1E-3
367
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : Optional[Any] = { 'configuration_efficientnet': [ 'EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'EfficientNetConfig', 'EfficientNetOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[str] = ['EfficientNetImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = [ 'EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'EfficientNetForImageClassification', 'EfficientNetModel', 'EfficientNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure)
327
0
def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if height >= 1: move_tower(height - 1 , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) move_disk(_UpperCAmelCase , _UpperCAmelCase) move_tower(height - 1 , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): print('moving disk from' , _UpperCAmelCase , 'to' , _UpperCAmelCase) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = int(input('Height of hanoi: ').strip()) move_tower(_UpperCAmelCase , 'A' , 'B' , 'C') if __name__ == "__main__": main()
368
import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) a_ : Dict = [ 'cross_validation.py', 'gradient_accumulation.py', 'local_sgd.py', 'multi_process_metrics.py', 'memory.py', 'automatic_gradient_accumulation.py', 'fsdp_with_peak_mem_tracking.py', 'deepspeed_with_config_support.py', 'megatron_lm_gpt_pretraining.py', ] class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , a = None) -> Optional[int]: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = os.path.abspath(os.path.join('examples' , 'by_feature')) SCREAMING_SNAKE_CASE = os.path.abspath('examples') for item in os.listdir(a): if item not in EXCLUDE_EXAMPLES: SCREAMING_SNAKE_CASE = os.path.join(a , a) if os.path.isfile(a) and ".py" in item_path: with self.subTest( tested_script=a , feature_script=a , tested_section='main()' if parser_only else 'training_function()' , ): SCREAMING_SNAKE_CASE = compare_against_test( os.path.join(a , a) , a , a , a) SCREAMING_SNAKE_CASE = '\n'.join(a) if special_strings is not None: for string in special_strings: SCREAMING_SNAKE_CASE = diff.replace(a , '') self.assertEqual(a , '') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: self.one_complete_example('complete_nlp_example.py' , a) self.one_complete_example('complete_nlp_example.py' , a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = os.path.abspath(os.path.join('examples' , 'cv_example.py')) SCREAMING_SNAKE_CASE = [ ' ' * 16 + '{\n\n', ' ' * 20 + '"accuracy": eval_metric["accuracy"],\n\n', ' ' * 20 + '"f1": eval_metric["f1"],\n\n', ' ' * 20 + '"train_loss": total_loss.item() / len(train_dataloader),\n\n', ' ' * 20 + '"epoch": epoch,\n\n', ' ' * 16 + '},\n\n', ' ' * 16 + 'step=epoch,\n', ' ' * 12, ' ' * 8 + 'for step, batch in enumerate(active_dataloader):\n', ] self.one_complete_example('complete_cv_example.py' , a , a , a) self.one_complete_example('complete_cv_example.py' , a , a , a) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class _snake_case ( A__ ): _lowercase : int = False @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Union[str, Any]: super().setUpClass() SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = os.path.join(cls._tmpdir , 'default_config.yml') write_basic_config(save_location=cls.configPath) SCREAMING_SNAKE_CASE = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Dict: super().tearDownClass() shutil.rmtree(cls._tmpdir) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'epoch_0'))) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'step_2'))) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0')} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) self.assertNotIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2')} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) if torch.cuda.is_available(): SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: SCREAMING_SNAKE_CASE = 1 if num_processes > 1: self.assertNotIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) else: self.assertIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = '\n examples/by_feature/cross_validation.py\n --num_folds 2\n '.split() with mock.patch.dict(os.environ , {'TESTING_MOCKED_DATALOADERS': '0'}): SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) SCREAMING_SNAKE_CASE = re.findall('({.+})' , a) SCREAMING_SNAKE_CASE = [r for r in results if 'accuracy' in r][-1] SCREAMING_SNAKE_CASE = ast.literal_eval(a) self.assertGreaterEqual(results['accuracy'] , 0.75) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ['examples/by_feature/multi_process_metrics.py'] run_command(self._launch_args + testargs) @require_trackers @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'}) def SCREAMING_SNAKE_CASE__ ( self) -> Any: with tempfile.TemporaryDirectory() as tmpdir: SCREAMING_SNAKE_CASE = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(a , 'tracking'))) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = ['examples/by_feature/gradient_accumulation.py'] run_command(self._launch_args + testargs) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = ['examples/by_feature/local_sgd.py'] run_command(self._launch_args + testargs)
327
0
def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [0] * len(a__) for i in range(1 , len(a__)): # use last results for better performance - dynamic programming SCREAMING_SNAKE_CASE = prefix_result[i - 1] while j > 0 and input_string[i] != input_string[j]: SCREAMING_SNAKE_CASE = prefix_result[j - 1] if input_string[i] == input_string[j]: j += 1 SCREAMING_SNAKE_CASE = j return prefix_result def lowerCamelCase__ (_UpperCAmelCase): return max(prefix_function(a__)) if __name__ == "__main__": import doctest doctest.testmod()
369
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _snake_case : def __init__( self , a , a=3 , a=32 , a=3 , a=10 , a=[10, 20, 30, 40] , a=[1, 1, 2, 1] , a=True , a=True , a="relu" , a=3 , a=None , ) -> Union[str, Any]: 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 SCREAMING_SNAKE_CASE__ ( self) -> List[str]: 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 SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return ResNetConfig( 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 , image_size=self.image_size , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Any: SCREAMING_SNAKE_CASE = TFResNetModel(config=a) 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 SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> int: SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = TFResNetForImageClassification(a) SCREAMING_SNAKE_CASE = model(a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: 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_tf class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () _lowercase : Dict = ( {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification} if is_tf_available() else {} ) _lowercase : Union[str, Any] = False _lowercase : Any = False _lowercase : List[str] = False _lowercase : str = False _lowercase : int = False def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = TFResNetModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , has_text_modality=a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return @unittest.skip(reason='ResNet does not use inputs_embeds') def SCREAMING_SNAKE_CASE__ ( self) -> int: pass @unittest.skip(reason='ResNet does not support input and output embeddings') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: pass def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: 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.call) # 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 SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: def check_hidden_states_output(a , a , a): SCREAMING_SNAKE_CASE = model_class(a) 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) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 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 SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> str: for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = TFResNetModel.from_pretrained(a) self.assertIsNotNone(a) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') return image @require_tf @require_vision class _snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = image_processor(images=a , return_tensors='tf') # forward pass SCREAMING_SNAKE_CASE = model(**a) # verify the logits SCREAMING_SNAKE_CASE = tf.TensorShape((1, 1000)) self.assertEqual(outputs.logits.shape , a) SCREAMING_SNAKE_CASE = tf.constant([-11.10_69, -9.78_77, -8.37_77]) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , a , atol=1E-4))
327
0
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartaaTokenizer, MBartaaTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from ...test_tokenization_common import TokenizerTesterMixin a_ : Union[str, Any] = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right a_ : List[Any] = 25_00_04 a_ : List[Any] = 25_00_20 @require_sentencepiece @require_tokenizers class _snake_case ( a__ , unittest.TestCase ): _lowercase : Optional[int] = MBartaaTokenizer _lowercase : Tuple = MBartaaTokenizerFast _lowercase : Optional[Any] = True _lowercase : Any = True def SCREAMING_SNAKE_CASE__ ( self) -> int: super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE = MBartaaTokenizer(a , src_lang='en_XX' , tgt_lang='ro_RO' , keep_accents=a) tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = "<s>" 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 SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , '<s>') self.assertEqual(vocab_keys[1] , '<pad>') self.assertEqual(vocab_keys[-1] , '<mask>') self.assertEqual(len(a) , 1054) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: self.assertEqual(self.get_tokenizer().vocab_size , 1054) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = MBartaaTokenizer(a , src_lang='en_XX' , tgt_lang='ro_RO' , keep_accents=a) SCREAMING_SNAKE_CASE = tokenizer.tokenize('This is a test') self.assertListEqual(a , ['▁This', '▁is', '▁a', '▁t', 'est']) self.assertListEqual( tokenizer.convert_tokens_to_ids(a) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) SCREAMING_SNAKE_CASE = tokenizer.tokenize('I was born in 92000, and this is falsé.') self.assertListEqual( a , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.'] , ) SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(a) self.assertListEqual( a , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(a) self.assertListEqual( a , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.'] , ) @slow def SCREAMING_SNAKE_CASE__ ( self) -> str: # fmt: off SCREAMING_SNAKE_CASE = {"input_ids": [[25_0004, 1_1062, 8_2772, 7, 15, 8_2772, 538, 5_1529, 237, 1_7198, 1290, 206, 9, 21_5175, 1314, 136, 1_7198, 1290, 206, 9, 5_6359, 42, 12_2009, 9, 1_6466, 16, 8_7344, 4537, 9, 4717, 7_8381, 6, 15_9958, 7, 15, 2_4480, 618, 4, 527, 2_2693, 5428, 4, 2777, 2_4480, 9874, 4, 4_3523, 594, 4, 803, 1_8392, 3_3189, 18, 4, 4_3523, 2_4447, 1_2399, 100, 2_4955, 8_3658, 9626, 14_4057, 15, 839, 2_2335, 16, 136, 2_4955, 8_3658, 8_3479, 15, 3_9102, 724, 16, 678, 645, 2789, 1328, 4589, 42, 12_2009, 11_5774, 23, 805, 1328, 4_6876, 7, 136, 5_3894, 1940, 4_2227, 4_1159, 1_7721, 823, 425, 4, 2_7512, 9_8722, 206, 136, 5531, 4970, 919, 1_7336, 5, 2], [25_0004, 2_0080, 618, 83, 8_2775, 47, 479, 9, 1517, 73, 5_3894, 333, 8_0581, 11_0117, 1_8811, 5256, 1295, 51, 15_2526, 297, 7986, 390, 12_4416, 538, 3_5431, 214, 98, 1_5044, 2_5737, 136, 7108, 4_3701, 23, 756, 13_5355, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [25_0004, 581, 6_3773, 11_9455, 6, 14_7797, 8_8203, 7, 645, 70, 21, 3285, 1_0269, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a , model_name='facebook/mbart-large-50' , revision='d3913889c59cd5c9e456b269c376325eabad57e2' , ) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return SCREAMING_SNAKE_CASE = (self.rust_tokenizer_class, "hf-internal-testing/tiny-random-mbart50", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})'''): SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(a , **a) SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(a , **a) SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(a) SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(a) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files)) SCREAMING_SNAKE_CASE = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f) self.assertSequenceEqual(a , a) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(a) SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(a) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(a , a)) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(a) # Save tokenizer rust, legacy_format=True SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(a , legacy_format=a) SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(a) # Checks it save with the same files self.assertSequenceEqual(a , a) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(a) SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(a) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(a , a)) shutil.rmtree(a) # Save tokenizer rust, legacy_format=False SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = tokenizer_r.save_pretrained(a , legacy_format=a) SCREAMING_SNAKE_CASE = tokenizer_p.save_pretrained(a) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files)) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE = tokenizer_r.from_pretrained(a) SCREAMING_SNAKE_CASE = tokenizer_p.from_pretrained(a) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(a , a)) shutil.rmtree(a) @require_torch @require_sentencepiece @require_tokenizers class _snake_case ( unittest.TestCase ): _lowercase : Any = '''facebook/mbart-large-50-one-to-many-mmt''' _lowercase : Union[str, Any] = [ ''' UN Chief Says There Is No Military Solution in Syria''', ''' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.''', ] _lowercase : Dict = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', '''Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei''' ''' pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor''' ''' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.''', ] _lowercase : Union[str, Any] = [EN_CODE, 82_74, 12_78_73, 2_59_16, 7, 86_22, 20_71, 4_38, 6_74_85, 53, 18_78_95, 23, 5_17_12, 2] @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Dict: SCREAMING_SNAKE_CASE = MBartaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang='en_XX' , tgt_lang='ro_RO') SCREAMING_SNAKE_CASE = 1 return cls def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ar_AR'] , 25_0001) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['en_EN'] , 25_0004) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ro_RO'] , 25_0020) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['mr_IN'] , 25_0038) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.tokenizer.batch_encode_plus(self.src_text).input_ids[0] self.assertListEqual(self.expected_src_tokens , a) def SCREAMING_SNAKE_CASE__ ( self) -> str: self.assertIn(a , self.tokenizer.all_special_ids) SCREAMING_SNAKE_CASE = [RO_CODE, 884, 9019, 96, 9, 916, 8_6792, 36, 1_8743, 1_5596, 5, 2] SCREAMING_SNAKE_CASE = self.tokenizer.decode(a , skip_special_tokens=a) SCREAMING_SNAKE_CASE = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=a) self.assertEqual(a , a) self.assertNotIn(self.tokenizer.eos_token , a) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = ["this is gunna be a long sentence " * 20] assert isinstance(src_text[0] , a) SCREAMING_SNAKE_CASE = 10 SCREAMING_SNAKE_CASE = self.tokenizer(a , max_length=a , truncation=a).input_ids[0] self.assertEqual(ids[0] , a) self.assertEqual(ids[-1] , 2) self.assertEqual(len(a) , a) def SCREAMING_SNAKE_CASE__ ( self) -> Any: self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR']) , [25_0053, 25_0001]) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(a) SCREAMING_SNAKE_CASE = MBartaaTokenizer.from_pretrained(a) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , a) @require_torch def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=a , return_tensors='pt') SCREAMING_SNAKE_CASE = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == RO_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2].tolist() == [2, RO_CODE] @require_torch def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=a , truncation=a , max_length=len(self.expected_src_tokens) , return_tensors='pt' , ) SCREAMING_SNAKE_CASE = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id) self.assertIsInstance(a , a) self.assertEqual((2, 14) , batch.input_ids.shape) self.assertEqual((2, 14) , batch.attention_mask.shape) SCREAMING_SNAKE_CASE = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , a) self.assertEqual(2 , batch.decoder_input_ids[0, 0]) # decoder_start_token_id # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE]) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id]) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , padding=a , truncation=a , max_length=3 , return_tensors='pt') SCREAMING_SNAKE_CASE = self.tokenizer( text_target=self.tgt_text , padding=a , truncation=a , max_length=10 , return_tensors='pt') SCREAMING_SNAKE_CASE = targets["input_ids"] SCREAMING_SNAKE_CASE = shift_tokens_right(a , self.tokenizer.pad_token_id) self.assertEqual(batch.input_ids.shape[1] , 3) self.assertEqual(batch.decoder_input_ids.shape[1] , 10) @require_torch def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='en_XX' , tgt_lang='ar_AR') self.assertEqual( nested_simplify(a) , { # en_XX, A, test, EOS 'input_ids': [[25_0004, 62, 3034, 2]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 25_0001, } , )
370
from math import isqrt def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [True] * max_number for i in range(2 , isqrt(max_number - 1) + 1): if is_prime[i]: for j in range(i**2 , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = False return [i for i in range(2 , _UpperCAmelCase) if is_prime[i]] def lowerCamelCase__ (_UpperCAmelCase = 10**8): SCREAMING_SNAKE_CASE = calculate_prime_numbers(max_number // 2) SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(f"""{solution() = }""")
327
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : List[str] = logging.get_logger(__name__) a_ : Dict = { 'BAAI/AltCLIP': 'https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json', # See all AltCLIP models at https://huggingface.co/models?filter=altclip } class _snake_case ( A__ ): _lowercase : str = '''altclip_text_model''' def __init__( self , a=25_0002 , a=1024 , a=24 , a=16 , a=4096 , a="gelu" , a=0.1 , a=0.1 , a=514 , a=1 , a=0.02 , a=0.02 , a=1E-05 , a=1 , a=0 , a=2 , a="absolute" , a=True , a=768 , **a , ) -> List[str]: super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE) 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 = 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 = initializer_factor SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = position_embedding_type SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = project_dim class _snake_case ( A__ ): _lowercase : int = '''altclip_vision_model''' def __init__( self , a=768 , a=3072 , a=512 , a=12 , a=12 , a=3 , a=224 , a=32 , a="quick_gelu" , a=1E-5 , a=0.0 , a=0.02 , a=1.0 , **a , ) -> Tuple: super().__init__(**_SCREAMING_SNAKE_CASE) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = projection_dim SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = initializer_factor SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = hidden_act @classmethod def SCREAMING_SNAKE_CASE__ ( cls , a , **a) -> "PretrainedConfig": cls._set_token_in_kwargs(_SCREAMING_SNAKE_CASE) SCREAMING_SNAKE_CASE = cls.get_config_dict(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE) # get the vision config dict if we are loading from AltCLIPConfig if config_dict.get('model_type') == "altclip": 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(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE) class _snake_case ( A__ ): _lowercase : str = '''altclip''' _lowercase : Any = True def __init__( self , a=None , a=None , a=768 , a=2.65_92 , **a) -> Optional[Any]: SCREAMING_SNAKE_CASE = kwargs.pop('text_config_dict' , _SCREAMING_SNAKE_CASE) SCREAMING_SNAKE_CASE = kwargs.pop('vision_config_dict' , _SCREAMING_SNAKE_CASE) super().__init__(**_SCREAMING_SNAKE_CASE) # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`. if text_config_dict is not None: if text_config is None: SCREAMING_SNAKE_CASE = {} # This is the complete result when using `text_config_dict`. SCREAMING_SNAKE_CASE = AltCLIPTextConfig(**_SCREAMING_SNAKE_CASE).to_dict() # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different. for key, value in _text_config_dict.items(): if key in text_config and value != text_config[key] and key not in ["transformers_version"]: # If specified in `text_config_dict` if key in text_config_dict: SCREAMING_SNAKE_CASE = ( f'''`{key}` is found in both `text_config_dict` and `text_config` but with different values. ''' f'''The value `text_config_dict["{key}"]` will be used instead.''' ) # If inferred from default argument values (just to be super careful) else: SCREAMING_SNAKE_CASE = ( f'''`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The ''' f'''value `text_config["{key}"]` will be overriden.''' ) logger.warning(_SCREAMING_SNAKE_CASE) # Update all values in `text_config` with the ones in `_text_config_dict`. text_config.update(_text_config_dict) if vision_config_dict is not None: if vision_config is None: SCREAMING_SNAKE_CASE = {} # This is the complete result when using `vision_config_dict`. SCREAMING_SNAKE_CASE = AltCLIPVisionConfig(**_SCREAMING_SNAKE_CASE).to_dict() # convert keys to string instead of integer if "id2label" in _vision_config_dict: SCREAMING_SNAKE_CASE = { str(_SCREAMING_SNAKE_CASE): value for key, value in _vision_config_dict['''id2label'''].items() } # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different. for key, value in _vision_config_dict.items(): if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]: # If specified in `vision_config_dict` if key in vision_config_dict: SCREAMING_SNAKE_CASE = ( f'''`{key}` is found in both `vision_config_dict` and `vision_config` but with different ''' f'''values. The value `vision_config_dict["{key}"]` will be used instead.''' ) # If inferred from default argument values (just to be super careful) else: SCREAMING_SNAKE_CASE = ( f'''`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. ''' f'''The value `vision_config["{key}"]` will be overriden.''' ) logger.warning(_SCREAMING_SNAKE_CASE) # Update all values in `vision_config` with the ones in `_vision_config_dict`. vision_config.update(_vision_config_dict) if text_config is None: SCREAMING_SNAKE_CASE = {} logger.info('`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.') if vision_config is None: SCREAMING_SNAKE_CASE = {} logger.info('`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.') SCREAMING_SNAKE_CASE = AltCLIPTextConfig(**_SCREAMING_SNAKE_CASE) SCREAMING_SNAKE_CASE = AltCLIPVisionConfig(**_SCREAMING_SNAKE_CASE) SCREAMING_SNAKE_CASE = projection_dim SCREAMING_SNAKE_CASE = logit_scale_init_value SCREAMING_SNAKE_CASE = 1.0 @classmethod def SCREAMING_SNAKE_CASE__ ( cls , a , a , **a) -> Optional[int]: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **_SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ ( self) -> str: 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
371
import baseaa def lowerCamelCase__ (_UpperCAmelCase): return baseaa.aaaencode(string.encode('utf-8')) def lowerCamelCase__ (_UpperCAmelCase): return baseaa.aaadecode(_UpperCAmelCase).decode('utf-8') if __name__ == "__main__": import doctest doctest.testmod()
327
0
def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [0] * len(lowerCamelCase__) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = 0 for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(lowerCamelCase__)): if indegree[i] == 0: queue.append(lowerCamelCase__) while queue: SCREAMING_SNAKE_CASE = queue.pop(0) cnt += 1 topo.append(lowerCamelCase__) for x in graph[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(lowerCamelCase__) if cnt != len(lowerCamelCase__): print('Cycle exists') else: print(lowerCamelCase__) # Adjacency List of Graph a_ : Tuple = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} topological_sort(graph)
350
import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(_UpperCAmelCase , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = emb.weight.shape SCREAMING_SNAKE_CASE = nn.Linear(_UpperCAmelCase , _UpperCAmelCase , bias=_UpperCAmelCase) SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = mam_aaa['args'] or mam_aaa['cfg']['model'] SCREAMING_SNAKE_CASE = mam_aaa['model'] remove_ignore_keys_(_UpperCAmelCase) SCREAMING_SNAKE_CASE = state_dict['encoder.embed_tokens.weight'].shape[0] SCREAMING_SNAKE_CASE = MaMaaaConfig( vocab_size=_UpperCAmelCase , max_position_embeddings=1024 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='relu' , ) SCREAMING_SNAKE_CASE = state_dict['decoder.embed_tokens.weight'] SCREAMING_SNAKE_CASE = MaMaaaForConditionalGeneration(_UpperCAmelCase) model.model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase) SCREAMING_SNAKE_CASE = make_linear_from_emb(model.model.shared) return model if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') a_ : List[str] = parser.parse_args() a_ : Dict = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
327
0
import os import tempfile import unittest from transformers.models.marian.convert_marian_tatoeba_to_pytorch import DEFAULT_REPO, TatoebaConverter from transformers.testing_utils import slow from transformers.utils import cached_property @unittest.skipUnless(os.path.exists(__SCREAMING_SNAKE_CASE ) , '''Tatoeba directory does not exist.''' ) class _snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = tempfile.mkdtemp() return TatoebaConverter(save_dir=_snake_case) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Dict: self.resolver.convert_models(['heb-eng']) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.resolver.write_model_card('opus-mt-he-en' , dry_run=_snake_case) assert mmeta["long_pair"] == "heb-eng"
351
import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = 'laion/clap-htsat-unfused' SCREAMING_SNAKE_CASE = tempfile.mkdtemp() def SCREAMING_SNAKE_CASE__ ( self , **a) -> Optional[Any]: return RobertaTokenizer.from_pretrained(self.checkpoint , **a) def SCREAMING_SNAKE_CASE__ ( self , **a) -> Union[str, Any]: return ClapFeatureExtractor.from_pretrained(self.checkpoint , **a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = ClapProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) self.assertIsInstance(processor.tokenizer , a) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor()) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)') SCREAMING_SNAKE_CASE = self.get_feature_extractor(do_normalize=a , padding_value=1.0) SCREAMING_SNAKE_CASE = ClapProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=a , padding_value=1.0) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) self.assertIsInstance(processor.tokenizer , a) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = floats_list((3, 1000)) SCREAMING_SNAKE_CASE = feature_extractor(a , return_tensors='np') SCREAMING_SNAKE_CASE = processor(audios=a , return_tensors='np') for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = 'This is a test string' SCREAMING_SNAKE_CASE = processor(text=a) SCREAMING_SNAKE_CASE = tokenizer(a) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE = processor.batch_decode(a) SCREAMING_SNAKE_CASE = tokenizer.batch_decode(a) self.assertListEqual(a , a) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , )
327
0
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing the experiment tracking capability, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a_ : List[Any] = 16 a_ : List[Any] = 32 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = 16): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc') def tokenize_function(_UpperCAmelCase): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=UpperCamelCase__ , max_length=UpperCamelCase__) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = datasets.map( UpperCamelCase__ , batched=UpperCamelCase__ , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE = 8 else: SCREAMING_SNAKE_CASE = None return tokenizer.pad( UpperCamelCase__ , padding='longest' , max_length=UpperCamelCase__ , pad_to_multiple_of=UpperCamelCase__ , return_tensors='pt' , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['train'] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=UpperCamelCase__) SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['validation'] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=UpperCamelCase__) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders a_ : str = mocked_dataloaders # noqa: F811 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS' , UpperCamelCase__) == "1": SCREAMING_SNAKE_CASE = 2 # Initialize Accelerator # New Code # # We pass in "all" to `log_with` to grab all available trackers in the environment # Note: If using a custom `Tracker` class, should be passed in here such as: # >>> log_with = ["all", MyCustomTrackerClassInstance()] if args.with_tracking: SCREAMING_SNAKE_CASE = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with='all' , project_dir=args.project_dir) else: SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE = config['''lr'''] SCREAMING_SNAKE_CASE = int(config['num_epochs']) SCREAMING_SNAKE_CASE = int(config['seed']) SCREAMING_SNAKE_CASE = int(config['batch_size']) set_seed(UpperCamelCase__) SCREAMING_SNAKE_CASE = get_dataloaders(UpperCamelCase__ , UpperCamelCase__) SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') # If the batch size is too big we use gradient accumulation SCREAMING_SNAKE_CASE = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: SCREAMING_SNAKE_CASE = batch_size // MAX_GPU_BATCH_SIZE SCREAMING_SNAKE_CASE = MAX_GPU_BATCH_SIZE # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=UpperCamelCase__) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE = model.to(accelerator.device) # Instantiate optimizer SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=UpperCamelCase__) # Instantiate scheduler SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=UpperCamelCase__ , num_warmup_steps=100 , num_training_steps=(len(UpperCamelCase__) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE = accelerator.prepare( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__) # New Code # # We need to initialize the trackers we use. Overall configurations can also be stored if args.with_tracking: SCREAMING_SNAKE_CASE = os.path.split(UpperCamelCase__)[-1].split('.')[0] accelerator.init_trackers(UpperCamelCase__ , UpperCamelCase__) # Now we train the model for epoch in range(UpperCamelCase__): model.train() # New Code # # For our tracking example, we will log the total loss of each epoch if args.with_tracking: SCREAMING_SNAKE_CASE = 0 for step, batch in enumerate(UpperCamelCase__): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) SCREAMING_SNAKE_CASE = model(**UpperCamelCase__) SCREAMING_SNAKE_CASE = outputs.loss # New Code # if args.with_tracking: total_loss += loss.detach().float() SCREAMING_SNAKE_CASE = loss / gradient_accumulation_steps accelerator.backward(UpperCamelCase__) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(UpperCamelCase__): # We could avoid this line since we set the accelerator with `device_placement=True` (the default). batch.to(accelerator.device) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**UpperCamelCase__) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch['labels'])) metric.add_batch( predictions=UpperCamelCase__ , references=UpperCamelCase__ , ) SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , UpperCamelCase__) # New Code # # To actually log, we call `Accelerator.log` # The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int` if args.with_tracking: accelerator.log( { 'accuracy': eval_metric['accuracy'], 'f1': eval_metric['f1'], 'train_loss': total_loss.item() / len(UpperCamelCase__), 'epoch': epoch, } , step=UpperCamelCase__ , ) # New Code # # When a run is finished, you should call `accelerator.end_training()` # to close all of the open trackers if args.with_tracking: accelerator.end_training() def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description='Simple example of training script.') parser.add_argument( '--mixed_precision' , type=UpperCamelCase__ , default=UpperCamelCase__ , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.') parser.add_argument( '--with_tracking' , action='store_true' , help='Whether to load in all available experiment trackers from the environment and use them for logging.' , ) parser.add_argument( '--project_dir' , type=UpperCamelCase__ , default='logs' , help='Location on where to store experiment tracking logs` and relevent project information' , ) SCREAMING_SNAKE_CASE = parser.parse_args() SCREAMING_SNAKE_CASE = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(UpperCamelCase__ , UpperCamelCase__) if __name__ == "__main__": main()
352
import argparse import datetime def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = { '0': 'Sunday', '1': 'Monday', '2': 'Tuesday', '3': 'Wednesday', '4': 'Thursday', '5': 'Friday', '6': 'Saturday', } SCREAMING_SNAKE_CASE = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(_UpperCAmelCase) < 11: raise ValueError('Must be 10 characters long') # Get month SCREAMING_SNAKE_CASE = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 13: raise ValueError('Month must be between 1 - 12') SCREAMING_SNAKE_CASE = date_input[2] # Validate if sep_a not in ["-", "/"]: raise ValueError('Date separator must be \'-\' or \'/\'') # Get day SCREAMING_SNAKE_CASE = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 32: raise ValueError('Date must be between 1 - 31') # Get second separator SCREAMING_SNAKE_CASE = date_input[5] # Validate if sep_a not in ["-", "/"]: raise ValueError('Date separator must be \'-\' or \'/\'') # Get year SCREAMING_SNAKE_CASE = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 45 < y < 8500: raise ValueError( 'Year out of range. There has to be some sort of limit...right?') # Get datetime obj for validation SCREAMING_SNAKE_CASE = datetime.date(int(_UpperCAmelCase) , int(_UpperCAmelCase) , int(_UpperCAmelCase)) # Start math if m <= 2: SCREAMING_SNAKE_CASE = y - 1 SCREAMING_SNAKE_CASE = m + 12 # maths var SCREAMING_SNAKE_CASE = int(str(_UpperCAmelCase)[:2]) SCREAMING_SNAKE_CASE = int(str(_UpperCAmelCase)[2:]) SCREAMING_SNAKE_CASE = int(2.6 * m - 5.39) SCREAMING_SNAKE_CASE = int(c / 4) SCREAMING_SNAKE_CASE = int(k / 4) SCREAMING_SNAKE_CASE = int(d + k) SCREAMING_SNAKE_CASE = int(t + u + v + x) SCREAMING_SNAKE_CASE = int(z - (2 * c)) SCREAMING_SNAKE_CASE = round(w % 7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError('The date was evaluated incorrectly. Contact developer.') # Response SCREAMING_SNAKE_CASE = F'''Your date {date_input}, is a {days[str(_UpperCAmelCase)]}!''' return response if __name__ == "__main__": import doctest doctest.testmod() a_ : Tuple = argparse.ArgumentParser( description=( 'Find out what day of the week nearly any date is or was. Enter ' 'date as a string in the mm-dd-yyyy or mm/dd/yyyy format' ) ) parser.add_argument( 'date_input', type=str, help='Date as a string (mm-dd-yyyy or mm/dd/yyyy)' ) a_ : Any = parser.parse_args() zeller(args.date_input)
327
0
"""simple docstring""" def lowerCamelCase__ (_UpperCAmelCase): if len(UpperCAmelCase_) <= 1: return [tuple(UpperCAmelCase_)] SCREAMING_SNAKE_CASE = [] def generate(_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [0] * n res.append(tuple(UpperCAmelCase_)) SCREAMING_SNAKE_CASE = 0 while i < n: if c[i] < i: if i % 2 == 0: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = arr[i], arr[0] else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = arr[i], arr[c[i]] res.append(tuple(UpperCAmelCase_)) c[i] += 1 SCREAMING_SNAKE_CASE = 0 else: SCREAMING_SNAKE_CASE = 0 i += 1 generate(len(UpperCAmelCase_) , UpperCAmelCase_) return res if __name__ == "__main__": a_ : Any = input('Enter numbers separated by a comma:\n').strip() a_ : str = [int(item) for item in user_input.split(',')] print(heaps(arr))
353
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 convert_to_rgb, 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 if is_vision_available(): import PIL a_ : Optional[Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : Optional[int] = ['''pixel_values'''] def __init__( self , a = True , a = None , a = PILImageResampling.BICUBIC , a = True , a = 1 / 255 , a = True , a = None , a = None , a = True , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = size if size is not None else {'height': 384, 'width': 384} SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) SCREAMING_SNAKE_CASE = do_resize SCREAMING_SNAKE_CASE = size SCREAMING_SNAKE_CASE = resample 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 SCREAMING_SNAKE_CASE__ ( self , a , a , a = PILImageResampling.BICUBIC , a = None , **a , ) -> np.ndarray: SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}''') SCREAMING_SNAKE_CASE = (size['height'], size['width']) return resize(a , size=a , resample=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a , ) -> Optional[Any]: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a = None , **a , ) -> np.ndarray: return normalize(a , mean=a , std=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> PIL.Image.Image: SCREAMING_SNAKE_CASE = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE = resample if resample is not None else self.resample 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 = size if size is not None else self.size SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) 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 or resample is None: raise ValueError('Size and resample must be specified if do_resize 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_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 = BatchFeature(data={'pixel_values': images} , tensor_type=a) return encoded_outputs
327
0
import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: a_ : List[str] = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class _snake_case ( unittest.TestCase ): def __init__( self , a , a=7 , a=3 , a=18 , a=30 , a=400 , a=None , a=True , a=True , a=None , ) -> Tuple: 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 SCREAMING_SNAKE_CASE__ ( self) -> int: return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: 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 _snake_case ( lowerCamelCase__ , unittest.TestCase ): _lowercase : Tuple = PixaStructImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = PixaStructImageProcessingTester(self) @property def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: 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 SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: 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 SCREAMING_SNAKE_CASE__ ( self) -> Tuple: 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 SCREAMING_SNAKE_CASE__ ( self) -> Tuple: 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 SCREAMING_SNAKE_CASE__ ( self) -> int: 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 SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: 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 _snake_case ( lowerCamelCase__ , unittest.TestCase ): _lowercase : Dict = PixaStructImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = PixaStructImageProcessingTester(self , num_channels=4) SCREAMING_SNAKE_CASE = 3 @property def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ ( self) -> Any: 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 SCREAMING_SNAKE_CASE__ ( self) -> int: 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) , )
354
class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = val SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None def SCREAMING_SNAKE_CASE__ ( self , a) -> str: if self.val: if val < self.val: if self.left is None: SCREAMING_SNAKE_CASE = Node(a) else: self.left.insert(a) elif val > self.val: if self.right is None: SCREAMING_SNAKE_CASE = Node(a) else: self.right.insert(a) else: SCREAMING_SNAKE_CASE = val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Recursive traversal if root: inorder(root.left , _UpperCAmelCase) res.append(root.val) inorder(root.right , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): # Build BST if len(_UpperCAmelCase) == 0: return arr SCREAMING_SNAKE_CASE = Node(arr[0]) for i in range(1 , len(_UpperCAmelCase)): root.insert(arr[i]) # Traverse BST in order. SCREAMING_SNAKE_CASE = [] inorder(_UpperCAmelCase , _UpperCAmelCase) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
327
0
import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a_ : Any = 16 a_ : str = 32 def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = 16): """simple docstring""" SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('bert-base-cased') SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc') def tokenize_function(_UpperCAmelCase): # max_length=None => use the model max length (it's actually the default) SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_UpperCAmelCase , max_length=_UpperCAmelCase) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels') def collate_fn(_UpperCAmelCase): # On TPU it's best to pad everything to the same length or training will be very slow. SCREAMING_SNAKE_CASE = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": SCREAMING_SNAKE_CASE = 8 else: SCREAMING_SNAKE_CASE = None return tokenizer.pad( _UpperCAmelCase , padding='longest' , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_tensors='pt' , ) # Instantiate dataloaders. SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['train'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=_UpperCAmelCase) SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets['validation'] , shuffle=_UpperCAmelCase , collate_fn=_UpperCAmelCase , batch_size=_UpperCAmelCase , drop_last=(accelerator.mixed_precision == 'fp8') , ) return train_dataloader, eval_dataloader def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): """simple docstring""" SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs SCREAMING_SNAKE_CASE = config['lr'] SCREAMING_SNAKE_CASE = int(config['num_epochs']) SCREAMING_SNAKE_CASE = int(config['seed']) SCREAMING_SNAKE_CASE = int(config['batch_size']) SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc') # If the batch size is too big we use gradient accumulation SCREAMING_SNAKE_CASE = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: SCREAMING_SNAKE_CASE = batch_size // MAX_GPU_BATCH_SIZE SCREAMING_SNAKE_CASE = MAX_GPU_BATCH_SIZE set_seed(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_dataloaders(_UpperCAmelCase , _UpperCAmelCase) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=_UpperCAmelCase) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). SCREAMING_SNAKE_CASE = model.to(accelerator.device) # Instantiate optimizer SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=_UpperCAmelCase) # Instantiate scheduler SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=_UpperCAmelCase , num_warmup_steps=100 , num_training_steps=(len(_UpperCAmelCase) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) # Now we train the model for epoch in range(_UpperCAmelCase): model.train() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.loss SCREAMING_SNAKE_CASE = loss / gradient_accumulation_steps accelerator.backward(_UpperCAmelCase) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch['labels'])) metric.add_batch( predictions=_UpperCAmelCase , references=_UpperCAmelCase , ) SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , _UpperCAmelCase) def lowerCamelCase__ (): """simple docstring""" SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description='Simple example of training script.') parser.add_argument( '--mixed_precision' , type=_UpperCAmelCase , default=_UpperCAmelCase , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.') SCREAMING_SNAKE_CASE = parser.parse_args() SCREAMING_SNAKE_CASE = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
355
import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint a_ : Optional[int] = { '169M': 12, '430M': 24, '1B5': 24, '3B': 32, '7B': 32, '14B': 40, } a_ : Optional[int] = { '169M': 7_68, '430M': 10_24, '1B5': 20_48, '3B': 25_60, '7B': 40_96, '14B': 51_20, } def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = list(state_dict.keys()) for name in state_dict_keys: SCREAMING_SNAKE_CASE = state_dict.pop(_UpperCAmelCase) # emb -> embedding if name.startswith('emb.'): SCREAMING_SNAKE_CASE = name.replace('emb.' , 'embeddings.') # ln_0 -> pre_ln (only present at block 0) if name.startswith('blocks.0.ln0'): SCREAMING_SNAKE_CASE = name.replace('blocks.0.ln0' , 'blocks.0.pre_ln') # att -> attention SCREAMING_SNAKE_CASE = re.sub(R'blocks\.(\d+)\.att' , R'blocks.\1.attention' , _UpperCAmelCase) # ffn -> feed_forward SCREAMING_SNAKE_CASE = re.sub(R'blocks\.(\d+)\.ffn' , R'blocks.\1.feed_forward' , _UpperCAmelCase) # time_mix_k -> time_mix_key and reshape if name.endswith('.time_mix_k'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_k' , '.time_mix_key') # time_mix_v -> time_mix_value and reshape if name.endswith('.time_mix_v'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_v' , '.time_mix_value') # time_mix_r -> time_mix_key and reshape if name.endswith('.time_mix_r'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_r' , '.time_mix_receptance') if name != "head.weight": SCREAMING_SNAKE_CASE = 'rwkv.' + name SCREAMING_SNAKE_CASE = weight return state_dict def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=False , _UpperCAmelCase=None): # 1. If possible, build the tokenizer. if tokenizer_file is None: print('No `--tokenizer_file` provided, we will use the default tokenizer.') SCREAMING_SNAKE_CASE = 5_0277 SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('EleutherAI/gpt-neox-20b') else: SCREAMING_SNAKE_CASE = PreTrainedTokenizerFast(tokenizer_file=_UpperCAmelCase) SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) tokenizer.save_pretrained(_UpperCAmelCase) # 2. Build the config SCREAMING_SNAKE_CASE = list(NUM_HIDDEN_LAYERS_MAPPING.keys()) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: SCREAMING_SNAKE_CASE = candidate break if size is None: raise ValueError('Could not infer the size, please provide it with the `--size` argument.') if size not in possible_sizes: raise ValueError(F'''`size` should be one of {possible_sizes}, got {size}.''') SCREAMING_SNAKE_CASE = RwkvConfig( vocab_size=_UpperCAmelCase , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(_UpperCAmelCase) # 3. Download model file then convert state_dict SCREAMING_SNAKE_CASE = hf_hub_download(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = convert_state_dict(_UpperCAmelCase) # 4. Split in shards and save SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = shard_checkpoint(_UpperCAmelCase) for shard_file, shard in shards.items(): torch.save(_UpperCAmelCase , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) if index is not None: SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , _UpperCAmelCase) # Save the index as well with open(_UpperCAmelCase , 'w' , encoding='utf-8') as f: SCREAMING_SNAKE_CASE = json.dumps(_UpperCAmelCase , indent=2 , sort_keys=_UpperCAmelCase) + '\n' f.write(_UpperCAmelCase) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( 'Cleaning up shards. This may error with an OOM error, it this is the case don\'t worry you still have converted the model.') SCREAMING_SNAKE_CASE = list(shards.keys()) del state_dict del shards gc.collect() for shard_file in shard_files: SCREAMING_SNAKE_CASE = torch.load(os.path.join(_UpperCAmelCase , _UpperCAmelCase)) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError('Please provide a `model_name` to push the model to the Hub.') SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(_UpperCAmelCase) model.push_to_hub(_UpperCAmelCase , max_shard_size='2GB') tokenizer.push_to_hub(_UpperCAmelCase) if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--repo_id', default=None, type=str, required=True, help='Repo ID from which to pull the checkpoint.' ) parser.add_argument( '--checkpoint_file', default=None, type=str, required=True, help='Name of the checkpoint file in the repo.' ) parser.add_argument( '--output_dir', default=None, type=str, required=True, help='Where to save the converted model.' ) parser.add_argument( '--tokenizer_file', default=None, type=str, help='Path to the tokenizer file to use (if not provided, only the model is converted).', ) parser.add_argument( '--size', default=None, type=str, help='Size of the model. Will be inferred from the `checkpoint_file` if not passed.', ) parser.add_argument( '--push_to_hub', action='store_true', help='Push to the Hub the converted model.', ) parser.add_argument( '--model_name', default=None, type=str, help='Name of the pushed model on the Hub, including the username / organization.', ) a_ : Tuple = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
327
0
import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import ops from transformers import GradientAccumulator, create_optimizer @require_tf class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> List[Any]: self.assertEqual(len(lowercase_) , len(lowercase_)) for a, b in zip(lowercase_ , lowercase_): self.assertAlmostEqual(lowercase_ , lowercase_ , delta=lowercase_) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = GradientAccumulator() accumulator([tf.constant([1.0, 2.0])]) accumulator([tf.constant([-2.0, 1.0])]) accumulator([tf.constant([-1.0, 2.0])]) with self.assertRaises(lowercase_): accumulator([tf.constant([1.0, 1.0]), tf.constant([2.0, 2.0])]) self.assertEqual(accumulator.step , 3) self.assertEqual(len(accumulator.gradients) , 1) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1E-2) accumulator.reset() self.assertEqual(accumulator.step , 0) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1E-2) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = None ops.enable_eager_execution_internal() SCREAMING_SNAKE_CASE = tf.config.list_physical_devices('CPU') if len(lowercase_) == 1: tf.config.set_logical_device_configuration( physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()]) SCREAMING_SNAKE_CASE = tf.config.list_logical_devices(device_type='CPU') SCREAMING_SNAKE_CASE = tf.distribute.MirroredStrategy(devices=devices[:2]) with strategy.scope(): SCREAMING_SNAKE_CASE = GradientAccumulator() SCREAMING_SNAKE_CASE = tf.Variable([4.0, 3.0]) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = create_optimizer(5E-5 , 10 , 5) SCREAMING_SNAKE_CASE = tf.Variable([0.0, 0.0] , trainable=lowercase_) def accumulate_on_replica(a): accumulator([gradient]) def apply_on_replica(): optimizer.apply_gradients(list(zip(accumulator.gradients , [variable]))) @tf.function def accumulate(a , a): with strategy.scope(): SCREAMING_SNAKE_CASE = strategy.experimental_local_results(lowercase_) local_variables[0].assign(lowercase_) local_variables[1].assign(lowercase_) strategy.run(lowercase_ , args=(gradient_placeholder,)) @tf.function def apply_grad(): with strategy.scope(): strategy.run(lowercase_) def _check_local_values(a , a): SCREAMING_SNAKE_CASE = strategy.experimental_local_results(accumulator._gradients[0]) self.assertListAlmostEqual(values[0].value() , lowercase_ , tol=1E-2) self.assertListAlmostEqual(values[1].value() , lowercase_ , tol=1E-2) accumulate([1.0, 2.0] , [-1.0, 1.0]) accumulate([3.0, -1.0] , [-1.0, -1.0]) accumulate([-2.0, 2.0] , [3.0, -2.0]) self.assertEqual(accumulator.step , 3) _check_local_values([2.0, 3.0] , [1.0, -2.0]) apply_grad() self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1E-2) accumulator.reset() self.assertEqual(accumulator.step , 0) _check_local_values([0.0, 0.0] , [0.0, 0.0])
356
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def lowerCamelCase__ (_UpperCAmelCase): monkeypatch.setattr('datasets.utils.deprecation_utils._emitted_deprecation_warnings' , set()) @pytest.fixture def lowerCamelCase__ (_UpperCAmelCase): class _snake_case : def __init__( self , a) -> List[Any]: SCREAMING_SNAKE_CASE = metric_id class _snake_case : _lowercase : Optional[Any] = [MetricMock(A__ ) for metric_id in ['''accuracy''', '''mse''', '''precision''', '''codeparrot/apps_metric''']] def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: return self._metrics monkeypatch.setattr('datasets.inspect.huggingface_hub' , HfhMock()) @pytest.mark.parametrize( 'func, args' , [(load_metric, ('metrics/mse',)), (list_metrics, ()), (inspect_metric, ('metrics/mse', 'tmp_path'))]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if "tmp_path" in args: SCREAMING_SNAKE_CASE = tuple(arg if arg != 'tmp_path' else tmp_path for arg in args) with pytest.warns(_UpperCAmelCase , match='https://huggingface.co/docs/evaluate'): func(*_UpperCAmelCase)
327
0
"""simple docstring""" import os from collections.abc import Iterator def lowerCamelCase__ (_UpperCAmelCase = "."): for dir_path, dir_names, filenames in os.walk(lowercase_): SCREAMING_SNAKE_CASE = [d for d in dir_names if d != 'scripts' and d[0] not in '._'] for filename in filenames: if filename == "__init__.py": continue if os.path.splitext(lowercase_)[1] in (".py", ".ipynb"): yield os.path.join(lowercase_ , lowercase_).lstrip('./') def lowerCamelCase__ (_UpperCAmelCase): return F'''{i * ' '}*''' if i else "\n##" def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = old_path.split(os.sep) for i, new_part in enumerate(new_path.split(os.sep)): if (i + 1 > len(lowercase_) or old_parts[i] != new_part) and new_part: print(F'''{md_prefix(lowercase_)} {new_part.replace('_' , ' ').title()}''') return new_path def lowerCamelCase__ (_UpperCAmelCase = "."): SCREAMING_SNAKE_CASE = '' for filepath in sorted(good_file_paths(lowercase_)): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = os.path.split(lowercase_) if filepath != old_path: SCREAMING_SNAKE_CASE = print_path(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE = (filepath.count(os.sep) + 1) if filepath else 0 SCREAMING_SNAKE_CASE = F'''{filepath}/{filename}'''.replace(' ' , '%20') SCREAMING_SNAKE_CASE = os.path.splitext(filename.replace('_' , ' ').title())[0] print(F'''{md_prefix(lowercase_)} [{filename}]({url})''') if __name__ == "__main__": print_directory_md('.')
357
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : Any = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Dict = ['MLukeTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys a_ : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
327
0
import unittest from transformers import RoFormerTokenizer, RoFormerTokenizerFast from transformers.testing_utils import require_rjieba, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_rjieba @require_tokenizers class _snake_case ( a_ , unittest.TestCase ): _lowercase : Optional[Any] = RoFormerTokenizer _lowercase : Optional[int] = RoFormerTokenizerFast _lowercase : Union[str, Any] = True _lowercase : str = True def SCREAMING_SNAKE_CASE__ ( self) -> Dict: super().setUp() def SCREAMING_SNAKE_CASE__ ( self , **a) -> List[str]: return self.tokenizer_class.from_pretrained('junnyu/roformer_chinese_base' , **lowercase_) def SCREAMING_SNAKE_CASE__ ( self , **a) -> List[str]: return self.rust_tokenizer_class.from_pretrained('junnyu/roformer_chinese_base' , **lowercase_) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = '''永和服装饰品有限公司,今天天气非常好''' SCREAMING_SNAKE_CASE = '''永和 服装 饰品 有限公司 , 今 天 天 气 非常 好''' return input_text, output_text def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = self.get_chinese_input_output_texts() SCREAMING_SNAKE_CASE = tokenizer.tokenize(lowercase_) self.assertListEqual(lowercase_ , output_text.split()) SCREAMING_SNAKE_CASE = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE = [2_2943, 2_1332, 3_4431, 4_5904, 117, 306, 1231, 1231, 2653, 3_3994, 1266, 100] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase_) , lowercase_) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE = self.get_chinese_input_output_texts() SCREAMING_SNAKE_CASE = tokenizer.tokenize(lowercase_) self.assertListEqual(lowercase_ , output_text.split()) SCREAMING_SNAKE_CASE = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE = [2_2943, 2_1332, 3_4431, 4_5904, 117, 306, 1231, 1231, 2653, 3_3994, 1266, 100] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase_) , lowercase_) def SCREAMING_SNAKE_CASE__ ( self) -> Any: pass def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: pass def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: pass
358
from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer a_ : List[Any] = logging.get_logger(__name__) a_ : Union[str, Any] = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} a_ : str = { 'vocab_file': { 'allegro/herbert-base-cased': 'https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json' }, 'merges_file': { 'allegro/herbert-base-cased': 'https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt' }, } a_ : List[Any] = {'allegro/herbert-base-cased': 5_14} a_ : Dict = {} class _snake_case ( A__ ): _lowercase : Dict = VOCAB_FILES_NAMES _lowercase : int = PRETRAINED_VOCAB_FILES_MAP _lowercase : Any = PRETRAINED_INIT_CONFIGURATION _lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : Any = HerbertTokenizer def __init__( self , a=None , a=None , a=None , a="<s>" , a="<unk>" , a="<pad>" , a="<mask>" , a="</s>" , **a , ) -> Dict: super().__init__( a , a , tokenizer_file=a , cls_token=a , unk_token=a , pad_token=a , mask_token=a , sep_token=a , **a , ) def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: SCREAMING_SNAKE_CASE = [self.cls_token_id] SCREAMING_SNAKE_CASE = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = False) -> List[int]: 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] + ([0] * len(a)) + [1] def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: 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 SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> Tuple[str]: SCREAMING_SNAKE_CASE = self._tokenizer.model.save(a , name=a) return tuple(a)
327
0
from ..utils import DummyObject, requires_backends class _snake_case ( metaclass=A__ ): _lowercase : Optional[int] = ['''flax''', '''transformers'''] def __init__( self , *a , **a) -> List[str]: requires_backends(self , ['flax', 'transformers']) @classmethod def SCREAMING_SNAKE_CASE__ ( cls , *a , **a) -> List[str]: requires_backends(cls , ['flax', 'transformers']) @classmethod def SCREAMING_SNAKE_CASE__ ( cls , *a , **a) -> Any: requires_backends(cls , ['flax', 'transformers']) class _snake_case ( metaclass=A__ ): _lowercase : Any = ['''flax''', '''transformers'''] def __init__( self , *a , **a) -> str: requires_backends(self , ['flax', 'transformers']) @classmethod def SCREAMING_SNAKE_CASE__ ( cls , *a , **a) -> List[str]: requires_backends(cls , ['flax', 'transformers']) @classmethod def SCREAMING_SNAKE_CASE__ ( cls , *a , **a) -> Dict: requires_backends(cls , ['flax', 'transformers']) class _snake_case ( metaclass=A__ ): _lowercase : Union[str, Any] = ['''flax''', '''transformers'''] def __init__( self , *a , **a) -> List[Any]: requires_backends(self , ['flax', 'transformers']) @classmethod def SCREAMING_SNAKE_CASE__ ( cls , *a , **a) -> Optional[Any]: requires_backends(cls , ['flax', 'transformers']) @classmethod def SCREAMING_SNAKE_CASE__ ( cls , *a , **a) -> Optional[int]: requires_backends(cls , ['flax', 'transformers']) class _snake_case ( metaclass=A__ ): _lowercase : str = ['''flax''', '''transformers'''] def __init__( self , *a , **a) -> Any: requires_backends(self , ['flax', 'transformers']) @classmethod def SCREAMING_SNAKE_CASE__ ( cls , *a , **a) -> Optional[Any]: requires_backends(cls , ['flax', 'transformers']) @classmethod def SCREAMING_SNAKE_CASE__ ( cls , *a , **a) -> List[str]: requires_backends(cls , ['flax', 'transformers'])
359
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput a_ : Dict = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class _snake_case ( A__ ): def __init__( self , *a , a=None , a=None , a=None , **a) -> List[Any]: super().__init__(*a , **a) SCREAMING_SNAKE_CASE = eval_examples SCREAMING_SNAKE_CASE = post_process_function SCREAMING_SNAKE_CASE = quant_trainer_args SCREAMING_SNAKE_CASE = 128 # default number of calibration samples def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Union[str, Any]: if calib_dataset is None and self.calib_dataset is None: raise ValueError('Trainer: calibration requires an calib_dataset.') SCREAMING_SNAKE_CASE = calib_dataset if calib_dataset is not None else self.calib_dataset SCREAMING_SNAKE_CASE = self._remove_unused_columns(a , description='Calibration') return DataLoader( a , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=a , ) def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.train_dataset if calib_dataset is None else calib_dataset SCREAMING_SNAKE_CASE = self.get_calib_dataloader(a) SCREAMING_SNAKE_CASE = self.model quant_trainer.configure_model(a , self.quant_trainer_args , calib=a) model.eval() quant_trainer.enable_calibration(a) logger.info('***** Running calibration *****') logger.info(f''' Num examples = {self.calib_num}''') logger.info(f''' Batch size = {calib_dataloader.batch_size}''') for step, inputs in enumerate(a): # Prediction step SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.prediction_step(a , a , prediction_loss_only=a) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = model def SCREAMING_SNAKE_CASE__ ( self , a=None , a=None , a=None , a = "eval") -> str: 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 = 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 , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions) 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) self.log(a) else: SCREAMING_SNAKE_CASE = {} 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 SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a = "test") -> Optional[Any]: 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 = 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 , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions , '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) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=a) def SCREAMING_SNAKE_CASE__ ( self , a="./") -> List[Any]: SCREAMING_SNAKE_CASE = self.eval_dataset SCREAMING_SNAKE_CASE = self.get_eval_dataloader(a) SCREAMING_SNAKE_CASE = next(iter(a)) # saving device - to make it consistent SCREAMING_SNAKE_CASE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # convert to tuple SCREAMING_SNAKE_CASE = tuple(v.to(a) for k, v in batch.items()) logger.info('Converting model to be onnx compatible') from pytorch_quantization.nn import TensorQuantizer SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = self.model.to(a) model.eval() model.float() SCREAMING_SNAKE_CASE = model.module if hasattr(a , 'module') else model quant_trainer.configure_model(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = os.path.join(a , 'model.onnx') logger.info(f'''exporting model to {output_model_file}''') SCREAMING_SNAKE_CASE = {0: 'batch_size', 1: 'seq_len'} torch.onnx.export( a , a , a , export_params=a , opset_version=13 , do_constant_folding=a , input_names=['input_ids', 'attention_mask', 'token_type_ids'] , output_names=['output_start_logits', 'output_end_logits'] , dynamic_axes={ 'input_ids': axes, 'attention_mask': axes, 'token_type_ids': axes, 'output_start_logits': axes, 'output_end_logits': axes, } , verbose=a , ) logger.info('onnx export finished')
327
0
"""simple docstring""" def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Check if the input is valid if not len(_UpperCAmelCase) == len(_UpperCAmelCase) == 3: raise ValueError('Please enter a valid equation.') if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0: raise ValueError('Both a & b of two equations can\'t be zero.') # Extract the coefficients SCREAMING_SNAKE_CASE = equationa SCREAMING_SNAKE_CASE = equationa # Calculate the determinants of the matrices SCREAMING_SNAKE_CASE = aa * ba - aa * ba SCREAMING_SNAKE_CASE = ca * ba - ca * ba SCREAMING_SNAKE_CASE = aa * ca - aa * ca # Check if the system of linear equations has a solution (using Cramer's rule) if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError('Infinite solutions. (Consistent system)') else: raise ValueError('No solution. (Inconsistent system)') else: if determinant_x == determinant_y == 0: # Trivial solution (Inconsistent system) return (0.0, 0.0) else: SCREAMING_SNAKE_CASE = determinant_x / determinant SCREAMING_SNAKE_CASE = determinant_y / determinant # Non-Trivial Solution (Consistent system) return (x, y)
360
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging a_ : Union[str, Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : List[str] = ['''pixel_values'''] def __init__( self , a = True , a = 1 / 255 , a = True , a = 8 , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = do_rescale SCREAMING_SNAKE_CASE = rescale_factor SCREAMING_SNAKE_CASE = do_pad SCREAMING_SNAKE_CASE = pad_size def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a) -> np.ndarray: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_image_size(a) SCREAMING_SNAKE_CASE = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE = (old_width // size + 1) * size - old_width return pad(a , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> List[str]: 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_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE = pad_size if pad_size is not None else self.pad_size 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_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE = [to_numpy_array(a) for image in images] if do_rescale: SCREAMING_SNAKE_CASE = [self.rescale(image=a , scale=a) for image in images] if do_pad: SCREAMING_SNAKE_CASE = [self.pad(a , size=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)
327
0
def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = abs(_a) SCREAMING_SNAKE_CASE = 0 while n > 0: res += n % 10 n //= 10 return res def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = abs(_a) return n if n < 10 else n % 10 + sum_of_digits(n // 10) def lowerCamelCase__ (_UpperCAmelCase): return sum(int(_a) for c in str(abs(_a))) def lowerCamelCase__ (): from collections.abc import Callable from timeit import timeit def benchmark_a_function(_UpperCAmelCase , _UpperCAmelCase) -> None: SCREAMING_SNAKE_CASE = F'''{func.__name__}({value})''' SCREAMING_SNAKE_CASE = timeit(F'''__main__.{call}''' , setup='import __main__') print(F'''{call:56} = {func(_a)} -- {timing:.4f} seconds''') for value in (26_2144, 1125_8999_0684_2624, 126_7650_6002_2822_9401_4967_0320_5376): for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact): benchmark_a_function(_a , _a) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
361
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class _snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = TFCamembertModel.from_pretrained('jplu/tf-camembert-base') SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 2_5543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" SCREAMING_SNAKE_CASE = model(a)['last_hidden_state'] SCREAMING_SNAKE_CASE = tf.TensorShape((1, 10, 768)) self.assertEqual(output.shape , a) # compare the actual values for a slice. SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[[-0.02_54, 0.02_35, 0.10_27], [0.06_06, -0.18_11, -0.04_18], [-0.15_61, -0.11_27, 0.26_87]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4))
327
0
import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a_ : Any = logging.get_logger(__name__) a_ : Tuple = {'vocab_file': 'vocab.json'} a_ : Tuple = { 'vocab_file': { 'mgp-str': 'https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json', } } a_ : str = {'mgp-str': 27} class _snake_case ( lowerCamelCase__ ): _lowercase : Union[str, Any] = VOCAB_FILES_NAMES _lowercase : int = PRETRAINED_VOCAB_FILES_MAP _lowercase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , a , a="[GO]" , a="[GO]" , a="[s]" , a="[GO]" , **a) -> Any: super().__init__( unk_token=snake_case__ , bos_token=snake_case__ , eos_token=snake_case__ , pad_token=snake_case__ , **snake_case__ , ) with open(snake_case__ , encoding='utf-8') as vocab_handle: SCREAMING_SNAKE_CASE = json.load(snake_case__) SCREAMING_SNAKE_CASE = {v: k for k, v in self.vocab.items()} @property def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: return len(self.vocab) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return dict(self.vocab , **self.added_tokens_encoder) def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = [] for s in text: char_tokens.extend(snake_case__) return char_tokens def SCREAMING_SNAKE_CASE__ ( self , a) -> Union[str, Any]: return self.vocab.get(snake_case__ , self.vocab.get(self.unk_token)) def SCREAMING_SNAKE_CASE__ ( self , a) -> Union[str, Any]: return self.decoder.get(snake_case__) def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> Tuple[str]: if not os.path.isdir(snake_case__): logger.error('Vocabulary path ({}) should be a directory'.format(snake_case__)) return SCREAMING_SNAKE_CASE = os.path.join( snake_case__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) with open(snake_case__ , 'w' , encoding='utf-8') as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=snake_case__ , ensure_ascii=snake_case__) + '\n') return (vocab_file,)
362
from scipy.stats import pearsonr import datasets a_ : Optional[int] = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n' a_ : Optional[int] = '\nArgs:\n predictions (`list` of `int`): Predicted class labels, as returned by a model.\n references (`list` of `int`): Ground truth labels.\n return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n Example 1-A simple example using only predictions and references.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n\n Example 2-The same as Example 1, but that also returns the `p-value`.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n >>> print(sorted(list(results.keys())))\n [\'p-value\', \'pearsonr\']\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n >>> print(round(results[\'p-value\'], 2))\n 0.15\n' a_ : Any = '\n@article{2020SciPy-NMeth,\nauthor = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Antonio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\njournal = {Nature Methods},\nyear = {2020},\nvolume = {17},\npages = {261--272},\nadsurl = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('float'), 'references': datasets.Value('float'), }) , reference_urls=['https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=False) -> Optional[Any]: if return_pvalue: SCREAMING_SNAKE_CASE = pearsonr(a , a) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(a , a)[0])}
327
0
import logging import re import pytorch_quantization import pytorch_quantization.nn as quant_nn import torch from pytorch_quantization import calib from pytorch_quantization.tensor_quant import QuantDescriptor a_ : Optional[int] = logging.getLogger(__name__) a_ : List[Any] = 50 # max width of layer names a_ : Dict = 70 # max width of quantizer names def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = parser.add_argument_group('quant_trainer arguments') group.add_argument('--wprec' , type=_lowercase , default=8 , help='weight precision') group.add_argument('--aprec' , type=_lowercase , default=8 , help='activation precision') group.add_argument('--quant-per-tensor' , action='store_true' , help='per tensor weight scaling') group.add_argument('--quant-disable' , action='store_true' , help='disable all quantizers') group.add_argument('--quant-disable-embeddings' , action='store_true' , help='disable all embeddings quantizers') group.add_argument('--quant-disable-keyword' , type=_lowercase , nargs='+' , help='disable quantizers by keyword') group.add_argument('--quant-disable-layer-module' , type=_lowercase , help='disable quantizers by keyword under layer.') group.add_argument('--quant-enable-layer-module' , type=_lowercase , help='enable quantizers by keyword under layer') group.add_argument('--calibrator' , default='max' , help='which quantization range calibrator to use') group.add_argument('--percentile' , default=_lowercase , type=_lowercase , help='percentile for PercentileCalibrator') group.add_argument('--fuse-qkv' , action='store_true' , help='use the same scale factor for qkv') group.add_argument('--clip-gelu' , metavar='N' , type=_lowercase , help='clip gelu output maximum value to N') group.add_argument( '--recalibrate-weights' , action='store_true' , help=( 'recalibrate weight amaxes by taking the max of the weights.' ' amaxes will be computed with the current quantization granularity (axis).' ) , ) def lowerCamelCase__ (_UpperCAmelCase): if args.calibrator == "max": SCREAMING_SNAKE_CASE = "max" elif args.calibrator == "percentile": if args.percentile is None: raise ValueError('Specify --percentile when using percentile calibrator') SCREAMING_SNAKE_CASE = "histogram" elif args.calibrator == "mse": SCREAMING_SNAKE_CASE = "histogram" else: raise ValueError(F'''Invalid calibrator {args.calibrator}''') SCREAMING_SNAKE_CASE = QuantDescriptor(num_bits=args.aprec , calib_method=_lowercase) SCREAMING_SNAKE_CASE = QuantDescriptor(num_bits=args.wprec , axis=(None if args.quant_per_tensor else (0,))) quant_nn.QuantLinear.set_default_quant_desc_input(_lowercase) quant_nn.QuantLinear.set_default_quant_desc_weight(_lowercase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=False , _UpperCAmelCase=False): logger.info('Configuring Model for Quantization') logger.info(F'''using quantization package {pytorch_quantization.__file__}''') if not calib: if args.quant_disable_embeddings: set_quantizer_by_name(_lowercase , ['embeddings'] , which='weight' , _disabled=_lowercase) if args.quant_disable: set_quantizer_by_name(_lowercase , [''] , _disabled=_lowercase) if args.quant_disable_keyword: set_quantizer_by_name(_lowercase , args.quant_disable_keyword , _disabled=_lowercase) if args.quant_disable_layer_module: set_quantizer_by_name(_lowercase , [R'layer.\d+.' + args.quant_disable_layer_module] , _disabled=_lowercase) if args.quant_enable_layer_module: set_quantizer_by_name(_lowercase , [R'layer.\d+.' + args.quant_enable_layer_module] , _disabled=_lowercase) if args.recalibrate_weights: recalibrate_weights(_lowercase) if args.fuse_qkv: fuse_qkv(_lowercase , _lowercase) if args.clip_gelu: clip_gelu(_lowercase , args.clip_gelu) # if args.local_rank in [-1, 0] and not calib: print_quant_summary(_lowercase) def lowerCamelCase__ (_UpperCAmelCase): logger.info('Enabling Calibration') for name, module in model.named_modules(): if name.endswith('_quantizer'): if module._calibrator is not None: module.disable_quant() module.enable_calib() else: module.disable() logger.info(F'''{name:80}: {module}''') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): logger.info('Loading calibrated amax') for name, module in model.named_modules(): if name.endswith('_quantizer'): if module._calibrator is not None: if isinstance(module._calibrator , calib.MaxCalibrator): module.load_calib_amax() else: module.load_calib_amax('percentile' , percentile=args.percentile) module.enable_quant() module.disable_calib() else: module.enable() model.cuda() print_quant_summary(_lowercase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): def fusea(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for mod in [qq, qk, qv]: if not hasattr(_lowercase , '_amax'): print(' WARNING: NO AMAX BUFFER') return SCREAMING_SNAKE_CASE = qq._amax.detach().item() SCREAMING_SNAKE_CASE = qk._amax.detach().item() SCREAMING_SNAKE_CASE = qv._amax.detach().item() SCREAMING_SNAKE_CASE = max(_lowercase , _lowercase , _lowercase) qq._amax.fill_(_lowercase) qk._amax.fill_(_lowercase) qv._amax.fill_(_lowercase) logger.info(F''' q={q:5.2f} k={k:5.2f} v={v:5.2f} -> {amax:5.2f}''') for name, mod in model.named_modules(): if name.endswith('.attention.self'): logger.info(F'''FUSE_QKV: {name:{name_width}}''') fusea(mod.matmul_q_input_quantizer , mod.matmul_k_input_quantizer , mod.matmul_v_input_quantizer) if args.quant_per_tensor: fusea(mod.query._weight_quantizer , mod.key._weight_quantizer , mod.value._weight_quantizer) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): for name, mod in model.named_modules(): if name.endswith('.output.dense') and not name.endswith('attention.output.dense'): SCREAMING_SNAKE_CASE = mod._input_quantizer._amax.data.detach().item() mod._input_quantizer._amax.data.detach().clamp_(max=_lowercase) SCREAMING_SNAKE_CASE = mod._input_quantizer._amax.data.detach().item() logger.info(F'''CLIP_GELU: {name:{name_width}} amax: {amax_init:5.2f} -> {amax:5.2f}''') def lowerCamelCase__ (_UpperCAmelCase): for name, mod in model.named_modules(): if hasattr(_lowercase , '_weight_quantizer') and mod._weight_quantizer.axis is not None: SCREAMING_SNAKE_CASE = mod.weight.shape[0] SCREAMING_SNAKE_CASE = mod._weight_quantizer._amax.detach() SCREAMING_SNAKE_CASE = torch.ones(_lowercase , dtype=amax.dtype , device=amax.device) * amax print(F'''expanding {name} {amax} -> {mod._weight_quantizer._amax}''') def lowerCamelCase__ (_UpperCAmelCase): for name, mod in model.named_modules(): if hasattr(_lowercase , '_weight_quantizer'): if not hasattr(mod.weight_quantizer , '_amax'): print('RECALIB: {name:{name_width}} WARNING: NO AMAX BUFFER') continue # determine which axes to reduce across # e.g. a 4D tensor quantized per axis 0 should reduce over (1,2,3) SCREAMING_SNAKE_CASE = set() if mod._weight_quantizer.axis is None else set(mod._weight_quantizer.axis) SCREAMING_SNAKE_CASE = set(range(len(mod.weight.size()))) - axis_set SCREAMING_SNAKE_CASE = pytorch_quantization.utils.reduce_amax(mod.weight , axis=_lowercase , keepdims=_lowercase).detach() logger.info(F'''RECALIB: {name:{name_width}} {mod._weight_quantizer._amax.flatten()} -> {amax.flatten()}''') SCREAMING_SNAKE_CASE = amax def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=25 , _UpperCAmelCase=180 , _UpperCAmelCase=None): if ignore is None: SCREAMING_SNAKE_CASE = [] elif not isinstance(_lowercase , _lowercase): SCREAMING_SNAKE_CASE = [ignore] SCREAMING_SNAKE_CASE = 0 for name, mod in model.named_modules(): if not hasattr(_lowercase , 'weight'): continue SCREAMING_SNAKE_CASE = max(_lowercase , len(_lowercase)) for name, mod in model.named_modules(): SCREAMING_SNAKE_CASE = getattr(_lowercase , '_input_quantizer' , _lowercase) SCREAMING_SNAKE_CASE = getattr(_lowercase , '_weight_quantizer' , _lowercase) if not hasattr(_lowercase , 'weight'): continue if type(_lowercase) in ignore: continue if [True for s in ignore if type(_lowercase) is str and s in name]: continue SCREAMING_SNAKE_CASE = F'''Act:{input_q.extra_repr()}''' SCREAMING_SNAKE_CASE = F'''Wgt:{weight_q.extra_repr()}''' SCREAMING_SNAKE_CASE = F'''{name:{name_width}} {act_str} {wgt_str}''' if len(_lowercase) <= line_width: logger.info(_lowercase) else: logger.info(F'''{name:{name_width}} {act_str}''') logger.info(F'''{' ':{name_width}} {wgt_str}''') def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = 0 for name, mod in model.named_modules(): if isinstance(_lowercase , pytorch_quantization.nn.TensorQuantizer): print(F'''{name:80} {mod}''') count += 1 print(F'''{count} TensorQuantizers found in model''') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = getattr(_lowercase , _lowercase , _lowercase) if quantizer_mod is not None: assert hasattr(_lowercase , _lowercase) setattr(_lowercase , _lowercase , _lowercase) else: logger.warning(F'''{name} has no {quantizer}''') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase="both" , **_UpperCAmelCase): SCREAMING_SNAKE_CASE = F'''Warning: changing {which} quantizers of {name:{qname_width}}''' for k, v in kwargs.items(): s += F''' {k}={v}''' if which in ["input", "both"]: set_quantizer(_lowercase , _lowercase , '_input_quantizer' , _lowercase , _lowercase) if which in ["weight", "both"]: set_quantizer(_lowercase , _lowercase , '_weight_quantizer' , _lowercase , _lowercase) logger.info(_lowercase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , **_UpperCAmelCase): for name, mod in model.named_modules(): if hasattr(_lowercase , '_input_quantizer') or hasattr(_lowercase , '_weight_quantizer'): for n in names: if re.search(_lowercase , _lowercase): set_quantizers(_lowercase , _lowercase , **_lowercase) elif name.endswith('_quantizer'): for n in names: if re.search(_lowercase , _lowercase): SCREAMING_SNAKE_CASE = F'''Warning: changing {name:{name_width}}''' for k, v in kwargs.items(): s += F''' {k}={v}''' setattr(_lowercase , _lowercase , _lowercase) logger.info(_lowercase)
363
import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class _snake_case ( unittest.TestCase ): _lowercase : List[Any] = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING _lowercase : int = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Any: SCREAMING_SNAKE_CASE = TextaTextGenerationPipeline(model=a , tokenizer=a) return generator, ["Something to write", "Something else"] def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Any: SCREAMING_SNAKE_CASE = generator('Something there') self.assertEqual(a , [{'generated_text': ANY(a)}]) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]['generated_text'].startswith('Something there')) SCREAMING_SNAKE_CASE = generator(['This is great !', 'Something else'] , num_return_sequences=2 , do_sample=a) self.assertEqual( a , [ [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], ] , ) SCREAMING_SNAKE_CASE = generator( ['This is great !', 'Something else'] , num_return_sequences=2 , batch_size=2 , do_sample=a) self.assertEqual( a , [ [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], ] , ) with self.assertRaises(a): generator(4) @require_torch def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='pt') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE = generator('Something there' , do_sample=a) self.assertEqual(a , [{'generated_text': ''}]) SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = generator( 'Something there' , num_return_sequences=a , num_beams=a , ) SCREAMING_SNAKE_CASE = [ {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': ''}, ] self.assertEqual(a , a) SCREAMING_SNAKE_CASE = generator('This is a test' , do_sample=a , num_return_sequences=2 , return_tensors=a) self.assertEqual( a , [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ] , ) SCREAMING_SNAKE_CASE = generator.model.config.eos_token_id SCREAMING_SNAKE_CASE = '<pad>' SCREAMING_SNAKE_CASE = generator( ['This is a test', 'This is a second test'] , do_sample=a , num_return_sequences=2 , batch_size=2 , return_tensors=a , ) self.assertEqual( a , [ [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ], [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ], ] , ) @require_tf def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='tf') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE = generator('Something there' , do_sample=a) self.assertEqual(a , [{'generated_text': ''}])
327
0
from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = cva.getAffineTransform(_UpperCAmelCase , _UpperCAmelCase) return cva.warpAffine(_UpperCAmelCase , _UpperCAmelCase , (rows, cols)) if __name__ == "__main__": # read original image a_ : List[Any] = cva.imread( str(Path(__file__).resolve().parent.parent / 'image_data' / 'lena.jpg') ) # turn image in gray scale value a_ : Optional[int] = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape a_ : Optional[int] = gray_img.shape # set different points to rotate image a_ : str = np.array([[50, 50], [2_00, 50], [50, 2_00]], np.floataa) a_ : Tuple = np.array([[10, 1_00], [2_00, 50], [1_00, 2_50]], np.floataa) a_ : Union[str, Any] = np.array([[50, 50], [1_50, 50], [1_20, 2_00]], np.floataa) a_ : Union[str, Any] = np.array([[10, 1_00], [80, 50], [1_80, 2_50]], np.floataa) # add all rotated images in a list a_ : Optional[int] = [ gray_img, get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), ] # plot different image rotations a_ : Optional[int] = plt.figure(1) a_ : Tuple = ["""Original""", """Rotation 1""", """Rotation 2""", """Rotation 3"""] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, 'gray') plt.title(titles[i]) plt.axis('off') plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
364
import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights SCREAMING_SNAKE_CASE = FlaxDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=a , cache_dir=a) SCREAMING_SNAKE_CASE = [t[-1] for t in os.walk(os.path.join(a , os.listdir(a)[0] , 'snapshots'))] SCREAMING_SNAKE_CASE = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith('.bin') for f in files) @slow @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 4 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 4.1_51_47_45) < 1E-3 assert np.abs(np.abs(a , dtype=np.floataa).sum() - 4_99_47.8_75) < 5E-1 SCREAMING_SNAKE_CASE = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]))) assert len(a) == num_samples def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='flax' , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.05_65_24_01)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_38_38_08.2)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_00_39_06)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_37_35_16.75)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_00_39_06)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_37_35_16.75)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = FlaxDDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , set_alpha_to_one=a , steps_offset=1 , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , scheduler=a , safety_checker=a , ) SCREAMING_SNAKE_CASE = scheduler.create_state() SCREAMING_SNAKE_CASE = scheduler_state SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.0_45_04_39_45)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_34_76_93.5)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = jax.random.split(jax.random.PRNGKey(0) , a) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a , ) SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) SCREAMING_SNAKE_CASE = images[2, 0, 256, 10:17, 1] # With memory efficient attention SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a , use_memory_efficient_attention=a , ) SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , jit=a).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) SCREAMING_SNAKE_CASE = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice).max() < 1E-2
327
0
import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor a_ : Dict = logging.get_logger(__name__) class _snake_case ( __lowerCAmelCase ): def __init__( self , *a , **a) -> None: warnings.warn( 'The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use CLIPImageProcessor instead.' , lowerCAmelCase_ , ) super().__init__(*lowerCAmelCase_ , **lowerCAmelCase_)
365
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets a_ : Tuple = '\\n@inproceedings{lin-2004-rouge,\n title = "{ROUGE}: A Package for Automatic Evaluation of Summaries",\n author = "Lin, Chin-Yew",\n booktitle = "Text Summarization Branches Out",\n month = jul,\n year = "2004",\n address = "Barcelona, Spain",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W04-1013",\n pages = "74--81",\n}\n' a_ : List[Any] = '\\nROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for\nevaluating automatic summarization and machine translation software in natural language processing.\nThe metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.\n\nNote that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.\n\nThis metrics is a wrapper around Google Research reimplementation of ROUGE:\nhttps://github.com/google-research/google-research/tree/master/rouge\n' a_ : List[str] = '\nCalculates average rouge scores for a list of hypotheses and 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 rouge_types: A list of rouge types to calculate.\n Valid names:\n `"rouge{n}"` (e.g. `"rouge1"`, `"rouge2"`) where: {n} is the n-gram based scoring,\n `"rougeL"`: Longest common subsequence based scoring.\n `"rougeLSum"`: rougeLsum splits text using `"\n"`.\n See details in https://github.com/huggingface/datasets/issues/617\n use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.\n use_aggregator: Return aggregates if this is set to True\nReturns:\n rouge1: rouge_1 (precision, recall, f1),\n rouge2: rouge_2 (precision, recall, f1),\n rougeL: rouge_l (precision, recall, f1),\n rougeLsum: rouge_lsum (precision, recall, f1)\nExamples:\n\n >>> rouge = datasets.load_metric(\'rouge\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> results = rouge.compute(predictions=predictions, references=references)\n >>> print(list(results.keys()))\n [\'rouge1\', \'rouge2\', \'rougeL\', \'rougeLsum\']\n >>> print(results["rouge1"])\n AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))\n >>> print(results["rouge1"].mid.fmeasure)\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence'), 'references': datasets.Value('string' , id='sequence'), }) , codebase_urls=['https://github.com/google-research/google-research/tree/master/rouge'] , reference_urls=[ 'https://en.wikipedia.org/wiki/ROUGE_(metric)', 'https://github.com/google-research/google-research/tree/master/rouge', ] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a=True , a=False) -> Optional[Any]: if rouge_types is None: SCREAMING_SNAKE_CASE = ['rouge1', 'rouge2', 'rougeL', 'rougeLsum'] SCREAMING_SNAKE_CASE = rouge_scorer.RougeScorer(rouge_types=a , use_stemmer=a) if use_aggregator: SCREAMING_SNAKE_CASE = scoring.BootstrapAggregator() else: SCREAMING_SNAKE_CASE = [] for ref, pred in zip(a , a): SCREAMING_SNAKE_CASE = scorer.score(a , a) if use_aggregator: aggregator.add_scores(a) else: scores.append(a) if use_aggregator: SCREAMING_SNAKE_CASE = aggregator.aggregate() else: SCREAMING_SNAKE_CASE = {} for key in scores[0]: SCREAMING_SNAKE_CASE = [score[key] for score in scores] return result
327
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer a_ : List[str] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a_ : str = { 'vocab_file': { 'google/electra-small-generator': ( 'https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt' ), 'google/electra-base-generator': 'https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt', 'google/electra-large-generator': ( 'https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt' ), 'google/electra-small-discriminator': ( 'https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt' ), 'google/electra-base-discriminator': ( 'https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt' ), 'google/electra-large-discriminator': ( 'https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'google/electra-small-generator': ( 'https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json' ), 'google/electra-base-generator': ( 'https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json' ), 'google/electra-large-generator': ( 'https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json' ), 'google/electra-small-discriminator': ( 'https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json' ), 'google/electra-base-discriminator': ( 'https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json' ), 'google/electra-large-discriminator': ( 'https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json' ), }, } a_ : Dict = { 'google/electra-small-generator': 5_12, 'google/electra-base-generator': 5_12, 'google/electra-large-generator': 5_12, 'google/electra-small-discriminator': 5_12, 'google/electra-base-discriminator': 5_12, 'google/electra-large-discriminator': 5_12, } a_ : Optional[Any] = { 'google/electra-small-generator': {'do_lower_case': True}, 'google/electra-base-generator': {'do_lower_case': True}, 'google/electra-large-generator': {'do_lower_case': True}, 'google/electra-small-discriminator': {'do_lower_case': True}, 'google/electra-base-discriminator': {'do_lower_case': True}, 'google/electra-large-discriminator': {'do_lower_case': True}, } class _snake_case ( _lowerCAmelCase ): _lowercase : Union[str, Any] = VOCAB_FILES_NAMES _lowercase : Dict = PRETRAINED_VOCAB_FILES_MAP _lowercase : List[Any] = PRETRAINED_INIT_CONFIGURATION _lowercase : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : Dict = ElectraTokenizer def __init__( self , a=None , a=None , a=True , a="[UNK]" , a="[SEP]" , a="[PAD]" , a="[CLS]" , a="[MASK]" , a=True , a=None , **a , ) -> Optional[int]: super().__init__( SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , do_lower_case=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) SCREAMING_SNAKE_CASE = json.loads(self.backend_tokenizer.normalizer.__getstate__()) if ( normalizer_state.get('lowercase' , SCREAMING_SNAKE_CASE_) != do_lower_case or normalizer_state.get('strip_accents' , SCREAMING_SNAKE_CASE_) != strip_accents or normalizer_state.get('handle_chinese_chars' , SCREAMING_SNAKE_CASE_) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE = getattr(SCREAMING_SNAKE_CASE_ , 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(**SCREAMING_SNAKE_CASE_) SCREAMING_SNAKE_CASE = do_lower_case def SCREAMING_SNAKE_CASE__ ( self , a , a=None) -> Optional[Any]: 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 SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: 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 SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> Tuple[str]: SCREAMING_SNAKE_CASE = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_) return tuple(SCREAMING_SNAKE_CASE_)
366
import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def lowerCamelCase__ (_UpperCAmelCase): if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class _snake_case ( nn.Module ): def __init__( self , a , a) -> Union[str, Any]: super().__init__() SCREAMING_SNAKE_CASE = module SCREAMING_SNAKE_CASE = nn.Sequential( nn.Linear(module.in_features , a , bias=a) , nn.Linear(a , module.out_features , bias=a) , ) SCREAMING_SNAKE_CASE = (2.0 / (5 * min(module.in_features , module.out_features))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=a) nn.init.zeros_(self.adapter[1].weight) self.adapter.to(module.weight.device) def SCREAMING_SNAKE_CASE__ ( self , a , *a , **a) -> Any: return self.module(a , *a , **a) + self.adapter(a) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): # We keep the constants inside the init function and model loading inside setUp function # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) # Therefore here we use only bloom-1b3 to test our module _lowercase : Union[str, Any] = '''bigscience/bloom-1b7''' # Constant values _lowercase : str = 2.109_6595_5269_2574 _lowercase : Any = '''Hello my name is''' _lowercase : Any = set() EXPECTED_OUTPUTS.add('''Hello my name is John and I am a professional photographer. I''' ) EXPECTED_OUTPUTS.add('''Hello my name is John.\nI am a friend of your father.\n''' ) EXPECTED_OUTPUTS.add('''Hello my name is John Doe, I am a student at the University''' ) _lowercase : Union[str, Any] = 10 def SCREAMING_SNAKE_CASE__ ( self) -> Any: # Models and tokenizer SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(self.model_name) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: super().setUp() # Models and tokenizer SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map='auto') SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_abit.config self.assertTrue(hasattr(a , 'quantization_config')) SCREAMING_SNAKE_CASE = config.to_dict() SCREAMING_SNAKE_CASE = config.to_diff_dict() SCREAMING_SNAKE_CASE = config.to_json_string() def SCREAMING_SNAKE_CASE__ ( self) -> Any: from bitsandbytes.nn import Paramsabit SCREAMING_SNAKE_CASE = self.model_fpaa.get_memory_footprint() SCREAMING_SNAKE_CASE = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE) SCREAMING_SNAKE_CASE = get_some_linear_layer(self.model_abit) self.assertTrue(linear.weight.__class__ == Paramsabit) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(a , torch.nn.Linear): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = self.model_abit.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = BitsAndBytesConfig() SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = model_abit_from_config.generate( input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) def SCREAMING_SNAKE_CASE__ ( self) -> str: with self.assertRaises(a), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = BitsAndBytesConfig() with self.assertRaises(a): SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=a , load_in_abit=a , device_map='auto' , bnb_abit_quant_type='nf4' , ) def SCREAMING_SNAKE_CASE__ ( self) -> int: with self.assertRaises(a): # Tries with `str` self.model_abit.to('cpu') with self.assertRaises(a): # Tries with a `dtype`` self.model_abit.to(torch.floataa) with self.assertRaises(a): # Tries with a `device` self.model_abit.to(torch.device('cuda:0')) with self.assertRaises(a): # Tries with a `device` self.model_abit.float() with self.assertRaises(a): # Tries with a `device` self.model_abit.half() # Test if we did not break anything SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = self.model_fpaa.to(torch.floataa) SCREAMING_SNAKE_CASE = self.model_fpaa.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.to('cpu') # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.half() # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.float() def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained('t5-small' , load_in_abit=a , device_map='auto') self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Tuple: SCREAMING_SNAKE_CASE = 't5-small' SCREAMING_SNAKE_CASE = 'google/flan-t5-small' # flan-t5 uses dense-act instead of dense-relu-dense SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(cls.model_name) SCREAMING_SNAKE_CASE = 'Translate in German: Hello, my dog is cute' def SCREAMING_SNAKE_CASE__ ( self) -> Dict: gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: from transformers import TaForConditionalGeneration SCREAMING_SNAKE_CASE = TaForConditionalGeneration._keep_in_fpaa_modules SCREAMING_SNAKE_CASE = None # test with `t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) # test with `flan-t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) SCREAMING_SNAKE_CASE = modules def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit)) SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) # test with `flan-t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> str: super().setUp() # model_name SCREAMING_SNAKE_CASE = 'bigscience/bloom-560m' SCREAMING_SNAKE_CASE = 't5-small' # Different types of model SCREAMING_SNAKE_CASE = AutoModel.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # Sequence classification model SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=a , device_map='auto') # CausalLM model SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # Seq2seq model SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=a , device_map='auto') def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Dict: del self.pipe gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = pipeline( 'text-generation' , model=self.model_name , model_kwargs={'device_map': 'auto', 'load_in_4bit': True, 'torch_dtype': torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass SCREAMING_SNAKE_CASE = self.pipe(self.input_text) self.assertIn(pipeline_output[0]['generated_text'] , self.EXPECTED_OUTPUTS) @require_torch_multi_gpu class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> int: super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=a , device_map='balanced') # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values()) , {0, 1}) # Check that inference pass works on the model SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') # Second real batch SCREAMING_SNAKE_CASE = model_parallel.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = 'facebook/opt-350m' super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Any: if version.parse(importlib.metadata.version('bitsandbytes')) < version.parse('0.37.0'): return # Step 1: freeze all parameters SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a) self.assertEqual(set(model.hf_device_map.values()) , {torch.cuda.current_device()}) for param in model.parameters(): SCREAMING_SNAKE_CASE = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability SCREAMING_SNAKE_CASE = param.data.to(torch.floataa) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(a)): SCREAMING_SNAKE_CASE = LoRALayer(module.q_proj , rank=16) SCREAMING_SNAKE_CASE = LoRALayer(module.k_proj , rank=16) SCREAMING_SNAKE_CASE = LoRALayer(module.v_proj , rank=16) # Step 3: dummy batch SCREAMING_SNAKE_CASE = self.tokenizer('Test batch ' , return_tensors='pt').to(0) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): SCREAMING_SNAKE_CASE = model.forward(**a) out.logits.norm().backward() for module in model.modules(): if isinstance(a , a): self.assertTrue(module.adapter[1].weight.grad is not None) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0) elif isinstance(a , nn.Embedding): self.assertTrue(module.weight.grad is None) class _snake_case ( A__ ): _lowercase : str = '''gpt2-xl''' _lowercase : Union[str, Any] = 3.3191_8548_5415_2187
327
0
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu a_ : List[str] = get_tests_dir() + '/test_data/fsmt/fsmt_val_data.json' with io.open(filename, 'r', encoding='utf-8') as f: a_ : List[Any] = json.load(f) @require_torch class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self , a) -> List[str]: return FSMTTokenizer.from_pretrained(UpperCamelCase__) def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = FSMTForConditionalGeneration.from_pretrained(UpperCamelCase__).to(UpperCamelCase__) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ['en-ru', 26.0], ['ru-en', 22.0], ['en-de', 22.0], ['de-en', 29.0], ]) @slow def SCREAMING_SNAKE_CASE__ ( self , a , a) -> str: SCREAMING_SNAKE_CASE = f'''facebook/wmt19-{pair}''' SCREAMING_SNAKE_CASE = self.get_tokenizer(UpperCamelCase__) SCREAMING_SNAKE_CASE = self.get_model(UpperCamelCase__) SCREAMING_SNAKE_CASE = bleu_data[pair]['''src'''] SCREAMING_SNAKE_CASE = bleu_data[pair]['''tgt'''] SCREAMING_SNAKE_CASE = tokenizer(UpperCamelCase__ , return_tensors='pt' , truncation=UpperCamelCase__ , padding='longest').to(UpperCamelCase__) SCREAMING_SNAKE_CASE = model.generate( input_ids=batch.input_ids , num_beams=8 , ) SCREAMING_SNAKE_CASE = tokenizer.batch_decode( UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ , clean_up_tokenization_spaces=UpperCamelCase__) SCREAMING_SNAKE_CASE = calculate_bleu(UpperCamelCase__ , UpperCamelCase__) print(UpperCamelCase__) self.assertGreaterEqual(scores['bleu'] , UpperCamelCase__)
367
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : Optional[Any] = { 'configuration_efficientnet': [ 'EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'EfficientNetConfig', 'EfficientNetOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[str] = ['EfficientNetImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = [ 'EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'EfficientNetForImageClassification', 'EfficientNetModel', 'EfficientNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure)
327
0
from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class _snake_case : _lowercase : List[str] _lowercase : Optional[str] = None # Automatically constructed _lowercase : ClassVar[str] = "dict" _lowercase : ClassVar[Any] = None _lowercase : str = field(default='''Translation''' , init=_a , repr=_a ) def __call__( self) -> Tuple: return pa.struct({lang: pa.string() for lang in sorted(self.languages)}) def SCREAMING_SNAKE_CASE__ ( self) -> Union["FeatureType", Dict[str, "FeatureType"]]: from .features import Value return {k: Value('string') for k in sorted(self.languages)} @dataclass class _snake_case : _lowercase : Optional[List] = None _lowercase : Optional[int] = None _lowercase : Optional[str] = None # Automatically constructed _lowercase : ClassVar[str] = "dict" _lowercase : ClassVar[Any] = None _lowercase : str = field(default='''TranslationVariableLanguages''' , init=_a , repr=_a ) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = sorted(set(self.languages)) if self.languages else None SCREAMING_SNAKE_CASE = len(self.languages) if self.languages else None def __call__( self) -> Optional[int]: return pa.struct({'language': pa.list_(pa.string()), 'translation': pa.list_(pa.string())}) def SCREAMING_SNAKE_CASE__ ( self , a) -> Tuple: SCREAMING_SNAKE_CASE = set(self.languages) if self.languages and set(a) - lang_set: raise ValueError( f'''Some languages in example ({', '.join(sorted(set(a) - lang_set))}) are not in valid set ({', '.join(a)}).''') # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. SCREAMING_SNAKE_CASE = [] for lang, text in translation_dict.items(): if isinstance(a , a): translation_tuples.append((lang, text)) else: translation_tuples.extend([(lang, el) for el in text]) # Ensure translations are in ascending order by language code. SCREAMING_SNAKE_CASE = zip(*sorted(a)) return {"language": languages, "translation": translations} def SCREAMING_SNAKE_CASE__ ( self) -> Union["FeatureType", Dict[str, "FeatureType"]]: from .features import Sequence, Value return { "language": Sequence(Value('string')), "translation": Sequence(Value('string')), }
368
import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) a_ : Dict = [ 'cross_validation.py', 'gradient_accumulation.py', 'local_sgd.py', 'multi_process_metrics.py', 'memory.py', 'automatic_gradient_accumulation.py', 'fsdp_with_peak_mem_tracking.py', 'deepspeed_with_config_support.py', 'megatron_lm_gpt_pretraining.py', ] class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , a = None) -> Optional[int]: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = os.path.abspath(os.path.join('examples' , 'by_feature')) SCREAMING_SNAKE_CASE = os.path.abspath('examples') for item in os.listdir(a): if item not in EXCLUDE_EXAMPLES: SCREAMING_SNAKE_CASE = os.path.join(a , a) if os.path.isfile(a) and ".py" in item_path: with self.subTest( tested_script=a , feature_script=a , tested_section='main()' if parser_only else 'training_function()' , ): SCREAMING_SNAKE_CASE = compare_against_test( os.path.join(a , a) , a , a , a) SCREAMING_SNAKE_CASE = '\n'.join(a) if special_strings is not None: for string in special_strings: SCREAMING_SNAKE_CASE = diff.replace(a , '') self.assertEqual(a , '') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: self.one_complete_example('complete_nlp_example.py' , a) self.one_complete_example('complete_nlp_example.py' , a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = os.path.abspath(os.path.join('examples' , 'cv_example.py')) SCREAMING_SNAKE_CASE = [ ' ' * 16 + '{\n\n', ' ' * 20 + '"accuracy": eval_metric["accuracy"],\n\n', ' ' * 20 + '"f1": eval_metric["f1"],\n\n', ' ' * 20 + '"train_loss": total_loss.item() / len(train_dataloader),\n\n', ' ' * 20 + '"epoch": epoch,\n\n', ' ' * 16 + '},\n\n', ' ' * 16 + 'step=epoch,\n', ' ' * 12, ' ' * 8 + 'for step, batch in enumerate(active_dataloader):\n', ] self.one_complete_example('complete_cv_example.py' , a , a , a) self.one_complete_example('complete_cv_example.py' , a , a , a) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class _snake_case ( A__ ): _lowercase : int = False @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Union[str, Any]: super().setUpClass() SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = os.path.join(cls._tmpdir , 'default_config.yml') write_basic_config(save_location=cls.configPath) SCREAMING_SNAKE_CASE = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Dict: super().tearDownClass() shutil.rmtree(cls._tmpdir) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'epoch_0'))) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'step_2'))) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0')} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) self.assertNotIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2')} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) if torch.cuda.is_available(): SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: SCREAMING_SNAKE_CASE = 1 if num_processes > 1: self.assertNotIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) else: self.assertIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = '\n examples/by_feature/cross_validation.py\n --num_folds 2\n '.split() with mock.patch.dict(os.environ , {'TESTING_MOCKED_DATALOADERS': '0'}): SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) SCREAMING_SNAKE_CASE = re.findall('({.+})' , a) SCREAMING_SNAKE_CASE = [r for r in results if 'accuracy' in r][-1] SCREAMING_SNAKE_CASE = ast.literal_eval(a) self.assertGreaterEqual(results['accuracy'] , 0.75) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ['examples/by_feature/multi_process_metrics.py'] run_command(self._launch_args + testargs) @require_trackers @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'}) def SCREAMING_SNAKE_CASE__ ( self) -> Any: with tempfile.TemporaryDirectory() as tmpdir: SCREAMING_SNAKE_CASE = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(a , 'tracking'))) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = ['examples/by_feature/gradient_accumulation.py'] run_command(self._launch_args + testargs) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = ['examples/by_feature/local_sgd.py'] run_command(self._launch_args + testargs)
327
0
from typing import List from .keymap import KEYMAP, get_character def lowerCamelCase__ (_UpperCAmelCase): def decorator(_UpperCAmelCase): SCREAMING_SNAKE_CASE = getattr(__UpperCamelCase , 'handle_key' , []) handle += [key] setattr(__UpperCamelCase , 'handle_key' , __UpperCamelCase) return func return decorator def lowerCamelCase__ (*_UpperCAmelCase): def decorator(_UpperCAmelCase): SCREAMING_SNAKE_CASE = getattr(__UpperCamelCase , 'handle_key' , []) handle += keys setattr(__UpperCamelCase , 'handle_key' , __UpperCamelCase) return func return decorator class _snake_case ( __a ): def __new__( cls , a , a , a) -> int: SCREAMING_SNAKE_CASE = super().__new__(cls , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__) if not hasattr(UpperCamelCase__ , 'key_handler'): setattr(UpperCamelCase__ , 'key_handler' , {}) setattr(UpperCamelCase__ , 'handle_input' , KeyHandler.handle_input) for value in attrs.values(): SCREAMING_SNAKE_CASE = getattr(UpperCamelCase__ , 'handle_key' , []) for key in handled_keys: SCREAMING_SNAKE_CASE = value return new_cls @staticmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Dict: SCREAMING_SNAKE_CASE = get_character() if char != KEYMAP["undefined"]: SCREAMING_SNAKE_CASE = ord(UpperCamelCase__) SCREAMING_SNAKE_CASE = cls.key_handler.get(UpperCamelCase__) if handler: SCREAMING_SNAKE_CASE = char return handler(cls) else: return None def lowerCamelCase__ (cls): return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy())
369
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _snake_case : def __init__( self , a , a=3 , a=32 , a=3 , a=10 , a=[10, 20, 30, 40] , a=[1, 1, 2, 1] , a=True , a=True , a="relu" , a=3 , a=None , ) -> Union[str, Any]: 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 SCREAMING_SNAKE_CASE__ ( self) -> List[str]: 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 SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return ResNetConfig( 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 , image_size=self.image_size , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Any: SCREAMING_SNAKE_CASE = TFResNetModel(config=a) 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 SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> int: SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = TFResNetForImageClassification(a) SCREAMING_SNAKE_CASE = model(a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: 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_tf class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () _lowercase : Dict = ( {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification} if is_tf_available() else {} ) _lowercase : Union[str, Any] = False _lowercase : Any = False _lowercase : List[str] = False _lowercase : str = False _lowercase : int = False def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = TFResNetModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , has_text_modality=a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return @unittest.skip(reason='ResNet does not use inputs_embeds') def SCREAMING_SNAKE_CASE__ ( self) -> int: pass @unittest.skip(reason='ResNet does not support input and output embeddings') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: pass def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: 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.call) # 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 SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: def check_hidden_states_output(a , a , a): SCREAMING_SNAKE_CASE = model_class(a) 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) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 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 SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> str: for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = TFResNetModel.from_pretrained(a) self.assertIsNotNone(a) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') return image @require_tf @require_vision class _snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = image_processor(images=a , return_tensors='tf') # forward pass SCREAMING_SNAKE_CASE = model(**a) # verify the logits SCREAMING_SNAKE_CASE = tf.TensorShape((1, 1000)) self.assertEqual(outputs.logits.shape , a) SCREAMING_SNAKE_CASE = tf.constant([-11.10_69, -9.78_77, -8.37_77]) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , a , atol=1E-4))
327
0
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ : Dict = { 'configuration_mctct': ['MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MCTCTConfig'], 'feature_extraction_mctct': ['MCTCTFeatureExtractor'], 'processing_mctct': ['MCTCTProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MCTCTForCTC', 'MCTCTModel', 'MCTCTPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig from .feature_extraction_mctct import MCTCTFeatureExtractor from .processing_mctct import MCTCTProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel else: import sys a_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
370
from math import isqrt def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [True] * max_number for i in range(2 , isqrt(max_number - 1) + 1): if is_prime[i]: for j in range(i**2 , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = False return [i for i in range(2 , _UpperCAmelCase) if is_prime[i]] def lowerCamelCase__ (_UpperCAmelCase = 10**8): SCREAMING_SNAKE_CASE = calculate_prime_numbers(max_number // 2) SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(f"""{solution() = }""")
327
0
def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = False): if n == 2: return True if not n % 2 or n < 2: return False if n > 5 and n % 10 not in (1, 3, 7, 9): # can quickly check last digit return False if n > 3_3170_4406_4679_8873_8596_1981 and not allow_probable: raise ValueError( 'Warning: upper bound of deterministic test is exceeded. ' 'Pass allow_probable=True to allow probabilistic test. ' 'A return value of True indicates a probable prime.') # array bounds provided by analysis SCREAMING_SNAKE_CASE = [ 2047, 137_3653, 2532_6001, 32_1503_1751, 2_1523_0289_8747, 3_4747_4966_0383, 341_5500_7172_8321, 1, 382_5123_0565_4641_3051, 1, 1, 3186_6585_7834_0311_5116_7461, 3_3170_4406_4679_8873_8596_1981, ] SCREAMING_SNAKE_CASE = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41] for idx, _p in enumerate(a__ , 1): if n < _p: # then we have our last prime to check SCREAMING_SNAKE_CASE = primes[:idx] break SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = n - 1, 0 # break up n -1 into a power of 2 (s) and # remaining odd component # essentially, solve for d * 2 ** s == n - 1 while d % 2 == 0: d //= 2 s += 1 for prime in plist: SCREAMING_SNAKE_CASE = False for r in range(a__): SCREAMING_SNAKE_CASE = pow(a__ , d * 2**r , a__) # see article for analysis explanation for m if (r == 0 and m == 1) or ((m + 1) % n == 0): SCREAMING_SNAKE_CASE = True # this loop will not determine compositeness break if pr: continue # if pr is False, then the above loop never evaluated to true, # and the n MUST be composite return False return True def lowerCamelCase__ (): assert not miller_rabin(561) assert miller_rabin(563) # 2047 assert not miller_rabin(83_8201) assert miller_rabin(83_8207) # 1_373_653 assert not miller_rabin(1731_6001) assert miller_rabin(1731_6017) # 25_326_001 assert not miller_rabin(30_7838_6641) assert miller_rabin(30_7838_6653) # 3_215_031_751 assert not miller_rabin(1_7130_4557_4801) assert miller_rabin(1_7130_4557_4819) # 2_152_302_898_747 assert not miller_rabin(2_7797_9972_8307) assert miller_rabin(2_7797_9972_8327) # 3_474_749_660_383 assert not miller_rabin(113_8500_2390_9441) assert miller_rabin(113_8500_2390_9527) # 341_550_071_728_321 assert not miller_rabin(127_5041_0188_4880_4351) assert miller_rabin(127_5041_0188_4880_4391) # 3_825_123_056_546_413_051 assert not miller_rabin(796_6646_4458_5077_8779_1867) assert miller_rabin(796_6646_4458_5077_8779_1951) # 318_665_857_834_031_151_167_461 assert not miller_rabin(5528_4067_7446_6478_9766_0333) assert miller_rabin(5528_4067_7446_6478_9766_0359) # 3_317_044_064_679_887_385_961_981 # upper limit for probabilistic test if __name__ == "__main__": test_miller_rabin()
371
import baseaa def lowerCamelCase__ (_UpperCAmelCase): return baseaa.aaaencode(string.encode('utf-8')) def lowerCamelCase__ (_UpperCAmelCase): return baseaa.aaadecode(_UpperCAmelCase).decode('utf-8') if __name__ == "__main__": import doctest doctest.testmod()
327
0
import unittest from dataclasses import dataclass import pytest from accelerate.commands.config.config_args import SageMakerConfig from accelerate.utils import ComputeEnvironment from accelerate.utils.launch import _convert_nargs_to_dict @dataclass class _snake_case ( snake_case_ ): _lowercase : Union[str, Any] = ComputeEnvironment.AMAZON_SAGEMAKER _lowercase : List[Any] = True _lowercase : Dict = "ml.p3.2xlarge" _lowercase : Dict = "accelerate_sagemaker_execution_role" _lowercase : Union[str, Any] = "hf-sm" _lowercase : str = "us-east-1" _lowercase : Optional[Any] = 1 _lowercase : Any = "accelerate-sagemaker-1" _lowercase : str = "1.6" _lowercase : List[str] = "4.4" _lowercase : Optional[Any] = "train.py" _lowercase : Any = [ "--model_name_or_path", "bert", "--do_train", "False", "--epochs", "3", "--learning_rate", "5e-5", "--max_steps", "50.5", ] _lowercase : List[str] = [ "--model_name_or_path", "bert", "--do_train", "--do_test", "False", "--do_predict", "--epochs", "3", "--learning_rate", "5e-5", "--max_steps", "50.5", ] class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = _convert_nargs_to_dict(MockLaunchConfig.success_training_script_args) assert isinstance(converted_args['model_name_or_path'] , _A) assert isinstance(converted_args['do_train'] , _A) assert isinstance(converted_args['epochs'] , _A) assert isinstance(converted_args['learning_rate'] , _A) assert isinstance(converted_args['max_steps'] , _A) with pytest.raises(_A): _convert_nargs_to_dict(MockLaunchConfig.fail_training_script_args)
350
import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(_UpperCAmelCase , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = emb.weight.shape SCREAMING_SNAKE_CASE = nn.Linear(_UpperCAmelCase , _UpperCAmelCase , bias=_UpperCAmelCase) SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = mam_aaa['args'] or mam_aaa['cfg']['model'] SCREAMING_SNAKE_CASE = mam_aaa['model'] remove_ignore_keys_(_UpperCAmelCase) SCREAMING_SNAKE_CASE = state_dict['encoder.embed_tokens.weight'].shape[0] SCREAMING_SNAKE_CASE = MaMaaaConfig( vocab_size=_UpperCAmelCase , max_position_embeddings=1024 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='relu' , ) SCREAMING_SNAKE_CASE = state_dict['decoder.embed_tokens.weight'] SCREAMING_SNAKE_CASE = MaMaaaForConditionalGeneration(_UpperCAmelCase) model.model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase) SCREAMING_SNAKE_CASE = make_linear_from_emb(model.model.shared) return model if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') a_ : List[str] = parser.parse_args() a_ : Dict = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
327
0
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : List[str] = logging.get_logger(__name__) a_ : str = { "s-JoL/Open-Llama-V1": "https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json", } class _snake_case ( _SCREAMING_SNAKE_CASE ): _lowercase : Any = '''open-llama''' def __init__( self , a=10_0000 , a=4096 , a=1_1008 , a=32 , a=32 , a="silu" , a=2048 , a=0.02 , a=1E-6 , a=True , a=0 , a=1 , a=2 , a=False , a=True , a=0.1 , a=0.1 , a=True , a=True , a=None , **a , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = rms_norm_eps SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = kwargs.pop( 'use_memorry_efficient_attention' , a) SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_dropout_prob SCREAMING_SNAKE_CASE = use_stable_embedding SCREAMING_SNAKE_CASE = shared_input_output_embedding SCREAMING_SNAKE_CASE = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=a , bos_token_id=a , eos_token_id=a , tie_word_embeddings=a , **a , ) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , a) or len(self.rope_scaling) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' f'''got {self.rope_scaling}''') SCREAMING_SNAKE_CASE = self.rope_scaling.get('type' , a) SCREAMING_SNAKE_CASE = self.rope_scaling.get('factor' , a) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''') if rope_scaling_factor is None or not isinstance(a , a) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''')
351
import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = 'laion/clap-htsat-unfused' SCREAMING_SNAKE_CASE = tempfile.mkdtemp() def SCREAMING_SNAKE_CASE__ ( self , **a) -> Optional[Any]: return RobertaTokenizer.from_pretrained(self.checkpoint , **a) def SCREAMING_SNAKE_CASE__ ( self , **a) -> Union[str, Any]: return ClapFeatureExtractor.from_pretrained(self.checkpoint , **a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = ClapProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) self.assertIsInstance(processor.tokenizer , a) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor()) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)') SCREAMING_SNAKE_CASE = self.get_feature_extractor(do_normalize=a , padding_value=1.0) SCREAMING_SNAKE_CASE = ClapProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=a , padding_value=1.0) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) self.assertIsInstance(processor.tokenizer , a) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = floats_list((3, 1000)) SCREAMING_SNAKE_CASE = feature_extractor(a , return_tensors='np') SCREAMING_SNAKE_CASE = processor(audios=a , return_tensors='np') for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = 'This is a test string' SCREAMING_SNAKE_CASE = processor(text=a) SCREAMING_SNAKE_CASE = tokenizer(a) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE = processor.batch_decode(a) SCREAMING_SNAKE_CASE = tokenizer.batch_decode(a) self.assertListEqual(a , a) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , )
327
0
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. a_ : Optional[Any] = 2_00 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. a_ : str = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. a_ : List[str] = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 10_00)) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = len([g for position, g in enumerate(lowerCAmelCase__) if g == main_target[position]]) return (item, float(lowerCAmelCase__)) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = random.randint(0 , len(lowerCAmelCase__) - 1) SCREAMING_SNAKE_CASE = parent_a[:random_slice] + parent_a[random_slice:] SCREAMING_SNAKE_CASE = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = list(lowerCAmelCase__) if random.uniform(0 , 1) < MUTATION_PROBABILITY: SCREAMING_SNAKE_CASE = random.choice(lowerCAmelCase__) return "".join(lowerCAmelCase__) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ): SCREAMING_SNAKE_CASE = [] # Generate more children proportionally to the fitness score. SCREAMING_SNAKE_CASE = int(parent_a[1] * 100) + 1 SCREAMING_SNAKE_CASE = 10 if child_n >= 10 else child_n for _ in range(lowerCAmelCase__): SCREAMING_SNAKE_CASE = population_score[random.randint(0 , lowerCAmelCase__)][0] SCREAMING_SNAKE_CASE = crossover(parent_a[0] , lowerCAmelCase__) # Append new string to the population list. pop.append(mutate(lowerCAmelCase__ , lowerCAmelCase__)) pop.append(mutate(lowerCAmelCase__ , lowerCAmelCase__)) return pop def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = True): # Verify if N_POPULATION is bigger than N_SELECTED if N_POPULATION < N_SELECTED: SCREAMING_SNAKE_CASE = F'''{N_POPULATION} must be bigger than {N_SELECTED}''' raise ValueError(lowerCAmelCase__) # Verify that the target contains no genes besides the ones inside genes variable. SCREAMING_SNAKE_CASE = sorted({c for c in target if c not in genes}) if not_in_genes_list: SCREAMING_SNAKE_CASE = F'''{not_in_genes_list} is not in genes list, evolution cannot converge''' raise ValueError(lowerCAmelCase__) # Generate random starting population. SCREAMING_SNAKE_CASE = [] for _ in range(lowerCAmelCase__): population.append(''.join([random.choice(lowerCAmelCase__) for i in range(len(lowerCAmelCase__))])) # Just some logs to know what the algorithms is doing. SCREAMING_SNAKE_CASE = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(lowerCAmelCase__) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. SCREAMING_SNAKE_CASE = [evaluate(lowerCAmelCase__ , lowerCAmelCase__) for item in population] # Check if there is a matching evolution. SCREAMING_SNAKE_CASE = sorted(lowerCAmelCase__ , key=lambda _UpperCAmelCase: x[1] , reverse=lowerCAmelCase__) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F'''\nGeneration: {generation}''' F'''\nTotal Population:{total_population}''' F'''\nBest score: {population_score[0][1]}''' F'''\nBest string: {population_score[0][0]}''') # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. SCREAMING_SNAKE_CASE = population[: int(N_POPULATION / 3)] population.clear() population.extend(lowerCAmelCase__) # Normalize population score to be between 0 and 1. SCREAMING_SNAKE_CASE = [ (item, score / len(lowerCAmelCase__)) for item, score in population_score ] # This is selection for i in range(lowerCAmelCase__): population.extend(select(population_score[int(lowerCAmelCase__)] , lowerCAmelCase__ , lowerCAmelCase__)) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(lowerCAmelCase__) > N_POPULATION: break if __name__ == "__main__": a_ : Optional[int] = ( 'This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!' ) a_ : Union[str, Any] = list( ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm' 'nopqrstuvwxyz.,;!?+-*#@^\'èéòà€ù=)(&%$£/\\' ) a_ , a_ , a_ : int = basic(target_str, genes_list) print( f"""\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}""" )
352
import argparse import datetime def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = { '0': 'Sunday', '1': 'Monday', '2': 'Tuesday', '3': 'Wednesday', '4': 'Thursday', '5': 'Friday', '6': 'Saturday', } SCREAMING_SNAKE_CASE = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(_UpperCAmelCase) < 11: raise ValueError('Must be 10 characters long') # Get month SCREAMING_SNAKE_CASE = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 13: raise ValueError('Month must be between 1 - 12') SCREAMING_SNAKE_CASE = date_input[2] # Validate if sep_a not in ["-", "/"]: raise ValueError('Date separator must be \'-\' or \'/\'') # Get day SCREAMING_SNAKE_CASE = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 32: raise ValueError('Date must be between 1 - 31') # Get second separator SCREAMING_SNAKE_CASE = date_input[5] # Validate if sep_a not in ["-", "/"]: raise ValueError('Date separator must be \'-\' or \'/\'') # Get year SCREAMING_SNAKE_CASE = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 45 < y < 8500: raise ValueError( 'Year out of range. There has to be some sort of limit...right?') # Get datetime obj for validation SCREAMING_SNAKE_CASE = datetime.date(int(_UpperCAmelCase) , int(_UpperCAmelCase) , int(_UpperCAmelCase)) # Start math if m <= 2: SCREAMING_SNAKE_CASE = y - 1 SCREAMING_SNAKE_CASE = m + 12 # maths var SCREAMING_SNAKE_CASE = int(str(_UpperCAmelCase)[:2]) SCREAMING_SNAKE_CASE = int(str(_UpperCAmelCase)[2:]) SCREAMING_SNAKE_CASE = int(2.6 * m - 5.39) SCREAMING_SNAKE_CASE = int(c / 4) SCREAMING_SNAKE_CASE = int(k / 4) SCREAMING_SNAKE_CASE = int(d + k) SCREAMING_SNAKE_CASE = int(t + u + v + x) SCREAMING_SNAKE_CASE = int(z - (2 * c)) SCREAMING_SNAKE_CASE = round(w % 7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError('The date was evaluated incorrectly. Contact developer.') # Response SCREAMING_SNAKE_CASE = F'''Your date {date_input}, is a {days[str(_UpperCAmelCase)]}!''' return response if __name__ == "__main__": import doctest doctest.testmod() a_ : Tuple = argparse.ArgumentParser( description=( 'Find out what day of the week nearly any date is or was. Enter ' 'date as a string in the mm-dd-yyyy or mm/dd/yyyy format' ) ) parser.add_argument( 'date_input', type=str, help='Date as a string (mm-dd-yyyy or mm/dd/yyyy)' ) a_ : Any = parser.parse_args() zeller(args.date_input)
327
0
"""simple docstring""" import inspect import unittest import numpy as np from transformers import ViTConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel class _snake_case ( unittest.TestCase ): def __init__( self , a , a=13 , a=30 , a=2 , a=3 , a=True , a=True , a=32 , a=5 , a=4 , a=37 , a="gelu" , a=0.1 , a=0.1 , a=10 , a=0.02 , ) -> Dict: SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_labels 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 = type_sequence_label_size SCREAMING_SNAKE_CASE = initializer_range # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE = num_patches + 1 def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE = ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=a , initializer_range=self.initializer_range , ) return config, pixel_values def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Dict: SCREAMING_SNAKE_CASE = FlaxViTModel(config=a) SCREAMING_SNAKE_CASE = model(a) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE = (self.patch_size, self.patch_size) SCREAMING_SNAKE_CASE = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, num_patches + 1, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a) -> str: SCREAMING_SNAKE_CASE = self.type_sequence_label_size SCREAMING_SNAKE_CASE = FlaxViTForImageClassification(config=a) SCREAMING_SNAKE_CASE = model(a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) # test greyscale images SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = FlaxViTForImageClassification(a) SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE = model(a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) = config_and_inputs SCREAMING_SNAKE_CASE = {'pixel_values': pixel_values} return config, inputs_dict @require_flax class _snake_case ( A__ , unittest.TestCase ): _lowercase : Any = (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else () def SCREAMING_SNAKE_CASE__ ( self) -> None: SCREAMING_SNAKE_CASE = FlaxViTModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , has_text_modality=a , hidden_size=37) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a) def SCREAMING_SNAKE_CASE__ ( self) -> Any: 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.__call__) # 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 SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__): SCREAMING_SNAKE_CASE = self._prepare_for_class(a , a) SCREAMING_SNAKE_CASE = model_class(a) @jax.jit def model_jitted(a , **a): return model(pixel_values=a , **a) with self.subTest('JIT Enabled'): SCREAMING_SNAKE_CASE = model_jitted(**a).to_tuple() with self.subTest('JIT Disabled'): with jax.disable_jit(): SCREAMING_SNAKE_CASE = model_jitted(**a).to_tuple() self.assertEqual(len(a) , len(a)) for jitted_output, output in zip(a , a): self.assertEqual(jitted_output.shape , output.shape) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Any: for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE = model_class_name.from_pretrained('google/vit-base-patch16-224') SCREAMING_SNAKE_CASE = model(np.ones((1, 3, 224, 224))) self.assertIsNotNone(a)
353
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 convert_to_rgb, 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 if is_vision_available(): import PIL a_ : Optional[Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : Optional[int] = ['''pixel_values'''] def __init__( self , a = True , a = None , a = PILImageResampling.BICUBIC , a = True , a = 1 / 255 , a = True , a = None , a = None , a = True , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = size if size is not None else {'height': 384, 'width': 384} SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) SCREAMING_SNAKE_CASE = do_resize SCREAMING_SNAKE_CASE = size SCREAMING_SNAKE_CASE = resample 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 SCREAMING_SNAKE_CASE__ ( self , a , a , a = PILImageResampling.BICUBIC , a = None , **a , ) -> np.ndarray: SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}''') SCREAMING_SNAKE_CASE = (size['height'], size['width']) return resize(a , size=a , resample=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a , ) -> Optional[Any]: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a = None , **a , ) -> np.ndarray: return normalize(a , mean=a , std=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> PIL.Image.Image: SCREAMING_SNAKE_CASE = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE = resample if resample is not None else self.resample 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 = size if size is not None else self.size SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) 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 or resample is None: raise ValueError('Size and resample must be specified if do_resize 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_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 = BatchFeature(data={'pixel_values': images} , tensor_type=a) return encoded_outputs
327
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Optional[int] = logging.get_logger(__name__) a_ : Optional[int] = { "BAAI/AltCLIP": "https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json", # See all AltCLIP models at https://huggingface.co/models?filter=altclip } class _snake_case ( lowercase_ ): _lowercase : List[Any] = "altclip_text_model" def __init__( self , a=25_0002 , a=1024 , a=24 , a=16 , a=4096 , a="gelu" , a=0.1 , a=0.1 , a=514 , a=1 , a=0.02 , a=0.02 , a=1E-05 , a=1 , a=0 , a=2 , a="absolute" , a=True , a=768 , **a , ) -> Tuple: super().__init__(pad_token_id=a__ , bos_token_id=a__ , eos_token_id=a__ , **a__) 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 = 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 = initializer_factor SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = position_embedding_type SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = project_dim class _snake_case ( lowercase_ ): _lowercase : Tuple = "altclip_vision_model" def __init__( self , a=768 , a=3072 , a=512 , a=12 , a=12 , a=3 , a=224 , a=32 , a="quick_gelu" , a=1E-5 , a=0.0 , a=0.02 , a=1.0 , **a , ) -> List[Any]: super().__init__(**a__) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = projection_dim SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = initializer_factor SCREAMING_SNAKE_CASE = attention_dropout SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = hidden_act @classmethod def SCREAMING_SNAKE_CASE__ ( cls , a , **a) -> "PretrainedConfig": 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 AltCLIPConfig if config_dict.get('model_type') == "altclip": 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 _snake_case ( lowercase_ ): _lowercase : Union[str, Any] = "altclip" _lowercase : Tuple = True def __init__( self , a=None , a=None , a=768 , a=2.65_92 , **a) -> Tuple: SCREAMING_SNAKE_CASE = kwargs.pop('text_config_dict' , a__) SCREAMING_SNAKE_CASE = kwargs.pop('vision_config_dict' , a__) super().__init__(**a__) # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`. if text_config_dict is not None: if text_config is None: SCREAMING_SNAKE_CASE = {} # This is the complete result when using `text_config_dict`. SCREAMING_SNAKE_CASE = AltCLIPTextConfig(**a__).to_dict() # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different. for key, value in _text_config_dict.items(): if key in text_config and value != text_config[key] and key not in ["transformers_version"]: # If specified in `text_config_dict` if key in text_config_dict: SCREAMING_SNAKE_CASE = ( f'''`{key}` is found in both `text_config_dict` and `text_config` but with different values. ''' f'''The value `text_config_dict["{key}"]` will be used instead.''' ) # If inferred from default argument values (just to be super careful) else: SCREAMING_SNAKE_CASE = ( f'''`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The ''' f'''value `text_config["{key}"]` will be overriden.''' ) logger.warning(a__) # Update all values in `text_config` with the ones in `_text_config_dict`. text_config.update(_text_config_dict) if vision_config_dict is not None: if vision_config is None: SCREAMING_SNAKE_CASE = {} # This is the complete result when using `vision_config_dict`. SCREAMING_SNAKE_CASE = AltCLIPVisionConfig(**a__).to_dict() # convert keys to string instead of integer if "id2label" in _vision_config_dict: SCREAMING_SNAKE_CASE = { str(a__): value for key, value in _vision_config_dict['id2label'].items() } # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different. for key, value in _vision_config_dict.items(): if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]: # If specified in `vision_config_dict` if key in vision_config_dict: SCREAMING_SNAKE_CASE = ( f'''`{key}` is found in both `vision_config_dict` and `vision_config` but with different ''' f'''values. The value `vision_config_dict["{key}"]` will be used instead.''' ) # If inferred from default argument values (just to be super careful) else: SCREAMING_SNAKE_CASE = ( f'''`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. ''' f'''The value `vision_config["{key}"]` will be overriden.''' ) logger.warning(a__) # Update all values in `vision_config` with the ones in `_vision_config_dict`. vision_config.update(_vision_config_dict) if text_config is None: SCREAMING_SNAKE_CASE = {} logger.info('`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.') if vision_config is None: SCREAMING_SNAKE_CASE = {} logger.info('`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.') SCREAMING_SNAKE_CASE = AltCLIPTextConfig(**a__) SCREAMING_SNAKE_CASE = AltCLIPVisionConfig(**a__) SCREAMING_SNAKE_CASE = projection_dim SCREAMING_SNAKE_CASE = logit_scale_init_value SCREAMING_SNAKE_CASE = 1.0 @classmethod def SCREAMING_SNAKE_CASE__ ( cls , a , a , **a) -> Optional[Any]: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **a__) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: 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
354
class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = val SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None def SCREAMING_SNAKE_CASE__ ( self , a) -> str: if self.val: if val < self.val: if self.left is None: SCREAMING_SNAKE_CASE = Node(a) else: self.left.insert(a) elif val > self.val: if self.right is None: SCREAMING_SNAKE_CASE = Node(a) else: self.right.insert(a) else: SCREAMING_SNAKE_CASE = val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Recursive traversal if root: inorder(root.left , _UpperCAmelCase) res.append(root.val) inorder(root.right , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): # Build BST if len(_UpperCAmelCase) == 0: return arr SCREAMING_SNAKE_CASE = Node(arr[0]) for i in range(1 , len(_UpperCAmelCase)): root.insert(arr[i]) # Traverse BST in order. SCREAMING_SNAKE_CASE = [] inorder(_UpperCAmelCase , _UpperCAmelCase) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
327
0
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridConfig, ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel, ) from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() a_ : Union[str, Any] = logging.get_logger(__name__) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=False): """simple docstring""" SCREAMING_SNAKE_CASE = [] # fmt: off # stem: rename_keys.append(('cls_token', 'vit.embeddings.cls_token')) rename_keys.append(('pos_embed', 'vit.embeddings.position_embeddings')) rename_keys.append(('patch_embed.proj.weight', 'vit.embeddings.patch_embeddings.projection.weight')) rename_keys.append(('patch_embed.proj.bias', 'vit.embeddings.patch_embeddings.projection.bias')) # backbone rename_keys.append(('patch_embed.backbone.stem.conv.weight', 'vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight')) rename_keys.append(('patch_embed.backbone.stem.norm.weight', 'vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight')) rename_keys.append(('patch_embed.backbone.stem.norm.bias', 'vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias')) for stage_idx in range(len(config.backbone_config.depths)): for layer_idx in range(config.backbone_config.depths[stage_idx]): rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight''')) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight''')) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias''')) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight''')) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight''')) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias''')) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight''')) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight''')) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias''')) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight''')) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight''')) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias''')) # transformer encoder for i in range(config.num_hidden_layers): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'''blocks.{i}.norm1.weight''', F'''vit.encoder.layer.{i}.layernorm_before.weight''')) rename_keys.append((F'''blocks.{i}.norm1.bias''', F'''vit.encoder.layer.{i}.layernorm_before.bias''')) rename_keys.append((F'''blocks.{i}.attn.proj.weight''', F'''vit.encoder.layer.{i}.attention.output.dense.weight''')) rename_keys.append((F'''blocks.{i}.attn.proj.bias''', F'''vit.encoder.layer.{i}.attention.output.dense.bias''')) rename_keys.append((F'''blocks.{i}.norm2.weight''', F'''vit.encoder.layer.{i}.layernorm_after.weight''')) rename_keys.append((F'''blocks.{i}.norm2.bias''', F'''vit.encoder.layer.{i}.layernorm_after.bias''')) rename_keys.append((F'''blocks.{i}.mlp.fc1.weight''', F'''vit.encoder.layer.{i}.intermediate.dense.weight''')) rename_keys.append((F'''blocks.{i}.mlp.fc1.bias''', F'''vit.encoder.layer.{i}.intermediate.dense.bias''')) rename_keys.append((F'''blocks.{i}.mlp.fc2.weight''', F'''vit.encoder.layer.{i}.output.dense.weight''')) rename_keys.append((F'''blocks.{i}.mlp.fc2.bias''', F'''vit.encoder.layer.{i}.output.dense.bias''')) if base_model: # layernorm + pooler rename_keys.extend( [ ('norm.weight', 'layernorm.weight'), ('norm.bias', 'layernorm.bias'), ('pre_logits.fc.weight', 'pooler.dense.weight'), ('pre_logits.fc.bias', 'pooler.dense.bias'), ]) # if just the base model, we should remove "vit" from all keys that start with "vit" SCREAMING_SNAKE_CASE = [(pair[0], pair[1][4:]) if pair[1].startswith('vit') else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ('norm.weight', 'vit.layernorm.weight'), ('norm.bias', 'vit.layernorm.bias'), ('head.weight', 'classifier.weight'), ('head.bias', 'classifier.bias'), ]) # fmt: on return rename_keys def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=False): """simple docstring""" for i in range(config.num_hidden_layers): if base_model: SCREAMING_SNAKE_CASE = '' else: SCREAMING_SNAKE_CASE = 'vit.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE = state_dict.pop(F'''blocks.{i}.attn.qkv.weight''') SCREAMING_SNAKE_CASE = state_dict.pop(F'''blocks.{i}.attn.qkv.bias''') # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE = in_proj_bias[-config.hidden_size :] def lowerCamelCase__ (_UpperCAmelCase): """simple docstring""" SCREAMING_SNAKE_CASE = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(_UpperCAmelCase , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): """simple docstring""" SCREAMING_SNAKE_CASE = dct.pop(_UpperCAmelCase) SCREAMING_SNAKE_CASE = val def lowerCamelCase__ (): """simple docstring""" SCREAMING_SNAKE_CASE = 'http://images.cocodataset.org/val2017/000000039769.jpg' SCREAMING_SNAKE_CASE = Image.open(requests.get(_UpperCAmelCase , stream=_UpperCAmelCase).raw) return im @torch.no_grad() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=False): """simple docstring""" SCREAMING_SNAKE_CASE = BitConfig( global_padding='same' , layer_type='bottleneck' , depths=(3, 4, 9) , out_features=['stage3'] , embedding_dynamic_padding=_UpperCAmelCase , ) SCREAMING_SNAKE_CASE = ViTHybridConfig(backbone_config=_UpperCAmelCase , image_size=384 , num_labels=1000) SCREAMING_SNAKE_CASE = False # load original model from timm SCREAMING_SNAKE_CASE = timm.create_model(_UpperCAmelCase , pretrained=_UpperCAmelCase) timm_model.eval() # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE = timm_model.state_dict() if base_model: remove_classification_head_(_UpperCAmelCase) SCREAMING_SNAKE_CASE = create_rename_keys(_UpperCAmelCase , _UpperCAmelCase) for src, dest in rename_keys: rename_key(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) read_in_q_k_v(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = 'huggingface/label-files' SCREAMING_SNAKE_CASE = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(_UpperCAmelCase , _UpperCAmelCase , repo_type='dataset') , 'r')) SCREAMING_SNAKE_CASE = {int(_UpperCAmelCase): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = idalabel SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} # load HuggingFace model if vit_name[-5:] == "in21k": SCREAMING_SNAKE_CASE = ViTHybridModel(_UpperCAmelCase).eval() else: SCREAMING_SNAKE_CASE = ViTHybridForImageClassification(_UpperCAmelCase).eval() model.load_state_dict(_UpperCAmelCase) # create image processor SCREAMING_SNAKE_CASE = create_transform(**resolve_data_config({} , model=_UpperCAmelCase)) SCREAMING_SNAKE_CASE = transform.transforms SCREAMING_SNAKE_CASE = { 'bilinear': PILImageResampling.BILINEAR, 'bicubic': PILImageResampling.BICUBIC, 'nearest': PILImageResampling.NEAREST, } SCREAMING_SNAKE_CASE = ViTHybridImageProcessor( do_resize=_UpperCAmelCase , size={'shortest_edge': timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=_UpperCAmelCase , crop_size={'height': timm_transforms[1].size[0], 'width': timm_transforms[1].size[1]} , do_normalize=_UpperCAmelCase , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = transform(_UpperCAmelCase).unsqueeze(0) SCREAMING_SNAKE_CASE = processor(_UpperCAmelCase , return_tensors='pt').pixel_values # verify pixel values assert torch.allclose(_UpperCAmelCase , _UpperCAmelCase) # verify logits with torch.no_grad(): SCREAMING_SNAKE_CASE = model(_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits print('Predicted class:' , logits.argmax(-1).item()) if base_model: SCREAMING_SNAKE_CASE = timm_model.forward_features(_UpperCAmelCase) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(_UpperCAmelCase , outputs.pooler_output , atol=1e-3) else: SCREAMING_SNAKE_CASE = timm_model(_UpperCAmelCase) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_UpperCAmelCase , outputs.logits , atol=1e-3) print('Looks ok!') if pytorch_dump_folder_path is not None: Path(_UpperCAmelCase).mkdir(exist_ok=_UpperCAmelCase) print(F'''Saving model {vit_name} to {pytorch_dump_folder_path}''') model.save_pretrained(_UpperCAmelCase) print(F'''Saving processor to {pytorch_dump_folder_path}''') processor.save_pretrained(_UpperCAmelCase) if push_to_hub: print(F'''Pushing model and processor to the hub {vit_name}''') model.push_to_hub(F'''ybelkada/{vit_name}''') processor.push_to_hub(F'''ybelkada/{vit_name}''') if __name__ == "__main__": a_ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--vit_name', default='vit_base_r50_s16_384', type=str, help='Name of the hybrid ViT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to upload the model to the HuggingFace hub.' ) a_ : Optional[Any] = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
355
import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint a_ : Optional[int] = { '169M': 12, '430M': 24, '1B5': 24, '3B': 32, '7B': 32, '14B': 40, } a_ : Optional[int] = { '169M': 7_68, '430M': 10_24, '1B5': 20_48, '3B': 25_60, '7B': 40_96, '14B': 51_20, } def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = list(state_dict.keys()) for name in state_dict_keys: SCREAMING_SNAKE_CASE = state_dict.pop(_UpperCAmelCase) # emb -> embedding if name.startswith('emb.'): SCREAMING_SNAKE_CASE = name.replace('emb.' , 'embeddings.') # ln_0 -> pre_ln (only present at block 0) if name.startswith('blocks.0.ln0'): SCREAMING_SNAKE_CASE = name.replace('blocks.0.ln0' , 'blocks.0.pre_ln') # att -> attention SCREAMING_SNAKE_CASE = re.sub(R'blocks\.(\d+)\.att' , R'blocks.\1.attention' , _UpperCAmelCase) # ffn -> feed_forward SCREAMING_SNAKE_CASE = re.sub(R'blocks\.(\d+)\.ffn' , R'blocks.\1.feed_forward' , _UpperCAmelCase) # time_mix_k -> time_mix_key and reshape if name.endswith('.time_mix_k'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_k' , '.time_mix_key') # time_mix_v -> time_mix_value and reshape if name.endswith('.time_mix_v'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_v' , '.time_mix_value') # time_mix_r -> time_mix_key and reshape if name.endswith('.time_mix_r'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_r' , '.time_mix_receptance') if name != "head.weight": SCREAMING_SNAKE_CASE = 'rwkv.' + name SCREAMING_SNAKE_CASE = weight return state_dict def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=False , _UpperCAmelCase=None): # 1. If possible, build the tokenizer. if tokenizer_file is None: print('No `--tokenizer_file` provided, we will use the default tokenizer.') SCREAMING_SNAKE_CASE = 5_0277 SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('EleutherAI/gpt-neox-20b') else: SCREAMING_SNAKE_CASE = PreTrainedTokenizerFast(tokenizer_file=_UpperCAmelCase) SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) tokenizer.save_pretrained(_UpperCAmelCase) # 2. Build the config SCREAMING_SNAKE_CASE = list(NUM_HIDDEN_LAYERS_MAPPING.keys()) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: SCREAMING_SNAKE_CASE = candidate break if size is None: raise ValueError('Could not infer the size, please provide it with the `--size` argument.') if size not in possible_sizes: raise ValueError(F'''`size` should be one of {possible_sizes}, got {size}.''') SCREAMING_SNAKE_CASE = RwkvConfig( vocab_size=_UpperCAmelCase , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(_UpperCAmelCase) # 3. Download model file then convert state_dict SCREAMING_SNAKE_CASE = hf_hub_download(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = convert_state_dict(_UpperCAmelCase) # 4. Split in shards and save SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = shard_checkpoint(_UpperCAmelCase) for shard_file, shard in shards.items(): torch.save(_UpperCAmelCase , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) if index is not None: SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , _UpperCAmelCase) # Save the index as well with open(_UpperCAmelCase , 'w' , encoding='utf-8') as f: SCREAMING_SNAKE_CASE = json.dumps(_UpperCAmelCase , indent=2 , sort_keys=_UpperCAmelCase) + '\n' f.write(_UpperCAmelCase) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( 'Cleaning up shards. This may error with an OOM error, it this is the case don\'t worry you still have converted the model.') SCREAMING_SNAKE_CASE = list(shards.keys()) del state_dict del shards gc.collect() for shard_file in shard_files: SCREAMING_SNAKE_CASE = torch.load(os.path.join(_UpperCAmelCase , _UpperCAmelCase)) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError('Please provide a `model_name` to push the model to the Hub.') SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(_UpperCAmelCase) model.push_to_hub(_UpperCAmelCase , max_shard_size='2GB') tokenizer.push_to_hub(_UpperCAmelCase) if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--repo_id', default=None, type=str, required=True, help='Repo ID from which to pull the checkpoint.' ) parser.add_argument( '--checkpoint_file', default=None, type=str, required=True, help='Name of the checkpoint file in the repo.' ) parser.add_argument( '--output_dir', default=None, type=str, required=True, help='Where to save the converted model.' ) parser.add_argument( '--tokenizer_file', default=None, type=str, help='Path to the tokenizer file to use (if not provided, only the model is converted).', ) parser.add_argument( '--size', default=None, type=str, help='Size of the model. Will be inferred from the `checkpoint_file` if not passed.', ) parser.add_argument( '--push_to_hub', action='store_true', help='Push to the Hub the converted model.', ) parser.add_argument( '--model_name', default=None, type=str, help='Name of the pushed model on the Hub, including the username / organization.', ) a_ : Tuple = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
327
0
import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, 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.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM @require_torch class _snake_case : def __init__( self , a , a=99 , a=13 , a=16 , a=7 , a=True , a=True , a=True , a=False , a=True , a=2 , a=32 , a=4 , a=4 , a=30 , a=0 , a=1 , a=2 , a=None , ) -> Dict: SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = decoder_seq_length # For common tests SCREAMING_SNAKE_CASE = self.decoder_seq_length SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_attention_mask SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = d_model SCREAMING_SNAKE_CASE = d_model SCREAMING_SNAKE_CASE = decoder_layers SCREAMING_SNAKE_CASE = decoder_layers SCREAMING_SNAKE_CASE = decoder_ffn_dim SCREAMING_SNAKE_CASE = decoder_attention_heads SCREAMING_SNAKE_CASE = decoder_attention_heads SCREAMING_SNAKE_CASE = eos_token_id SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = pad_token_id SCREAMING_SNAKE_CASE = decoder_start_token_id SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = decoder_seq_length SCREAMING_SNAKE_CASE = 2 SCREAMING_SNAKE_CASE = 1 def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE = None if self.use_attention_mask: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.decoder_seq_length] , vocab_size=2) SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE = TrOCRConfig( vocab_size=self.vocab_size , d_model=self.d_model , decoder_layers=self.decoder_layers , decoder_ffn_dim=self.decoder_ffn_dim , decoder_attention_heads=self.decoder_attention_heads , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , use_cache=self.use_cache , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , max_position_embeddings=self.max_position_embeddings , ) return (config, input_ids, attention_mask, lm_labels) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , ) -> List[Any]: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = TrOCRDecoder(config=__lowerCamelCase).to(__lowerCamelCase).eval() SCREAMING_SNAKE_CASE = input_ids[:2] input_ids[input_ids == 0] += 1 # first forward pass SCREAMING_SNAKE_CASE = model(__lowerCamelCase , use_cache=__lowerCamelCase) SCREAMING_SNAKE_CASE = model(__lowerCamelCase) SCREAMING_SNAKE_CASE = model(__lowerCamelCase , use_cache=__lowerCamelCase) self.parent.assertTrue(len(__lowerCamelCase) == len(__lowerCamelCase)) self.parent.assertTrue(len(__lowerCamelCase) == len(__lowerCamelCase) + 1) SCREAMING_SNAKE_CASE = outputs['''past_key_values'''] # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE = ids_tensor((2, 1) , config.vocab_size - 1) + 1 # append to next input_ids and SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1) SCREAMING_SNAKE_CASE = model(__lowerCamelCase)['''last_hidden_state'''] SCREAMING_SNAKE_CASE = model(__lowerCamelCase , past_key_values=__lowerCamelCase)['''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[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() SCREAMING_SNAKE_CASE = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice assert torch.allclose(__lowerCamelCase , __lowerCamelCase , atol=1E-3) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE = config_and_inputs SCREAMING_SNAKE_CASE = {'''input_ids''': input_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_torch class _snake_case ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): _lowercase : str = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else () _lowercase : Dict = (TrOCRForCausalLM,) if is_torch_available() else () _lowercase : List[Any] = {'''text-generation''': TrOCRForCausalLM} if is_torch_available() else {} _lowercase : Union[str, Any] = True _lowercase : List[str] = False def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = TrOCRStandaloneDecoderModelTester(self , is_training=__lowerCamelCase) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=__lowerCamelCase) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: pass def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: pass def SCREAMING_SNAKE_CASE__ ( self) -> str: pass def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past(*__lowerCamelCase) def SCREAMING_SNAKE_CASE__ ( self) -> Any: return @unittest.skip('The model doesn\'t support left padding') # and it's not used enough to be worth fixing :) def SCREAMING_SNAKE_CASE__ ( self) -> int: pass
356
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def lowerCamelCase__ (_UpperCAmelCase): monkeypatch.setattr('datasets.utils.deprecation_utils._emitted_deprecation_warnings' , set()) @pytest.fixture def lowerCamelCase__ (_UpperCAmelCase): class _snake_case : def __init__( self , a) -> List[Any]: SCREAMING_SNAKE_CASE = metric_id class _snake_case : _lowercase : Optional[Any] = [MetricMock(A__ ) for metric_id in ['''accuracy''', '''mse''', '''precision''', '''codeparrot/apps_metric''']] def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: return self._metrics monkeypatch.setattr('datasets.inspect.huggingface_hub' , HfhMock()) @pytest.mark.parametrize( 'func, args' , [(load_metric, ('metrics/mse',)), (list_metrics, ()), (inspect_metric, ('metrics/mse', 'tmp_path'))]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if "tmp_path" in args: SCREAMING_SNAKE_CASE = tuple(arg if arg != 'tmp_path' else tmp_path for arg in args) with pytest.warns(_UpperCAmelCase , match='https://huggingface.co/docs/evaluate'): func(*_UpperCAmelCase)
327
0
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin a_ : Tuple = random.Random() if is_torch_available(): import torch def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=1.0 , _UpperCAmelCase=None , _UpperCAmelCase=None): if rng is None: SCREAMING_SNAKE_CASE = global_rng SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0]): values.append([]) for _ in range(shape[1]): values[-1].append(rng.random() * scale) return values class _snake_case ( unittest.TestCase ): def __init__( self , a , a=7 , a=400 , a=2000 , a=1 , a=0.0 , a=1_6000 , a=True , a=True , ) -> Tuple: SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = min_seq_length SCREAMING_SNAKE_CASE = max_seq_length SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE = feature_size SCREAMING_SNAKE_CASE = padding_value SCREAMING_SNAKE_CASE = sampling_rate SCREAMING_SNAKE_CASE = return_attention_mask SCREAMING_SNAKE_CASE = do_normalize def SCREAMING_SNAKE_CASE__ ( self) -> Any: return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def SCREAMING_SNAKE_CASE__ ( self , a=False , a=False) -> Union[str, Any]: def _flatten(a): return list(itertools.chain(*_A)) if equal_length: SCREAMING_SNAKE_CASE = floats_list((self.batch_size, self.max_seq_length)) else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE = [ _flatten(floats_list((x, self.feature_size))) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff) ] if numpify: SCREAMING_SNAKE_CASE = [np.asarray(_A) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class _snake_case ( A__ , unittest.TestCase ): _lowercase : List[Any] = ASTFeatureExtractor def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = ASTFeatureExtractionTester(self) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE = [floats_list((1, x))[0] for x in range(800 , 1400 , 200)] SCREAMING_SNAKE_CASE = [np.asarray(_A) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE = feat_extract(speech_inputs[0] , return_tensors='np').input_values SCREAMING_SNAKE_CASE = feat_extract(np_speech_inputs[0] , return_tensors='np').input_values self.assertTrue(np.allclose(_A , _A , atol=1E-3)) # Test batched SCREAMING_SNAKE_CASE = feat_extract(_A , padding=_A , return_tensors='np').input_values SCREAMING_SNAKE_CASE = feat_extract(_A , padding=_A , return_tensors='np').input_values for enc_seq_a, enc_seq_a in zip(_A , _A): self.assertTrue(np.allclose(_A , _A , atol=1E-3)) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE = [floats_list((1, x))[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE = np.asarray(_A) SCREAMING_SNAKE_CASE = feat_extract(_A , return_tensors='np').input_values SCREAMING_SNAKE_CASE = feat_extract(_A , return_tensors='np').input_values for enc_seq_a, enc_seq_a in zip(_A , _A): self.assertTrue(np.allclose(_A , _A , atol=1E-3)) @require_torch def SCREAMING_SNAKE_CASE__ ( self) -> str: import torch SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) SCREAMING_SNAKE_CASE = np.random.rand(100).astype(np.floataa) SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE = feature_extractor.pad([{'input_values': inputs}] , return_tensors='np') self.assertTrue(np_processed.input_values.dtype == np.floataa) SCREAMING_SNAKE_CASE = feature_extractor.pad([{'input_values': inputs}] , return_tensors='pt') self.assertTrue(pt_processed.input_values.dtype == torch.floataa) def SCREAMING_SNAKE_CASE__ ( self , a) -> List[str]: from datasets import load_dataset SCREAMING_SNAKE_CASE = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation') # automatic decoding with librispeech SCREAMING_SNAKE_CASE = ds.sort('id').select(range(_A))[:num_samples]['audio'] return [x["array"] for x in speech_samples] @require_torch def SCREAMING_SNAKE_CASE__ ( self) -> Dict: # fmt: off SCREAMING_SNAKE_CASE = torch.tensor( [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76, -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33, -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36, -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69]) # fmt: on SCREAMING_SNAKE_CASE = self._load_datasamples(1) SCREAMING_SNAKE_CASE = ASTFeatureExtractor() SCREAMING_SNAKE_CASE = feature_extractor(_A , return_tensors='pt').input_values self.assertEquals(input_values.shape , (1, 1024, 128)) self.assertTrue(torch.allclose(input_values[0, 0, :30] , _A , atol=1E-4))
357
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : Any = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Dict = ['MLukeTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys a_ : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
327
0
import torch from transformers import AutoModel class _snake_case ( torch.nn.Module ): def __init__( self , a="sayef/fsner-bert-base-uncased") -> Optional[Any]: super(__snake_case , self).__init__() SCREAMING_SNAKE_CASE = AutoModel.from_pretrained(__snake_case , return_dict=__snake_case) SCREAMING_SNAKE_CASE = torch.nn.CosineSimilarity(3 , 1E-08) SCREAMING_SNAKE_CASE = torch.nn.Softmax(dim=1) def SCREAMING_SNAKE_CASE__ ( self , **a) -> Dict: return self.bert(**__snake_case).last_hidden_state def SCREAMING_SNAKE_CASE__ ( self , a) -> Union[str, Any]: return token_embeddings.sum(2 , keepdim=__snake_case) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=1) -> int: return self.softmax(T * self.cos(__snake_case , __snake_case)) def SCREAMING_SNAKE_CASE__ ( self , a , a) -> str: SCREAMING_SNAKE_CASE = W_supports['sizes'].tolist() SCREAMING_SNAKE_CASE = W_supports['start_token_id'].item() SCREAMING_SNAKE_CASE = W_supports['end_token_id'].item() del W_supports["sizes"] del W_supports["start_token_id"] del W_supports["end_token_id"] SCREAMING_SNAKE_CASE = self.BERT(**__snake_case) SCREAMING_SNAKE_CASE = self.BERT(**__snake_case) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = W_supports['input_ids'] == start_token_id SCREAMING_SNAKE_CASE = W_supports['input_ids'] == end_token_id for i, size in enumerate(__snake_case): if i == 0: SCREAMING_SNAKE_CASE = 0 else: SCREAMING_SNAKE_CASE = support_sizes[i - 1] SCREAMING_SNAKE_CASE = S[s : s + size][start_token_masks[s : s + size]] SCREAMING_SNAKE_CASE = S[s : s + size][end_token_masks[s : s + size]] SCREAMING_SNAKE_CASE = torch.matmul(q[i] , s_start.T).sum(1).softmax(0) SCREAMING_SNAKE_CASE = torch.matmul(q[i] , s_end.T).sum(1).softmax(0) if p_starts is not None: SCREAMING_SNAKE_CASE = torch.vstack((p_starts, p_start)) SCREAMING_SNAKE_CASE = torch.vstack((p_ends, p_end)) else: SCREAMING_SNAKE_CASE = p_start SCREAMING_SNAKE_CASE = p_end return p_starts, p_ends
358
from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer a_ : List[Any] = logging.get_logger(__name__) a_ : Union[str, Any] = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} a_ : str = { 'vocab_file': { 'allegro/herbert-base-cased': 'https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json' }, 'merges_file': { 'allegro/herbert-base-cased': 'https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt' }, } a_ : List[Any] = {'allegro/herbert-base-cased': 5_14} a_ : Dict = {} class _snake_case ( A__ ): _lowercase : Dict = VOCAB_FILES_NAMES _lowercase : int = PRETRAINED_VOCAB_FILES_MAP _lowercase : Any = PRETRAINED_INIT_CONFIGURATION _lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : Any = HerbertTokenizer def __init__( self , a=None , a=None , a=None , a="<s>" , a="<unk>" , a="<pad>" , a="<mask>" , a="</s>" , **a , ) -> Dict: super().__init__( a , a , tokenizer_file=a , cls_token=a , unk_token=a , pad_token=a , mask_token=a , sep_token=a , **a , ) def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: SCREAMING_SNAKE_CASE = [self.cls_token_id] SCREAMING_SNAKE_CASE = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = False) -> List[int]: 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] + ([0] * len(a)) + [1] def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: 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 SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> Tuple[str]: SCREAMING_SNAKE_CASE = self._tokenizer.model.save(a , name=a) return tuple(a)
327
0
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = inspect.getfile(accelerate.test_utils) SCREAMING_SNAKE_CASE = os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ['scripts', 'test_script.py']) SCREAMING_SNAKE_CASE = os.path.sep.join( mod_file.split(os.path.sep)[:-1] + ['scripts', 'test_distributed_data_loop.py']) SCREAMING_SNAKE_CASE = os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ['scripts', 'test_ops.py']) @require_multi_gpu def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: print(f'''Found {torch.cuda.device_count()} devices.''') SCREAMING_SNAKE_CASE = ['torchrun', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1): execute_subprocess_async(A__ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: print(f'''Found {torch.cuda.device_count()} devices.''') SCREAMING_SNAKE_CASE = ['torchrun', f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''') with patch_environment(omp_num_threads=1): execute_subprocess_async(A__ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = ['torchrun', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__)] with patch_environment(omp_num_threads=1): execute_subprocess_async(A__ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''') SCREAMING_SNAKE_CASE = ['torchrun', f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices='0,1'): execute_subprocess_async(A__ , env=os.environ.copy()) if __name__ == "__main__": a_ : Union[str, Any] = Accelerator() a_ : int = (accelerator.state.process_index + 2, 10) a_ : Any = torch.randint(0, 10, shape).to(accelerator.device) a_ : str = "" a_ : List[str] = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." a_ : List[Any] = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." a_ : int = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
359
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput a_ : Dict = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class _snake_case ( A__ ): def __init__( self , *a , a=None , a=None , a=None , **a) -> List[Any]: super().__init__(*a , **a) SCREAMING_SNAKE_CASE = eval_examples SCREAMING_SNAKE_CASE = post_process_function SCREAMING_SNAKE_CASE = quant_trainer_args SCREAMING_SNAKE_CASE = 128 # default number of calibration samples def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Union[str, Any]: if calib_dataset is None and self.calib_dataset is None: raise ValueError('Trainer: calibration requires an calib_dataset.') SCREAMING_SNAKE_CASE = calib_dataset if calib_dataset is not None else self.calib_dataset SCREAMING_SNAKE_CASE = self._remove_unused_columns(a , description='Calibration') return DataLoader( a , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=a , ) def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.train_dataset if calib_dataset is None else calib_dataset SCREAMING_SNAKE_CASE = self.get_calib_dataloader(a) SCREAMING_SNAKE_CASE = self.model quant_trainer.configure_model(a , self.quant_trainer_args , calib=a) model.eval() quant_trainer.enable_calibration(a) logger.info('***** Running calibration *****') logger.info(f''' Num examples = {self.calib_num}''') logger.info(f''' Batch size = {calib_dataloader.batch_size}''') for step, inputs in enumerate(a): # Prediction step SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.prediction_step(a , a , prediction_loss_only=a) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = model def SCREAMING_SNAKE_CASE__ ( self , a=None , a=None , a=None , a = "eval") -> str: 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 = 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 , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions) 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) self.log(a) else: SCREAMING_SNAKE_CASE = {} 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 SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a = "test") -> Optional[Any]: 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 = 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 , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions , '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) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=a) def SCREAMING_SNAKE_CASE__ ( self , a="./") -> List[Any]: SCREAMING_SNAKE_CASE = self.eval_dataset SCREAMING_SNAKE_CASE = self.get_eval_dataloader(a) SCREAMING_SNAKE_CASE = next(iter(a)) # saving device - to make it consistent SCREAMING_SNAKE_CASE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # convert to tuple SCREAMING_SNAKE_CASE = tuple(v.to(a) for k, v in batch.items()) logger.info('Converting model to be onnx compatible') from pytorch_quantization.nn import TensorQuantizer SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = self.model.to(a) model.eval() model.float() SCREAMING_SNAKE_CASE = model.module if hasattr(a , 'module') else model quant_trainer.configure_model(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = os.path.join(a , 'model.onnx') logger.info(f'''exporting model to {output_model_file}''') SCREAMING_SNAKE_CASE = {0: 'batch_size', 1: 'seq_len'} torch.onnx.export( a , a , a , export_params=a , opset_version=13 , do_constant_folding=a , input_names=['input_ids', 'attention_mask', 'token_type_ids'] , output_names=['output_start_logits', 'output_end_logits'] , dynamic_axes={ 'input_ids': axes, 'attention_mask': axes, 'token_type_ids': axes, 'output_start_logits': axes, 'output_end_logits': axes, } , verbose=a , ) logger.info('onnx export finished')
327
0
"""simple docstring""" import argparse import logging import sys from unittest.mock import patch import run_glue_deebert from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow logging.basicConfig(level=logging.DEBUG) a_ : List[Any] = logging.getLogger() def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument('-f') SCREAMING_SNAKE_CASE = parser.parse_args() return args.f class _snake_case ( __a ): def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = logging.StreamHandler(sys.stdout) logger.addHandler(a__) def SCREAMING_SNAKE_CASE__ ( self , a) -> int: SCREAMING_SNAKE_CASE = get_gpu_count() if n_gpu > 1: pass # XXX: doesn't quite work with n_gpu > 1 https://github.com/huggingface/transformers/issues/10560 # script = f"{self.examples_dir_str}/research_projects/deebert/run_glue_deebert.py" # distributed_args = f"-m torch.distributed.launch --nproc_per_node={n_gpu} {script}".split() # cmd = [sys.executable] + distributed_args + args # execute_subprocess_async(cmd, env=self.get_env()) # XXX: test the results - need to save them first into .json file else: args.insert(0 , 'run_glue_deebert.py') with patch.object(a__ , 'argv' , a__): SCREAMING_SNAKE_CASE = run_glue_deebert.main() for value in result.values(): self.assertGreaterEqual(a__ , 0.6_66) @slow @require_torch_non_multi_gpu def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = '\n --model_type roberta\n --model_name_or_path roberta-base\n --task_name MRPC\n --do_train\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --max_seq_length 128\n --per_gpu_eval_batch_size=1\n --per_gpu_train_batch_size=8\n --learning_rate 2e-4\n --num_train_epochs 3\n --overwrite_output_dir\n --seed 42\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --save_steps 0\n --overwrite_cache\n --eval_after_first_stage\n '.split() self.run_and_check(a__) SCREAMING_SNAKE_CASE = '\n --model_type roberta\n --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --task_name MRPC\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --max_seq_length 128\n --eval_each_highway\n --eval_highway\n --overwrite_cache\n --per_gpu_eval_batch_size=1\n '.split() self.run_and_check(a__) SCREAMING_SNAKE_CASE = '\n --model_type roberta\n --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --task_name MRPC\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --max_seq_length 128\n --early_exit_entropy 0.1\n --eval_highway\n --overwrite_cache\n --per_gpu_eval_batch_size=1\n '.split() self.run_and_check(a__)
360
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging a_ : Union[str, Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : List[str] = ['''pixel_values'''] def __init__( self , a = True , a = 1 / 255 , a = True , a = 8 , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = do_rescale SCREAMING_SNAKE_CASE = rescale_factor SCREAMING_SNAKE_CASE = do_pad SCREAMING_SNAKE_CASE = pad_size def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a) -> np.ndarray: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_image_size(a) SCREAMING_SNAKE_CASE = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE = (old_width // size + 1) * size - old_width return pad(a , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> List[str]: 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_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE = pad_size if pad_size is not None else self.pad_size 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_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE = [to_numpy_array(a) for image in images] if do_rescale: SCREAMING_SNAKE_CASE = [self.rescale(image=a , scale=a) for image in images] if do_pad: SCREAMING_SNAKE_CASE = [self.pad(a , size=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)
327
0
import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class _snake_case : def __init__( self , a , a=13 , a=7 , a=True , a=True , a=True , a=True , a=99 , a=32 , a=5 , a=4 , a=37 , a="gelu" , a=0.1 , a=0.1 , a=128 , a=32 , a=16 , a=2 , a=0.02 , a=3 , a=4 , a=None , ) -> List[str]: 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 SCREAMING_SNAKE_CASE__ ( self) -> str: 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 SCREAMING_SNAKE_CASE__ ( self) -> Any: return NezhaConfig( 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 SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: ( SCREAMING_SNAKE_CASE ) = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a) -> Dict: SCREAMING_SNAKE_CASE = NezhaModel(config=__A) model.to(__A) model.eval() SCREAMING_SNAKE_CASE = model(__A , attention_mask=__A , token_type_ids=__A) SCREAMING_SNAKE_CASE = model(__A , token_type_ids=__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 SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a , a , ) -> List[Any]: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = NezhaModel(__A) model.to(__A) model.eval() SCREAMING_SNAKE_CASE = model( __A , attention_mask=__A , token_type_ids=__A , encoder_hidden_states=__A , encoder_attention_mask=__A , ) SCREAMING_SNAKE_CASE = model( __A , attention_mask=__A , token_type_ids=__A , encoder_hidden_states=__A , ) SCREAMING_SNAKE_CASE = model(__A , attention_mask=__A , token_type_ids=__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 SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a) -> List[Any]: SCREAMING_SNAKE_CASE = NezhaForMaskedLM(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 SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a) -> Optional[int]: SCREAMING_SNAKE_CASE = NezhaForNextSentencePrediction(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, 2)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a) -> str: SCREAMING_SNAKE_CASE = NezhaForPreTraining(config=__A) model.to(__A) model.eval() SCREAMING_SNAKE_CASE = model( __A , attention_mask=__A , token_type_ids=__A , labels=__A , next_sentence_label=__A , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a) -> Dict: SCREAMING_SNAKE_CASE = NezhaForQuestionAnswering(config=__A) model.to(__A) model.eval() SCREAMING_SNAKE_CASE = model( __A , attention_mask=__A , token_type_ids=__A , start_positions=__A , end_positions=__A , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a) -> Optional[int]: SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = NezhaForSequenceClassification(__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.num_labels)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a) -> Optional[int]: SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = NezhaForTokenClassification(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.num_labels)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.num_choices SCREAMING_SNAKE_CASE = NezhaForMultipleChoice(config=__A) model.to(__A) model.eval() SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() SCREAMING_SNAKE_CASE = token_type_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 , token_type_ids=__A , labels=__A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( 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_torch class _snake_case ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): _lowercase : Optional[int] = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) _lowercase : str = ( { '''feature-extraction''': NezhaModel, '''fill-mask''': NezhaForMaskedLM, '''question-answering''': NezhaForQuestionAnswering, '''text-classification''': NezhaForSequenceClassification, '''token-classification''': NezhaForTokenClassification, '''zero-shot''': NezhaForSequenceClassification, } if is_torch_available() else {} ) _lowercase : Union[str, Any] = True def SCREAMING_SNAKE_CASE__ ( self , a , a , a=False) -> str: SCREAMING_SNAKE_CASE = super()._prepare_for_class(__A , __A , return_labels=__A) if return_labels: if model_class in get_values(__A): SCREAMING_SNAKE_CASE = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=__A) SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__A) return inputs_dict def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = NezhaModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=__A , hidden_size=37) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*__A) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: # This regression test was failing with PyTorch < 1.3 ( SCREAMING_SNAKE_CASE ) = self.model_tester.prepare_config_and_inputs_for_decoder() SCREAMING_SNAKE_CASE = None self.model_tester.create_and_check_model_as_decoder( __A , __A , __A , __A , __A , __A , __A , __A , __A , ) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__A) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__A) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*__A) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*__A) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__A) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__A) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__A) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained(__A) self.assertIsNotNone(__A) @slow @require_torch_gpu def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = model_class(config=__A) SCREAMING_SNAKE_CASE = self._prepare_for_class(__A , __A) SCREAMING_SNAKE_CASE = torch.jit.trace( __A , (inputs_dict['input_ids'].to('cpu'), inputs_dict['attention_mask'].to('cpu'))) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(__A , os.path.join(__A , 'bert.pt')) SCREAMING_SNAKE_CASE = torch.jit.load(os.path.join(__A , 'bert.pt') , map_location=__A) loaded(inputs_dict['input_ids'].to(__A) , inputs_dict['attention_mask'].to(__A)) @require_torch class _snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained('sijunhe/nezha-cn-base') SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]]) SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 1, 1, 1, 1]]) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(__A , attention_mask=__A)[0] SCREAMING_SNAKE_CASE = torch.Size((1, 6, 768)) self.assertEqual(output.shape , __A) SCREAMING_SNAKE_CASE = torch.tensor([[[0.06_85, 0.24_41, 0.11_02], [0.06_00, 0.19_06, 0.13_49], [0.02_21, 0.08_19, 0.05_86]]]) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __A , atol=1E-4)) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = NezhaForMaskedLM.from_pretrained('sijunhe/nezha-cn-base') SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]]) SCREAMING_SNAKE_CASE = torch.tensor([[1, 1, 1, 1, 1, 1]]) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(__A , attention_mask=__A)[0] SCREAMING_SNAKE_CASE = torch.Size((1, 6, 2_1128)) self.assertEqual(output.shape , __A) SCREAMING_SNAKE_CASE = torch.tensor( [[-2.79_39, -1.79_02, -2.21_89], [-2.85_85, -1.89_08, -2.37_23], [-2.64_99, -1.77_50, -2.25_58]]) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __A , atol=1E-4))
361
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class _snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = TFCamembertModel.from_pretrained('jplu/tf-camembert-base') SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 2_5543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" SCREAMING_SNAKE_CASE = model(a)['last_hidden_state'] SCREAMING_SNAKE_CASE = tf.TensorShape((1, 10, 768)) self.assertEqual(output.shape , a) # compare the actual values for a slice. SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[[-0.02_54, 0.02_35, 0.10_27], [0.06_06, -0.18_11, -0.04_18], [-0.15_61, -0.11_27, 0.26_87]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4))
327
0
from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING a_ : Optional[Any] = logging.get_logger(__name__) a_ : Dict = Dict[str, Any] a_ : Optional[int] = List[Prediction] @add_end_docstrings(A__ ) class _snake_case ( A__ ): def __init__( self , *a , **a) -> Any: super().__init__(*__a , **__a) if self.framework == "tf": raise ValueError(f'''The {self.__class__} is only available in PyTorch.''') requires_backends(self , 'vision') self.check_model_type( dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items())) def SCREAMING_SNAKE_CASE__ ( self , **a) -> Optional[Any]: SCREAMING_SNAKE_CASE = {} if "threshold" in kwargs: SCREAMING_SNAKE_CASE = kwargs['threshold'] return {}, {}, postprocess_kwargs def __call__( self , *a , **a) -> Union[Predictions, List[Prediction]]: return super().__call__(*__a , **__a) def SCREAMING_SNAKE_CASE__ ( self , a) -> str: SCREAMING_SNAKE_CASE = load_image(__a) SCREAMING_SNAKE_CASE = torch.IntTensor([[image.height, image.width]]) SCREAMING_SNAKE_CASE = self.image_processor(images=[image] , return_tensors='pt') if self.tokenizer is not None: SCREAMING_SNAKE_CASE = self.tokenizer(text=inputs['words'] , boxes=inputs['boxes'] , return_tensors='pt') SCREAMING_SNAKE_CASE = target_size return inputs def SCREAMING_SNAKE_CASE__ ( self , a) -> int: SCREAMING_SNAKE_CASE = model_inputs.pop('target_size') SCREAMING_SNAKE_CASE = self.model(**__a) SCREAMING_SNAKE_CASE = outputs.__class__({'target_size': target_size, **outputs}) if self.tokenizer is not None: SCREAMING_SNAKE_CASE = model_inputs['bbox'] return model_outputs def SCREAMING_SNAKE_CASE__ ( self , a , a=0.9) -> Dict: SCREAMING_SNAKE_CASE = model_outputs['target_size'] if self.tokenizer is not None: # This is a LayoutLMForTokenClassification variant. # The OCR got the boxes and the model classified the words. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = target_size[0].tolist() def unnormalize(a): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ])) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = model_outputs['logits'].squeeze(0).softmax(dim=-1).max(dim=-1) SCREAMING_SNAKE_CASE = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] SCREAMING_SNAKE_CASE = [unnormalize(__a) for bbox in model_outputs['bbox'].squeeze(0)] SCREAMING_SNAKE_CASE = ['score', 'label', 'box'] SCREAMING_SNAKE_CASE = [dict(zip(__a , __a)) for vals in zip(scores.tolist() , __a , __a) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel SCREAMING_SNAKE_CASE = self.image_processor.post_process_object_detection(__a , __a , __a) SCREAMING_SNAKE_CASE = raw_annotations[0] SCREAMING_SNAKE_CASE = raw_annotation['scores'] SCREAMING_SNAKE_CASE = raw_annotation['labels'] SCREAMING_SNAKE_CASE = raw_annotation['boxes'] SCREAMING_SNAKE_CASE = scores.tolist() SCREAMING_SNAKE_CASE = [self.model.config.idalabel[label.item()] for label in labels] SCREAMING_SNAKE_CASE = [self._get_bounding_box(__a) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] SCREAMING_SNAKE_CASE = ['score', 'label', 'box'] SCREAMING_SNAKE_CASE = [ dict(zip(__a , __a)) for vals in zip(raw_annotation['scores'] , raw_annotation['labels'] , raw_annotation['boxes']) ] return annotation def SCREAMING_SNAKE_CASE__ ( self , a) -> Dict[str, int]: if self.framework != "pt": raise ValueError('The ObjectDetectionPipeline is only available in PyTorch.') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = box.int().tolist() SCREAMING_SNAKE_CASE = { 'xmin': xmin, 'ymin': ymin, 'xmax': xmax, 'ymax': ymax, } return bbox
362
from scipy.stats import pearsonr import datasets a_ : Optional[int] = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n' a_ : Optional[int] = '\nArgs:\n predictions (`list` of `int`): Predicted class labels, as returned by a model.\n references (`list` of `int`): Ground truth labels.\n return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n Example 1-A simple example using only predictions and references.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n\n Example 2-The same as Example 1, but that also returns the `p-value`.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n >>> print(sorted(list(results.keys())))\n [\'p-value\', \'pearsonr\']\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n >>> print(round(results[\'p-value\'], 2))\n 0.15\n' a_ : Any = '\n@article{2020SciPy-NMeth,\nauthor = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Antonio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\njournal = {Nature Methods},\nyear = {2020},\nvolume = {17},\npages = {261--272},\nadsurl = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('float'), 'references': datasets.Value('float'), }) , reference_urls=['https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=False) -> Optional[Any]: if return_pvalue: SCREAMING_SNAKE_CASE = pearsonr(a , a) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(a , a)[0])}
327
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) a_ : Union[str, 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: a_ : Tuple = ['FunnelTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Any = [ 'FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST', 'FunnelBaseModel', 'FunnelForMaskedLM', 'FunnelForMultipleChoice', 'FunnelForPreTraining', 'FunnelForQuestionAnswering', 'FunnelForSequenceClassification', 'FunnelForTokenClassification', 'FunnelModel', 'FunnelPreTrainedModel', 'load_tf_weights_in_funnel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[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 a_ : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
363
import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class _snake_case ( unittest.TestCase ): _lowercase : List[Any] = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING _lowercase : int = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Any: SCREAMING_SNAKE_CASE = TextaTextGenerationPipeline(model=a , tokenizer=a) return generator, ["Something to write", "Something else"] def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Any: SCREAMING_SNAKE_CASE = generator('Something there') self.assertEqual(a , [{'generated_text': ANY(a)}]) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]['generated_text'].startswith('Something there')) SCREAMING_SNAKE_CASE = generator(['This is great !', 'Something else'] , num_return_sequences=2 , do_sample=a) self.assertEqual( a , [ [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], ] , ) SCREAMING_SNAKE_CASE = generator( ['This is great !', 'Something else'] , num_return_sequences=2 , batch_size=2 , do_sample=a) self.assertEqual( a , [ [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], ] , ) with self.assertRaises(a): generator(4) @require_torch def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='pt') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE = generator('Something there' , do_sample=a) self.assertEqual(a , [{'generated_text': ''}]) SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = generator( 'Something there' , num_return_sequences=a , num_beams=a , ) SCREAMING_SNAKE_CASE = [ {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': ''}, ] self.assertEqual(a , a) SCREAMING_SNAKE_CASE = generator('This is a test' , do_sample=a , num_return_sequences=2 , return_tensors=a) self.assertEqual( a , [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ] , ) SCREAMING_SNAKE_CASE = generator.model.config.eos_token_id SCREAMING_SNAKE_CASE = '<pad>' SCREAMING_SNAKE_CASE = generator( ['This is a test', 'This is a second test'] , do_sample=a , num_return_sequences=2 , batch_size=2 , return_tensors=a , ) self.assertEqual( a , [ [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ], [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ], ] , ) @require_tf def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='tf') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE = generator('Something there' , do_sample=a) self.assertEqual(a , [{'generated_text': ''}])
327
0
import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class _snake_case ( snake_case__ ): def __init__( self , a , a , a=1024 , a=1024 , a=3.6) -> str: SCREAMING_SNAKE_CASE = tokenizer SCREAMING_SNAKE_CASE = tokenizer.bos_token_id SCREAMING_SNAKE_CASE = dataset SCREAMING_SNAKE_CASE = seq_length SCREAMING_SNAKE_CASE = seq_length * chars_per_token * num_of_sequences def __iter__( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = iter(self.dataset) SCREAMING_SNAKE_CASE = True while more_examples: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(_A)['content']) buffer_len += len(buffer[-1]) except StopIteration: SCREAMING_SNAKE_CASE = False break SCREAMING_SNAKE_CASE = tokenizer(_A , truncation=_A)['input_ids'] SCREAMING_SNAKE_CASE = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id]) for i in range(0 , len(_A) , self.seq_length): SCREAMING_SNAKE_CASE = all_token_ids[i : i + self.seq_length] if len(_A) == self.seq_length: yield torch.tensor(_A) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {'streaming': True} SCREAMING_SNAKE_CASE = load_dataset(args.dataset_name , split='train' , **SCREAMING_SNAKE_CASE_) SCREAMING_SNAKE_CASE = ConstantLengthDataset(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , seq_length=args.seq_length) SCREAMING_SNAKE_CASE = DataLoader(SCREAMING_SNAKE_CASE_ , batch_size=args.batch_size) return eval_dataloader def lowerCamelCase__ (_UpperCAmelCase): model.eval() SCREAMING_SNAKE_CASE = [] for step, batch in enumerate(SCREAMING_SNAKE_CASE_): with torch.no_grad(): SCREAMING_SNAKE_CASE = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_) SCREAMING_SNAKE_CASE = outputs.loss.repeat(args.batch_size) losses.append(accelerator.gather(SCREAMING_SNAKE_CASE_)) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break SCREAMING_SNAKE_CASE = torch.mean(torch.cat(SCREAMING_SNAKE_CASE_)) try: SCREAMING_SNAKE_CASE = torch.exp(SCREAMING_SNAKE_CASE_) except OverflowError: SCREAMING_SNAKE_CASE = float('inf') return loss.item(), perplexity.item() # Setup Accelerator a_ : int = Accelerator() # Parse configuration a_ : Dict = HfArgumentParser(EvaluationArguments) a_ : Union[str, Any] = parser.parse_args() set_seed(args.seed) # Logging a_ : Optional[Any] = logging.getLogger(__name__) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) # Load model and tokenizer a_ : Any = AutoModelForCausalLM.from_pretrained(args.model_ckpt) a_ : Optional[Any] = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader a_ : str = create_dataloader(args) # Prepare everything with our `accelerator`. a_ , a_ : List[str] = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('Evaluating and saving model after training') a_ , a_ : Optional[int] = evaluate(args) logger.info(f"""loss/eval: {eval_loss}, perplexity: {perplexity}""")
364
import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights SCREAMING_SNAKE_CASE = FlaxDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=a , cache_dir=a) SCREAMING_SNAKE_CASE = [t[-1] for t in os.walk(os.path.join(a , os.listdir(a)[0] , 'snapshots'))] SCREAMING_SNAKE_CASE = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith('.bin') for f in files) @slow @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 4 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 4.1_51_47_45) < 1E-3 assert np.abs(np.abs(a , dtype=np.floataa).sum() - 4_99_47.8_75) < 5E-1 SCREAMING_SNAKE_CASE = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]))) assert len(a) == num_samples def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='flax' , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.05_65_24_01)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_38_38_08.2)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_00_39_06)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_37_35_16.75)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_00_39_06)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_37_35_16.75)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = FlaxDDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , set_alpha_to_one=a , steps_offset=1 , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , scheduler=a , safety_checker=a , ) SCREAMING_SNAKE_CASE = scheduler.create_state() SCREAMING_SNAKE_CASE = scheduler_state SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 50 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.0_45_04_39_45)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_34_76_93.5)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = jax.random.split(jax.random.PRNGKey(0) , a) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a , ) SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) SCREAMING_SNAKE_CASE = images[2, 0, 256, 10:17, 1] # With memory efficient attention SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a , use_memory_efficient_attention=a , ) SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , jit=a).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) SCREAMING_SNAKE_CASE = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice).max() < 1E-2
327
0
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_fnet import FNetTokenizer else: a_ : Union[str, Any] = None a_ : List[Any] = logging.get_logger(__name__) a_ : Tuple = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} a_ : Any = { 'vocab_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/spiece.model', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/spiece.model', }, 'tokenizer_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json', }, } a_ : str = { 'google/fnet-base': 5_12, 'google/fnet-large': 5_12, } a_ : Optional[Any] = '▁' class _snake_case ( a__ ): _lowercase : str = VOCAB_FILES_NAMES _lowercase : Dict = PRETRAINED_VOCAB_FILES_MAP _lowercase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : int = ["input_ids", "token_type_ids"] _lowercase : Union[str, Any] = FNetTokenizer def __init__( self , a=None , a=None , a=False , a=True , a=True , a="<unk>" , a="[SEP]" , a="<pad>" , a="[CLS]" , a="[MASK]" , **a , ) -> Any: # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. SCREAMING_SNAKE_CASE = ( AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ , normalized=SCREAMING_SNAKE_CASE_) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_) else mask_token ) super().__init__( SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , do_lower_case=SCREAMING_SNAKE_CASE_ , remove_space=SCREAMING_SNAKE_CASE_ , keep_accents=SCREAMING_SNAKE_CASE_ , unk_token=SCREAMING_SNAKE_CASE_ , sep_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) SCREAMING_SNAKE_CASE = do_lower_case SCREAMING_SNAKE_CASE = remove_space SCREAMING_SNAKE_CASE = keep_accents SCREAMING_SNAKE_CASE = vocab_file SCREAMING_SNAKE_CASE = False if not self.vocab_file else True def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: SCREAMING_SNAKE_CASE = [self.sep_token_id] SCREAMING_SNAKE_CASE = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: 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 SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE_): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''') return SCREAMING_SNAKE_CASE = os.path.join( SCREAMING_SNAKE_CASE_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE_): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE_) return (out_vocab_file,)
365
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets a_ : Tuple = '\\n@inproceedings{lin-2004-rouge,\n title = "{ROUGE}: A Package for Automatic Evaluation of Summaries",\n author = "Lin, Chin-Yew",\n booktitle = "Text Summarization Branches Out",\n month = jul,\n year = "2004",\n address = "Barcelona, Spain",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W04-1013",\n pages = "74--81",\n}\n' a_ : List[Any] = '\\nROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for\nevaluating automatic summarization and machine translation software in natural language processing.\nThe metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.\n\nNote that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.\n\nThis metrics is a wrapper around Google Research reimplementation of ROUGE:\nhttps://github.com/google-research/google-research/tree/master/rouge\n' a_ : List[str] = '\nCalculates average rouge scores for a list of hypotheses and 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 rouge_types: A list of rouge types to calculate.\n Valid names:\n `"rouge{n}"` (e.g. `"rouge1"`, `"rouge2"`) where: {n} is the n-gram based scoring,\n `"rougeL"`: Longest common subsequence based scoring.\n `"rougeLSum"`: rougeLsum splits text using `"\n"`.\n See details in https://github.com/huggingface/datasets/issues/617\n use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.\n use_aggregator: Return aggregates if this is set to True\nReturns:\n rouge1: rouge_1 (precision, recall, f1),\n rouge2: rouge_2 (precision, recall, f1),\n rougeL: rouge_l (precision, recall, f1),\n rougeLsum: rouge_lsum (precision, recall, f1)\nExamples:\n\n >>> rouge = datasets.load_metric(\'rouge\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> results = rouge.compute(predictions=predictions, references=references)\n >>> print(list(results.keys()))\n [\'rouge1\', \'rouge2\', \'rougeL\', \'rougeLsum\']\n >>> print(results["rouge1"])\n AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))\n >>> print(results["rouge1"].mid.fmeasure)\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence'), 'references': datasets.Value('string' , id='sequence'), }) , codebase_urls=['https://github.com/google-research/google-research/tree/master/rouge'] , reference_urls=[ 'https://en.wikipedia.org/wiki/ROUGE_(metric)', 'https://github.com/google-research/google-research/tree/master/rouge', ] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a=True , a=False) -> Optional[Any]: if rouge_types is None: SCREAMING_SNAKE_CASE = ['rouge1', 'rouge2', 'rougeL', 'rougeLsum'] SCREAMING_SNAKE_CASE = rouge_scorer.RougeScorer(rouge_types=a , use_stemmer=a) if use_aggregator: SCREAMING_SNAKE_CASE = scoring.BootstrapAggregator() else: SCREAMING_SNAKE_CASE = [] for ref, pred in zip(a , a): SCREAMING_SNAKE_CASE = scorer.score(a , a) if use_aggregator: aggregator.add_scores(a) else: scores.append(a) if use_aggregator: SCREAMING_SNAKE_CASE = aggregator.aggregate() else: SCREAMING_SNAKE_CASE = {} for key in scores[0]: SCREAMING_SNAKE_CASE = [score[key] for score in scores] return result
327
0
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class _snake_case ( unittest.TestCase ): def __init__( self , a , a=7 , a=3 , a=18 , a=30 , a=400 , a=True , a=None , a=True , ) -> str: SCREAMING_SNAKE_CASE = size if 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 = image_size SCREAMING_SNAKE_CASE = min_resolution SCREAMING_SNAKE_CASE = max_resolution SCREAMING_SNAKE_CASE = do_resize SCREAMING_SNAKE_CASE = size SCREAMING_SNAKE_CASE = apply_ocr def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class _snake_case ( _SCREAMING_SNAKE_CASE , unittest.TestCase ): _lowercase : str = LayoutLMvaImageProcessor if is_pytesseract_available() else None def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = LayoutLMvaImageProcessingTester(self) @property def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(a , 'do_resize')) self.assertTrue(hasattr(a , 'size')) self.assertTrue(hasattr(a , 'apply_ocr')) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size , {'height': 18, 'width': 18}) SCREAMING_SNAKE_CASE = self.image_processing_class.from_dict(self.image_processor_dict , size=42) self.assertEqual(image_processor.size , {'height': 42, 'width': 42}) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: pass def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: # Initialize image_processing 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 = image_processing(image_inputs[0] , return_tensors='pt') self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , a) self.assertIsInstance(encoding.boxes , a) # Test batched SCREAMING_SNAKE_CASE = image_processing(a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: # Initialize image_processing 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) # Test not batched input SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched SCREAMING_SNAKE_CASE = image_processing(a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def SCREAMING_SNAKE_CASE__ ( self) -> Any: # Initialize image_processing 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 = image_processing(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched SCREAMING_SNAKE_CASE = image_processing(a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def SCREAMING_SNAKE_CASE__ ( self) -> int: # with apply_OCR = True SCREAMING_SNAKE_CASE = LayoutLMvaImageProcessor() from datasets import load_dataset SCREAMING_SNAKE_CASE = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test') SCREAMING_SNAKE_CASE = Image.open(ds[0]['file']).convert('RGB') SCREAMING_SNAKE_CASE = image_processing(a , return_tensors='pt') self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224)) self.assertEqual(len(encoding.words) , len(encoding.boxes)) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 SCREAMING_SNAKE_CASE = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 SCREAMING_SNAKE_CASE = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , a) self.assertListEqual(encoding.boxes , a) # with apply_OCR = False SCREAMING_SNAKE_CASE = LayoutLMvaImageProcessor(apply_ocr=a) SCREAMING_SNAKE_CASE = image_processing(a , return_tensors='pt') self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224))
366
import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def lowerCamelCase__ (_UpperCAmelCase): if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class _snake_case ( nn.Module ): def __init__( self , a , a) -> Union[str, Any]: super().__init__() SCREAMING_SNAKE_CASE = module SCREAMING_SNAKE_CASE = nn.Sequential( nn.Linear(module.in_features , a , bias=a) , nn.Linear(a , module.out_features , bias=a) , ) SCREAMING_SNAKE_CASE = (2.0 / (5 * min(module.in_features , module.out_features))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=a) nn.init.zeros_(self.adapter[1].weight) self.adapter.to(module.weight.device) def SCREAMING_SNAKE_CASE__ ( self , a , *a , **a) -> Any: return self.module(a , *a , **a) + self.adapter(a) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): # We keep the constants inside the init function and model loading inside setUp function # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) # Therefore here we use only bloom-1b3 to test our module _lowercase : Union[str, Any] = '''bigscience/bloom-1b7''' # Constant values _lowercase : str = 2.109_6595_5269_2574 _lowercase : Any = '''Hello my name is''' _lowercase : Any = set() EXPECTED_OUTPUTS.add('''Hello my name is John and I am a professional photographer. I''' ) EXPECTED_OUTPUTS.add('''Hello my name is John.\nI am a friend of your father.\n''' ) EXPECTED_OUTPUTS.add('''Hello my name is John Doe, I am a student at the University''' ) _lowercase : Union[str, Any] = 10 def SCREAMING_SNAKE_CASE__ ( self) -> Any: # Models and tokenizer SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(self.model_name) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: super().setUp() # Models and tokenizer SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map='auto') SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_abit.config self.assertTrue(hasattr(a , 'quantization_config')) SCREAMING_SNAKE_CASE = config.to_dict() SCREAMING_SNAKE_CASE = config.to_diff_dict() SCREAMING_SNAKE_CASE = config.to_json_string() def SCREAMING_SNAKE_CASE__ ( self) -> Any: from bitsandbytes.nn import Paramsabit SCREAMING_SNAKE_CASE = self.model_fpaa.get_memory_footprint() SCREAMING_SNAKE_CASE = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE) SCREAMING_SNAKE_CASE = get_some_linear_layer(self.model_abit) self.assertTrue(linear.weight.__class__ == Paramsabit) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(a , torch.nn.Linear): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = self.model_abit.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = BitsAndBytesConfig() SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = model_abit_from_config.generate( input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) def SCREAMING_SNAKE_CASE__ ( self) -> str: with self.assertRaises(a), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = BitsAndBytesConfig() with self.assertRaises(a): SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=a , load_in_abit=a , device_map='auto' , bnb_abit_quant_type='nf4' , ) def SCREAMING_SNAKE_CASE__ ( self) -> int: with self.assertRaises(a): # Tries with `str` self.model_abit.to('cpu') with self.assertRaises(a): # Tries with a `dtype`` self.model_abit.to(torch.floataa) with self.assertRaises(a): # Tries with a `device` self.model_abit.to(torch.device('cuda:0')) with self.assertRaises(a): # Tries with a `device` self.model_abit.float() with self.assertRaises(a): # Tries with a `device` self.model_abit.half() # Test if we did not break anything SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = self.model_fpaa.to(torch.floataa) SCREAMING_SNAKE_CASE = self.model_fpaa.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.to('cpu') # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.half() # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.float() def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained('t5-small' , load_in_abit=a , device_map='auto') self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Tuple: SCREAMING_SNAKE_CASE = 't5-small' SCREAMING_SNAKE_CASE = 'google/flan-t5-small' # flan-t5 uses dense-act instead of dense-relu-dense SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(cls.model_name) SCREAMING_SNAKE_CASE = 'Translate in German: Hello, my dog is cute' def SCREAMING_SNAKE_CASE__ ( self) -> Dict: gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: from transformers import TaForConditionalGeneration SCREAMING_SNAKE_CASE = TaForConditionalGeneration._keep_in_fpaa_modules SCREAMING_SNAKE_CASE = None # test with `t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) # test with `flan-t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) SCREAMING_SNAKE_CASE = modules def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit)) SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) # test with `flan-t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> str: super().setUp() # model_name SCREAMING_SNAKE_CASE = 'bigscience/bloom-560m' SCREAMING_SNAKE_CASE = 't5-small' # Different types of model SCREAMING_SNAKE_CASE = AutoModel.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # Sequence classification model SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=a , device_map='auto') # CausalLM model SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # Seq2seq model SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=a , device_map='auto') def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Dict: del self.pipe gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = pipeline( 'text-generation' , model=self.model_name , model_kwargs={'device_map': 'auto', 'load_in_4bit': True, 'torch_dtype': torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass SCREAMING_SNAKE_CASE = self.pipe(self.input_text) self.assertIn(pipeline_output[0]['generated_text'] , self.EXPECTED_OUTPUTS) @require_torch_multi_gpu class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> int: super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=a , device_map='balanced') # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values()) , {0, 1}) # Check that inference pass works on the model SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') # Second real batch SCREAMING_SNAKE_CASE = model_parallel.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = 'facebook/opt-350m' super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Any: if version.parse(importlib.metadata.version('bitsandbytes')) < version.parse('0.37.0'): return # Step 1: freeze all parameters SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a) self.assertEqual(set(model.hf_device_map.values()) , {torch.cuda.current_device()}) for param in model.parameters(): SCREAMING_SNAKE_CASE = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability SCREAMING_SNAKE_CASE = param.data.to(torch.floataa) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(a)): SCREAMING_SNAKE_CASE = LoRALayer(module.q_proj , rank=16) SCREAMING_SNAKE_CASE = LoRALayer(module.k_proj , rank=16) SCREAMING_SNAKE_CASE = LoRALayer(module.v_proj , rank=16) # Step 3: dummy batch SCREAMING_SNAKE_CASE = self.tokenizer('Test batch ' , return_tensors='pt').to(0) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): SCREAMING_SNAKE_CASE = model.forward(**a) out.logits.norm().backward() for module in model.modules(): if isinstance(a , a): self.assertTrue(module.adapter[1].weight.grad is not None) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0) elif isinstance(a , nn.Embedding): self.assertTrue(module.weight.grad is None) class _snake_case ( A__ ): _lowercase : str = '''gpt2-xl''' _lowercase : Union[str, Any] = 3.3191_8548_5415_2187
327
0
import gc import unittest from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> str: # clean up the VRAM after each test super().tearDown() gc.collect() def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = FlaxControlNetModel.from_pretrained( 'lllyasviel/sd-controlnet-canny' , from_pt=__lowercase , dtype=jnp.bfloataa) SCREAMING_SNAKE_CASE = FlaxStableDiffusionControlNetPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , controlnet=__lowercase , from_pt=__lowercase , dtype=jnp.bfloataa) SCREAMING_SNAKE_CASE = controlnet_params SCREAMING_SNAKE_CASE = '''bird''' SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = pipe.prepare_text_inputs([prompts] * num_samples) SCREAMING_SNAKE_CASE = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png') SCREAMING_SNAKE_CASE = pipe.prepare_image_inputs([canny_image] * num_samples) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = jax.random.split(__lowercase , jax.device_count()) SCREAMING_SNAKE_CASE = replicate(__lowercase) SCREAMING_SNAKE_CASE = shard(__lowercase) SCREAMING_SNAKE_CASE = shard(__lowercase) SCREAMING_SNAKE_CASE = pipe( prompt_ids=__lowercase , image=__lowercase , params=__lowercase , prng_seed=__lowercase , num_inference_steps=50 , jit=__lowercase , ).images assert images.shape == (jax.device_count(), 1, 768, 512, 3) SCREAMING_SNAKE_CASE = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:]) SCREAMING_SNAKE_CASE = images[0, 253:256, 253:256, -1] SCREAMING_SNAKE_CASE = jnp.asarray(jax.device_get(image_slice.flatten())) SCREAMING_SNAKE_CASE = jnp.array( [0.16_79_69, 0.11_66_99, 0.08_15_43, 0.15_42_97, 0.13_28_12, 0.10_88_87, 0.16_99_22, 0.16_99_22, 0.20_50_78]) print(f'''output_slice: {output_slice}''') assert jnp.abs(output_slice - expected_slice).max() < 1E-2 def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = FlaxControlNetModel.from_pretrained( 'lllyasviel/sd-controlnet-openpose' , from_pt=__lowercase , dtype=jnp.bfloataa) SCREAMING_SNAKE_CASE = FlaxStableDiffusionControlNetPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , controlnet=__lowercase , from_pt=__lowercase , dtype=jnp.bfloataa) SCREAMING_SNAKE_CASE = controlnet_params SCREAMING_SNAKE_CASE = '''Chef in the kitchen''' SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = pipe.prepare_text_inputs([prompts] * num_samples) SCREAMING_SNAKE_CASE = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png') SCREAMING_SNAKE_CASE = pipe.prepare_image_inputs([pose_image] * num_samples) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = jax.random.split(__lowercase , jax.device_count()) SCREAMING_SNAKE_CASE = replicate(__lowercase) SCREAMING_SNAKE_CASE = shard(__lowercase) SCREAMING_SNAKE_CASE = shard(__lowercase) SCREAMING_SNAKE_CASE = pipe( prompt_ids=__lowercase , image=__lowercase , params=__lowercase , prng_seed=__lowercase , num_inference_steps=50 , jit=__lowercase , ).images assert images.shape == (jax.device_count(), 1, 768, 512, 3) SCREAMING_SNAKE_CASE = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:]) SCREAMING_SNAKE_CASE = images[0, 253:256, 253:256, -1] SCREAMING_SNAKE_CASE = jnp.asarray(jax.device_get(image_slice.flatten())) SCREAMING_SNAKE_CASE = jnp.array( [[0.27_14_84, 0.26_17_19, 0.27_53_91, 0.27_73_44, 0.27_92_97, 0.29_10_16, 0.29_49_22, 0.30_27_34, 0.30_27_34]]) print(f'''output_slice: {output_slice}''') assert jnp.abs(output_slice - expected_slice).max() < 1E-2
367
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : Optional[Any] = { 'configuration_efficientnet': [ 'EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'EfficientNetConfig', 'EfficientNetOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[str] = ['EfficientNetImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = [ 'EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'EfficientNetForImageClassification', 'EfficientNetModel', 'EfficientNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure)
327
0
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _snake_case ( UpperCamelCase__ ): _lowercase : List[str] = ["""image_processor""", """tokenizer"""] _lowercase : List[Any] = """AutoImageProcessor""" _lowercase : Any = """AutoTokenizer""" def __init__( self , a , a) -> Dict: super().__init__(__a , __a) SCREAMING_SNAKE_CASE = self.image_processor def __call__( self , a=None , a=None , a=None , **a) -> int: 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(__a , return_tensors=__a , **__a) if images is not None: SCREAMING_SNAKE_CASE = self.image_processor(__a , return_tensors=__a , **__a) if text is not None and images is not None: SCREAMING_SNAKE_CASE = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__a) , tensor_type=__a) def SCREAMING_SNAKE_CASE__ ( self , *a , **a) -> Tuple: return self.tokenizer.batch_decode(*__a , **__a) def SCREAMING_SNAKE_CASE__ ( self , *a , **a) -> List[str]: return self.tokenizer.decode(*__a , **__a) @property def SCREAMING_SNAKE_CASE__ ( self) -> int: return ["input_ids", "attention_mask", "pixel_values"]
368
import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) a_ : Dict = [ 'cross_validation.py', 'gradient_accumulation.py', 'local_sgd.py', 'multi_process_metrics.py', 'memory.py', 'automatic_gradient_accumulation.py', 'fsdp_with_peak_mem_tracking.py', 'deepspeed_with_config_support.py', 'megatron_lm_gpt_pretraining.py', ] class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , a = None) -> Optional[int]: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = os.path.abspath(os.path.join('examples' , 'by_feature')) SCREAMING_SNAKE_CASE = os.path.abspath('examples') for item in os.listdir(a): if item not in EXCLUDE_EXAMPLES: SCREAMING_SNAKE_CASE = os.path.join(a , a) if os.path.isfile(a) and ".py" in item_path: with self.subTest( tested_script=a , feature_script=a , tested_section='main()' if parser_only else 'training_function()' , ): SCREAMING_SNAKE_CASE = compare_against_test( os.path.join(a , a) , a , a , a) SCREAMING_SNAKE_CASE = '\n'.join(a) if special_strings is not None: for string in special_strings: SCREAMING_SNAKE_CASE = diff.replace(a , '') self.assertEqual(a , '') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: self.one_complete_example('complete_nlp_example.py' , a) self.one_complete_example('complete_nlp_example.py' , a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = os.path.abspath(os.path.join('examples' , 'cv_example.py')) SCREAMING_SNAKE_CASE = [ ' ' * 16 + '{\n\n', ' ' * 20 + '"accuracy": eval_metric["accuracy"],\n\n', ' ' * 20 + '"f1": eval_metric["f1"],\n\n', ' ' * 20 + '"train_loss": total_loss.item() / len(train_dataloader),\n\n', ' ' * 20 + '"epoch": epoch,\n\n', ' ' * 16 + '},\n\n', ' ' * 16 + 'step=epoch,\n', ' ' * 12, ' ' * 8 + 'for step, batch in enumerate(active_dataloader):\n', ] self.one_complete_example('complete_cv_example.py' , a , a , a) self.one_complete_example('complete_cv_example.py' , a , a , a) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class _snake_case ( A__ ): _lowercase : int = False @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Union[str, Any]: super().setUpClass() SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = os.path.join(cls._tmpdir , 'default_config.yml') write_basic_config(save_location=cls.configPath) SCREAMING_SNAKE_CASE = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Dict: super().tearDownClass() shutil.rmtree(cls._tmpdir) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'epoch_0'))) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'step_2'))) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0')} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) self.assertNotIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2')} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) if torch.cuda.is_available(): SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: SCREAMING_SNAKE_CASE = 1 if num_processes > 1: self.assertNotIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) else: self.assertIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = '\n examples/by_feature/cross_validation.py\n --num_folds 2\n '.split() with mock.patch.dict(os.environ , {'TESTING_MOCKED_DATALOADERS': '0'}): SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) SCREAMING_SNAKE_CASE = re.findall('({.+})' , a) SCREAMING_SNAKE_CASE = [r for r in results if 'accuracy' in r][-1] SCREAMING_SNAKE_CASE = ast.literal_eval(a) self.assertGreaterEqual(results['accuracy'] , 0.75) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ['examples/by_feature/multi_process_metrics.py'] run_command(self._launch_args + testargs) @require_trackers @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'}) def SCREAMING_SNAKE_CASE__ ( self) -> Any: with tempfile.TemporaryDirectory() as tmpdir: SCREAMING_SNAKE_CASE = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(a , 'tracking'))) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = ['examples/by_feature/gradient_accumulation.py'] run_command(self._launch_args + testargs) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = ['examples/by_feature/local_sgd.py'] run_command(self._launch_args + testargs)
327
0
from ....configuration_utils import PretrainedConfig from ....utils import logging a_ : Any = logging.get_logger(__name__) # TODO: upload to AWS a_ : Any = { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json' ), } class _snake_case ( _UpperCamelCase ): _lowercase : Tuple = 'retribert' def __init__( self , a=3_0522 , a=768 , a=8 , a=12 , a=3072 , a="gelu" , a=0.1 , a=0.1 , a=512 , a=2 , a=0.02 , a=1E-12 , a=True , a=128 , a=0 , **a , ) -> int: super().__init__(pad_token_id=_UpperCAmelCase , **_UpperCAmelCase) 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 = 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 = share_encoders SCREAMING_SNAKE_CASE = projection_dim
369
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _snake_case : def __init__( self , a , a=3 , a=32 , a=3 , a=10 , a=[10, 20, 30, 40] , a=[1, 1, 2, 1] , a=True , a=True , a="relu" , a=3 , a=None , ) -> Union[str, Any]: 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 SCREAMING_SNAKE_CASE__ ( self) -> List[str]: 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 SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return ResNetConfig( 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 , image_size=self.image_size , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Any: SCREAMING_SNAKE_CASE = TFResNetModel(config=a) 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 SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> int: SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = TFResNetForImageClassification(a) SCREAMING_SNAKE_CASE = model(a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: 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_tf class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () _lowercase : Dict = ( {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification} if is_tf_available() else {} ) _lowercase : Union[str, Any] = False _lowercase : Any = False _lowercase : List[str] = False _lowercase : str = False _lowercase : int = False def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = TFResNetModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , has_text_modality=a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return @unittest.skip(reason='ResNet does not use inputs_embeds') def SCREAMING_SNAKE_CASE__ ( self) -> int: pass @unittest.skip(reason='ResNet does not support input and output embeddings') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: pass def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: 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.call) # 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 SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: def check_hidden_states_output(a , a , a): SCREAMING_SNAKE_CASE = model_class(a) 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) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 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 SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> str: for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = TFResNetModel.from_pretrained(a) self.assertIsNotNone(a) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') return image @require_tf @require_vision class _snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = image_processor(images=a , return_tensors='tf') # forward pass SCREAMING_SNAKE_CASE = model(**a) # verify the logits SCREAMING_SNAKE_CASE = tf.TensorShape((1, 1000)) self.assertEqual(outputs.logits.shape , a) SCREAMING_SNAKE_CASE = tf.constant([-11.10_69, -9.78_77, -8.37_77]) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , a , atol=1E-4))
327
0
import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def lowerCamelCase__ (_UpperCAmelCase): return (data["data"], data["target"]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = XGBRegressor(verbosity=0 , random_state=42) xgb.fit(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) # Predict target for test data SCREAMING_SNAKE_CASE = xgb.predict(__SCREAMING_SNAKE_CASE) SCREAMING_SNAKE_CASE = predictions.reshape(len(__SCREAMING_SNAKE_CASE) , 1) return predictions def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = fetch_california_housing() SCREAMING_SNAKE_CASE = data_handling(__SCREAMING_SNAKE_CASE) SCREAMING_SNAKE_CASE = train_test_split( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , test_size=0.25 , random_state=1) SCREAMING_SNAKE_CASE = xgboost(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) # Error printing print(F'''Mean Absolute Error : {mean_absolute_error(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE)}''') print(F'''Mean Square Error : {mean_squared_error(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE)}''') if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
370
from math import isqrt def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [True] * max_number for i in range(2 , isqrt(max_number - 1) + 1): if is_prime[i]: for j in range(i**2 , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = False return [i for i in range(2 , _UpperCAmelCase) if is_prime[i]] def lowerCamelCase__ (_UpperCAmelCase = 10**8): SCREAMING_SNAKE_CASE = calculate_prime_numbers(max_number // 2) SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(f"""{solution() = }""")
327
0