/usr/local/lib/python3.6/site-packages/transformers/__pycache__
NameSizeModeActions
activations.cpython-36.pyc77500644editdlrm
activations_tf.cpython-36.pyc41360644editdlrm
configuration_utils.cpython-36.pyc393970644editdlrm
convert_graph_to_onnx.cpython-36.pyc160360644editdlrm
convert_pytorch_checkpoint_to_tf2.cpython-36.pyc91760644editdlrm
convert_slow_tokenizer.cpython-36.pyc304510644editdlrm
convert_slow_tokenizers_checkpoints_to_fast.cpython-36.pyc29500644editdlrm
convert_tf_hub_seq_to_seq_bert_to_pytorch.cpython-36.pyc18310644editdlrm
debug_utils.cpython-36.pyc110980644editdlrm
deepspeed.cpython-36.pyc128870644editdlrm
dependency_versions_check.cpython-36.pyc9610644editdlrm
dependency_versions_table.cpython-36.pyc20390644editdlrm
dynamic_module_utils.cpython-36.pyc139500644editdlrm
feature_extraction_sequence_utils.cpython-36.pyc128480644editdlrm
feature_extraction_utils.cpython-36.pyc225680644editdlrm
file_utils.cpython-36.pyc38030644editdlrm
generation_beam_constraints.cpython-36.pyc165560644editdlrm
generation_beam_search.cpython-36.pyc254400644editdlrm
generation_flax_logits_process.cpython-36.pyc110800644editdlrm
generation_flax_utils.cpython-36.pyc223200644editdlrm
generation_logits_process.cpython-36.pyc283870644editdlrm
generation_stopping_criteria.cpython-36.pyc63520644editdlrm
generation_tf_logits_process.cpython-36.pyc165240644editdlrm
generation_tf_utils.cpython-36.pyc863740644editdlrm
generation_utils.cpython-36.pyc1135760644editdlrm
hf_argparser.cpython-36.pyc89970644editdlrm
image_utils.cpython-36.pyc97300644editdlrm
integrations.cpython-36.pyc314040644editdlrm
keras_callbacks.cpython-36.pyc145290644editdlrm
modelcard.cpython-36.pyc261650644editdlrm
modeling_flax_outputs.cpython-36.pyc348780644editdlrm
modeling_flax_pytorch_utils.cpython-36.pyc83510644editdlrm
modeling_flax_utils.cpython-36.pyc286020644editdlrm
modeling_outputs.cpython-36.pyc590830644editdlrm
modeling_tf_outputs.cpython-36.pyc457330644editdlrm
modeling_tf_pytorch_utils.cpython-36.pyc125920644editdlrm
modeling_tf_utils.cpython-36.pyc709060644editdlrm
modeling_utils.cpython-36.pyc983820644editdlrm
optimization.cpython-36.pyc226530644editdlrm
optimization_tf.cpython-36.pyc134080644editdlrm
processing_utils.cpython-36.pyc85680644editdlrm
pytorch_utils.cpython-36.pyc11180644editdlrm
testing_utils.cpython-36.pyc432770644editdlrm
tf_utils.cpython-36.pyc12510644editdlrm
tokenization_utils.cpython-36.pyc258450644editdlrm
tokenization_utils_base.cpython-36.pyc1292790644editdlrm
tokenization_utils_fast.cpython-36.pyc219790644editdlrm
trainer.cpython-36.pyc818400644editdlrm
trainer_callback.cpython-36.pyc229060644editdlrm
trainer_pt_utils.cpython-36.pyc398290644editdlrm
trainer_seq2seq.cpython-36.pyc80280644editdlrm
trainer_tf.cpython-36.pyc255360644editdlrm
trainer_utils.cpython-36.pyc155710644editdlrm
training_args.cpython-36.pyc546000644editdlrm
training_args_seq2seq.cpython-36.pyc23170644editdlrm
training_args_tf.cpython-36.pyc128690644editdlrm
__init__.cpython-36.pyc1094310644editdlrm
Edit: /usr/local/lib/python3.6/site-packages/transformers/__pycache__/trainer.cpython-36.pyc (81840B)
3 Eg.@sBdZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddl mZddlmZmZmZmZmZmZmZmZddlmZddlmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&ddl'Z(ddl)Z)ddl*j+Z,dd l-m.Z.dd l)m/Z/dd l0m1Z1m2Z2m3Z3m4Z4dd l5m6Z6dd l7m8Z8ddl9m:Z:ddl;mZ>m?Z?m@Z@ddlAmBZBmCZCddlDmEZEmFZFmGZGddlHmIZIddlJmKZKddlLmMZMmNZNddlOmPZPmQZQddlRmSZSddlTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[ddl\m]Z]m^Z^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZkmlZlmmZmmnZnddlompZpmqZqmrZrmsZsmtZtmuZumvZvmwZwmxZxmyZymzZzm{Z{m|Z|m}Z}m~Z~mZmZmZmZddlmZmZmZddlmZmZmZmZmZmZmZmZmZmZmZdZdZeVgZeXZerddlmZeZerddlmZe.je)j:e.jd krHd!Zd!Zdd"lmZerXddlZerddljjZddljjZddlj+jZereId#ddlZdd$lmZdd%lmZdd&lmZdd'lmZdd(lmZerddljj)Zdd)l\mZmZmZmZerddlZejeZd*Zd+Zd,Zd-Zd.ZGd/d0d0ZdS)1uc The Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task. N)Mapping)Path) TYPE_CHECKINGAnyCallableDictListOptionalTupleUnion)tqdm) default_hp_search_backend#get_reporting_integration_callbacks hp_paramsis_fairscale_availableis_optuna_availableis_ray_tune_availableis_sigopt_availableis_wandb_availablerun_hp_search_optunarun_hp_search_rayrun_hp_search_sigoptrun_hp_search_wandb)version)nn) DataLoaderDataset RandomSamplerSequentialSampler)DistributedSampler) Repository) __version__)PretrainedConfig) DataCollatorDataCollatorWithPaddingdefault_data_collator) DebugOptionDebugUnderflowOverflow)deepspeed_initdeepspeed_reinitis_deepspeed_zero3_enabled)dep_version_check)TrainingSummary)PreTrainedModel unwrap_model) Adafactor get_scheduler)PreTrainedTokenizerBase)CallbackHandlerDefaultFlowCallbackPrinterCallbackProgressCallbackTrainerCallbackTrainerControl TrainerState)DistributedLengthGroupedSamplerDistributedSamplerWithLoopDistributedTensorGathererIterableDatasetShard LabelSmootherLengthGroupedSamplerSequentialDistributedSampler ShardSamplerdistributed_broadcast_scalarsdistributed_concatfind_batch_sizeget_parameter_names nested_concat nested_detachnested_numpifynested_truncatenested_xla_mesh_reducereissue_pt_warnings)PREFIX_CHECKPOINT_DIRBestRunEvalLoopOutputEvalPredictionHPSearchBackend HubStrategyIntervalStrategyPredictionOutputShardedDDPOptionTrainerMemoryTracker TrainOutputdefault_compute_objectivedefault_hp_spacedenumpify_detensorizeget_last_checkpoint has_lengthnumber_of_argumentsset_seed speed_metrics)OptimizerNames ParallelModeTrainingArguments) CONFIG_NAME WEIGHTS_NAME find_labelsget_full_repo_nameis_apex_availableis_datasets_availableis_in_notebookis_sagemaker_dp_enabledis_sagemaker_mp_enabledis_torch_tpu_availableloggingF)NotebookProgressCallback)ampz1.6T)autocast fairscale)FullyShardedDataParallel)ShardedDataParallel) auto_wrap)OSS)ShardedGradScaler)smp_forward_backwardsmp_forward_only smp_gathersmp_nested_concatztraining_args.binztrainer_state.jsonz optimizer.ptz scheduler.ptz scaler.ptc@seZdZdZddlmZmZmZmZm Z de e e j feeeeeeeeeege feeegefeeeeejjejjjfeejejgejfd ddZdd Z d d Z!d d Z"ddZ#ddee$dddZ%eej&j'j(dddZ)e*dddZ+eeej&j'j(dddZ,deee*dddZ-ee*ddd Z.e/d!d"d#Z0d$d%Z1e2eee3e3fd&d'd(Z4de/ejjd)d*d+Z5e*e/d,d-d.Z6e d/ee$e3ffd0d1d2Z7e d/ee$e3ffe/ee$e8fd3d4d5Z9d6d7Z:dd8d9Z;dd;d<Zd?Z>d@dAZ?dBdCZ@dDdEZAddFdGZBdHdIZCdeed/gee$e8ffeeee$e8fge8fe/e$ee dLeDfeed/ge$feEdMdNdOZFee$e8fddPdQdRZGe eje3fe eje3fdSdTdUZHee$e eje3ffee$e eje3ffdVdWdXZIdYdZZJe j ee$e eje3ffejd[d\d]ZKdd_d`ZLe=ddadbZMe=ddcddZNdee$e=dedfdgZOdee$dhdidjZPdee$dhdkdlZQdmdnZRdeSd^fee$ddodpZTddddqdrZUdeeeee$e$ee$e8fdtdudvZVdeeee$e$eWdxdydzZXde*e$ee=eee$e$eYd{d|d}ZZdd~dZ[dddZ\de j ee$e eje3ffe=eee$eeejeejeejfdddZ]ee$e eje3ffdddZ^de=dddZ_dee$ee$ee$ee$ee$ee$ee e$ee$fee e$ee$fee e$ee$fd ddZ`ddZadee$e=e$dddZbde*e$ee=eee$e$eWd{ddZcddZddS)Traineru Trainer is a simple but feature-complete training and eval loop for PyTorch, optimized for 🤗 Transformers. Args: model ([`PreTrainedModel`] or `torch.nn.Module`, *optional*): The model to train, evaluate or use for predictions. If not provided, a `model_init` must be passed. [`Trainer`] is optimized to work with the [`PreTrainedModel`] provided by the library. You can still use your own models defined as `torch.nn.Module` as long as they work the same way as the 🤗 Transformers models. args ([`TrainingArguments`], *optional*): The arguments to tweak for training. Will default to a basic instance of [`TrainingArguments`] with the `output_dir` set to a directory named *tmp_trainer* in the current directory if not provided. data_collator (`DataCollator`, *optional*): The function to use to form a batch from a list of elements of `train_dataset` or `eval_dataset`. Will default to [`default_data_collator`] if no `tokenizer` is provided, an instance of [`DataCollatorWithPadding`] otherwise. train_dataset (`torch.utils.data.Dataset` or `torch.utils.data.IterableDataset`, *optional*): The dataset to use for training. If it is an `datasets.Dataset`, columns not accepted by the `model.forward()` method are automatically removed. Note that if it's a `torch.utils.data.IterableDataset` with some randomization and you are training in a distributed fashion, your iterable dataset should either use a internal attribute `generator` that is a `torch.Generator` for the randomization that must be identical on all processes (and the Trainer will manually set the seed of this `generator` at each epoch) or have a `set_epoch()` method that internally sets the seed of the RNGs used. eval_dataset (`torch.utils.data.Dataset`, *optional*): The dataset to use for evaluation. If it is an `datasets.Dataset`, columns not accepted by the `model.forward()` method are automatically removed. tokenizer ([`PreTrainedTokenizerBase`], *optional*): The tokenizer used to preprocess the data. If provided, will be used to automatically pad the inputs the maximum length when batching inputs, and it will be saved along the model to make it easier to rerun an interrupted training or reuse the fine-tuned model. model_init (`Callable[[], PreTrainedModel]`, *optional*): A function that instantiates the model to be used. If provided, each call to [`~Trainer.train`] will start from a new instance of the model as given by this function. The function may have zero argument, or a single one containing the optuna/Ray Tune/SigOpt trial object, to be able to choose different architectures according to hyper parameters (such as layer count, sizes of inner layers, dropout probabilities etc). compute_metrics (`Callable[[EvalPrediction], Dict]`, *optional*): The function that will be used to compute metrics at evaluation. Must take a [`EvalPrediction`] and return a dictionary string to metric values. callbacks (List of [`TrainerCallback`], *optional*): A list of callbacks to customize the training loop. Will add those to the list of default callbacks detailed in [here](callback). If you want to remove one of the default callbacks used, use the [`Trainer.remove_callback`] method. optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`, *optional*): A tuple containing the optimizer and the scheduler to use. Will default to an instance of [`AdamW`] on your model and a scheduler given by [`get_linear_schedule_with_warmup`] controlled by `args`. preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`, *optional*): A function that preprocess the logits right before caching them at each evaluation step. Must take two tensors, the logits and the labels, and return the logits once processed as desired. The modifications made by this function will be reflected in the predictions received by `compute_metrics`. Note that the labels (second parameter) will be `None` if the dataset does not have them. Important attributes: - **model** -- Always points to the core model. If using a transformers model, it will be a [`PreTrainedModel`] subclass. - **model_wrapped** -- Always points to the most external model in case one or more other modules wrap the original model. This is the model that should be used for the forward pass. For example, under `DeepSpeed`, the inner model is wrapped in `DeepSpeed` and then again in `torch.nn.DistributedDataParallel`. If the inner model hasn't been wrapped, then `self.model_wrapped` is the same as `self.model`. - **is_model_parallel** -- Whether or not a model has been switched to a model parallel mode (different from data parallelism, this means some of the model layers are split on different GPUs). - **place_model_on_device** -- Whether or not to automatically place the model on the device - it will be set to `False` if model parallel or deepspeed is used, or if the default `TrainingArguments.place_model_on_device` is overridden to return `False` . - **is_in_train** -- Whether or not a model is currently running `train` (e.g. when `evaluate` is called while in `train`) r )_get_learning_rate log_metricsmetrics_format save_metrics save_stateN) modelargs data_collator train_dataset eval_dataset tokenizer model_initcompute_metrics callbacks optimizerspreprocess_logits_for_metricsc Cs|dkr(d} tjd| dt| d}||_t|jjd|_d|_d|_t |jj |_ |j j |j } tj| |j|dkr|dk r||_|j}qtdn|dk rtjdt||_t|dr|jr|jrd |_nd|_d|_t|jd kr|jr td |jd%kr td nts2t dnrt!j"|jkr^t#dkr^t dt$j%dnFt!j"|jkrvt!j"|_n.t!j&|jkrt!j&|_nt!j'|jkrt!j'|_|j(|_(|js|js|j)s|j*r|j+ s|jt!j&t!j'gkrd|_(|dkrt,nt-|}|dk r|n||_.||_/||_0||_1|j(rB|j2||j3|jrRd |j_4||_5||_6||_7| |_8| \|_9|_:|dk r|j9dk s|j:dk rtdt;t<|jj=}| dkr|n|| } t>| |j6|j1|j9|j:|_?|j@|jjArtBntCd|_D|jjEr<|jFd dtGr(tHjIdn|jd&kr= 0.3, found zD. Upgrade your fairscale library: `pip install --upgrade fairscale`.zPassing a `model_init` is incompatible with providing the `optimizers` argument. You should subclass `Trainer` and override the `create_optimizer_and_scheduler` method.)at_initz init git repo)exist_okZ collate_batchzRThe `data_collator` should be a simple callable (function, class with `__call__`).zHmax_steps is given, it will override any value given in num_train_epochszGtrain_dataset does not implement __len__, max_steps has to be specifiedzTthe `--group_by_length` option is only available for `Dataset`, not `IterableDatasetautornz3Tried to use `bf16` but native amp is not availableapexzUsing z half precision backend) GradScalerzcUsing FP16 with APEX but APEX is not installed, please refer to https://www.github.com/nvidia/apex.zSageMaker Model Parallelism in mixed precision mode does not support gradient clipping yet. Pass along 'max_grad_norm': 0 in your hyperparameters.)epsilon)is_local_process_zerois_world_process_zeror)loggerinforarr]seedhp_name deepspeed is_in_trainrUZskip_memory_metrics_memory_trackerstartZget_process_log_levelrl set_verbosityZ_setup_devicesrcall_model_init RuntimeErrorwarningswarn FutureWarninghasattrrZmodel_parallelZis_model_parallel sharded_ddplen ValueError local_rankr ImportErrorrTSIMPLEFullyShardedDDPrpr" ZERO_DP_2 ZERO_DP_3place_model_on_devicefp16_full_evalbf16_full_evaldo_trainr&r%rrrr_move_model_to_devicedevice_n_gpu model_wrappedrrr optimizer lr_schedulerDEFAULT_CALLBACKSrZ report_tor3callback_handler add_callback disable_tqdmr5DEFAULT_PROGRESS_CALLBACKZ_loggers_initialized push_to_hub init_git_reporkxm rendezvousdistbarrier should_saveosmakedirsrcallablegetattr max_stepsr[ isinstancetorchutilsdataIterableDatasetgroup_by_length_signature_columnsuse_apexuse_ampfp16bf16Zhalf_precision_backend_is_native_amp_availabledo_grad_scalingfloat16bfloat16 amp_dtyperjsmprnrscalerruZ torch_xla.ampcudarf max_grad_normZlabel_smoothing_factorr>label_smootherr9rrstater8control current_floshp_search_backenduse_tune_checkpointsrd __class__ label_namesZ on_init_endstop_and_update_metrics)selfrrrrrrrrrrrr log_levelZdefault_collatorZdefault_callbacksrZdefault_label_namesr>/usr/local/lib/python3.6/site-packages/transformers/trainer.py__init__s             "     "  "        ( zTrainer.__init__cCs|jj|dS)ac Add a callback to the current list of [`~transformer.TrainerCallback`]. Args: callback (`type` or [`~transformer.TrainerCallback`]): A [`~transformer.TrainerCallback`] class or an instance of a [`~transformer.TrainerCallback`]. In the first case, will instantiate a member of that class. N)rr)rcallbackrrrrs zTrainer.add_callbackcCs |jj|S)aF Remove a callback from the current list of [`~transformer.TrainerCallback`] and returns it. If the callback is not found, returns `None` (and no error is raised). Args: callback (`type` or [`~transformer.TrainerCallback`]): A [`~transformer.TrainerCallback`] class or an instance of a [`~transformer.TrainerCallback`]. In the first case, will pop the first member of that class found in the list of callbacks. Returns: [`~transformer.TrainerCallback`]: The callback removed, if found. )r pop_callback)rrrrrrszTrainer.pop_callbackcCs|jj|dS)a Remove a callback from the current list of [`~transformer.TrainerCallback`]. Args: callback (`type` or [`~transformer.TrainerCallback`]): A [`~transformer.TrainerCallback`] class or an instance of a [`~transformer.TrainerCallback`]. In the first case, will remove the first member of that class found in the list of callbacks. N)rremove_callback)rrrrrrs zTrainer.remove_callbackcCs.|j|}|jjtjkr*t|dr*|jdS)N tie_weights)tor parallel_moder`TPUrr)rrrrrrr#s zTrainer._move_model_to_devicezdatasets.Dataset)dataset descriptionc s|jjs S|jdkrFtj|jj}t|jj |_|jddg7_tt j t |j}t |dkr|dkrvdn d|d}t jd|d|jjjd d j|d d j|d |jjjd fdd|jD}tjtjtjdkrjjd|jddSj|SdS)Nlabel label_idsrzin the z set zThe following columns z) don't have a corresponding argument in `z!.forward` and have been ignored: z, z. If z are not expected by `z/.forward`, you can safely ignore this message.csg|]}|jkr|qSr) column_names).0k)rrr =sz2Trainer._remove_unused_columns..z1.4.0type format_kwargs)rcolumnsr)rZremove_unused_columnsrinspect signaturerZforwardlist parameterskeyssetrrrrr__name__joinrparsedatasetsr"Z set_formatformatZremove_columns)rrrrZignored_columnsZdset_descriptionrr)rr_remove_unused_columns)s"  >zTrainer._remove_unused_columns)returnc Cs|jdkst|j rdSd}|jjdkrrtrrtj}|jjdkr`ttj ftj dj j }n|jj}|j ||jjdk r|jjn|jj}|jjrJtrt|jtjr|jj|jjkr|j|jjnd}nd}|jdk r|jjdnd}|jjdkrt|jj|jj|j|||dSt|jj|jj|j|jj|jj|||dSn|jjdkrvtrlt|j|dSt|jS|jjtj tj!gkr|jj" rt#|j|jj$|jj|jj|dSt%|j|jj|jj|dSdS) Nr )dtyper)rlengthsmodel_input_name generator)r num_replicasrankr r r)r) batch_sizerrr)rrr)&rr[r world_size_is_torch_generator_availabler GeneratorZ data_seedintemptyint64Zrandom_itemZ manual_seedrrrgrrrZlength_column_namerrZmodel_input_namesr?train_batch_sizegradient_accumulation_stepsr: process_indexrrr`rZSAGEMAKER_MODEL_PARALLELdataloader_drop_lastr;per_device_train_batch_sizer )rrrr r rrr_get_train_samplerGs`      zTrainer._get_train_samplerc Cs|jdkrtd|j}tr8t|tjr8|j|dd}t|tjj j r|j j dkrvt ||j j|j j|j j |j jd}t||j j|j|j j|j jdS|j}t||j j||j|j j|j j|j jdS) a@ Returns the training [`~torch.utils.data.DataLoader`]. Will use no sampler if `train_dataset` does not implement `__len__`, a random sampler (adapted to distributed training if necessary) otherwise. Subclass and override this method if you want to inject some custom behavior. Nz+Trainer: training requires a train_dataset.training)rr )r drop_last num_processesr)r collate_fn num_workers pin_memory)rsamplerr"r r#r$)rrrgrrrr rrrrrrr=rrrrrrdataloader_num_workersdataloader_pin_memoryr)rrZ train_samplerrrrget_train_dataloaders8    zTrainer.get_train_dataloader)rr cCs|jjrbtr$t|tjtjdStrFt|tj tj |jj dS|jj dkrZt|St |S|jjdkrvt |St||jj |jj|jjdSdS)N)rr)rrrr )rr!rr)ruse_legacy_prediction_looprkr@rxrt_world_sizeZ get_ordinalrjrZdp_sizeZdp_rankper_device_eval_batch_sizerrrrAr)rrrrr_get_eval_samplers(   zTrainer._get_eval_samplerc Cs|dkr|jdkrtd|dk r&|n|j}trLt|tjrL|j|dd}t|tjj j r|j j dkrt ||j j|j j|j j |j jd}t||j j|j|j j|j jdS|j|}t|||j j|j|j j|j j|j jdS) a Returns the evaluation [`~torch.utils.data.DataLoader`]. Subclass and override this method if you want to inject some custom behavior. Args: eval_dataset (`torch.utils.data.Dataset`, *optional*): If provided, will override `self.eval_dataset`. If it is an `datasets.Dataset`, columns not accepted by the `model.forward()` method are automatically removed. It must implement `__len__`. Nz-Trainer: evaluation requires an eval_dataset.Z evaluation)rr )rr r!r)rr"r#r$)r%rr"r r#r$)rrrgrrrr rrrrrrr=r+rrreval_batch_sizerr&r'r,)rrZ eval_samplerrrrget_eval_dataloaders8     zTrainer.get_eval_dataloader) test_datasetr cCstr t|tjr |j|dd}t|tjjjr~|j j dkr^t ||j j |j j |j j |j jd}t||j j |j|j j|j jdS|j|}t|||j j |j|j j |j jdS)a Returns the test [`~torch.utils.data.DataLoader`]. Subclass and override this method if you want to inject some custom behavior. Args: test_dataset (`torch.utils.data.Dataset`, *optional*): The test dataset to use. If it is an `datasets.Dataset`, columns not accepted by the `model.forward()` method are automatically removed. It must implement `__len__`. test)rr )rr r!r)rr"r#r$)r%rr"r r$)rgrrrr rrrrrrr=r-rrrrr&r'r,)rr/Z test_samplerrrrget_test_dataloader s0     zTrainer.get_test_dataloader)num_training_stepscCs|j|j||jddS)aZ Setup the optimizer and the learning rate scheduler. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the Trainer's init through `optimizers`, or subclass and override this method (or `create_optimizer` and/or `create_scheduler`) in a subclass. )r2rN)create_optimizercreate_schedulerr)rr2rrrcreate_optimizer_and_scheduler5sz&Trainer.create_optimizer_and_schedulercs|jdkrt|jtjgddDfdd|jjD|jjdfdd|jjDddg}tj |j\}}|j t j krt f||d||_n||f||_trtj|j|_|jS) a Setup the optimizer. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the Trainer's init through `optimizers`, or subclass and override this method in a subclass. NcSsg|]}d|kr|qS)Zbiasr)rnamerrrrIsz,Trainer.create_optimizer..csg|]\}}|kr|qSrr)rnp)decay_parametersrrrLs)params weight_decaycsg|]\}}|kr|qSrr)rr7r8)r9rrrPsg)r:optim)rrErrZ LayerNormZnamed_parametersrr;rzget_optimizer_cls_and_kwargsrrTrrtrjrZDistributedOptimizer)rZoptimizer_grouped_parameters optimizer_clsoptimizer_kwargsr)r9rr3@s"     zTrainer.create_optimizer)rr c Cs@d|ji}|j|jf|jd}|jtjkr@t}|jdddn|jtj krhddl m }|}|j|n|jtj krddl m }|}|j|n|jtjkryddlm }|}|j|Wntk rtdYnXn^|jtjkr(ydd lm}|}|j|Wntk r$td YnXntd |j||fS) z Returns the optimizer class and optimizer parameters based on the training arguments. Args: args (`transformers.training_args.TrainingArguments`): The training arguments for the training session. lr)ZbetasZepsF)Zscale_parameterZ relative_stepr )AdamWrz7Trainer failed to import syncfree AdamW from torch_xla.) FusedAdamzFTrainer tried to instantiate apex FusedAdam but apex is not installed!z2Trainer cannot instantiate unsupported optimizer: ) learning_rateZ adam_beta1Z adam_beta2Z adam_epsilonr<r_Z ADAFACTORr0updateZADAMW_HF optimizationrAZ ADAMW_TORCHZ torch.optimZADAMW_TORCH_XLAZtorch_xla.amp.syncfreerrZADAMW_APEX_FUSEDZapex.optimizersrB)rr?Z adam_kwargsr>rArBrrrr=es<             z$Trainer.get_optimizer_cls_and_kwargs)r2rcCs<|jdkr6t|jj|dkr |jn||jj||d|_|jS)z Setup the scheduler. The optimizer of the trainer must have been set up either before this method is called or passed as an argument. Args: num_training_steps (int): The number of training steps to do. N)rZnum_warmup_stepsr2)rr1rZlr_scheduler_typerZget_warmup_steps)rr2rrrrr4s   zTrainer.create_scheduler) dataloaderr c Cs6y t|jStttfk r0t||jjSXdS)z Helper to get number of samples in a [`~torch.utils.data.DataLoader`] by accessing its dataset. When dataloader.dataset does not exist or has no length, estimates as best it can N)rr NameErrorAttributeError TypeErrorrr)rrFrrr num_exampless zTrainer.num_examplesz optuna.Trial)trialcCsn||_|jdks|dkrdS|jtjkr4|j|}nP|jtjkrR|}|jddn2|jtjkrtdd|jj D}n|jtj kr|}xd|j D]X\}}t |j |st jd|dqt|j |d}|dk rt||}t|j ||qW|jtjkrt jd|j|jtjkr&t jd|j|jtj krDt jd ||j jrjd d lm}||j j|j _dS) zHP search setup codeNwandbcSs(i|] \}}t|trt|n||qSr)rstrr)rrvrrr sz,Trainer._hp_search_setup..zTrying to set zY in the hyperparameter search but there is no corresponding field in `TrainingArguments`.zTrial:zSigOpt Assignments: zW&B Sweep parameters: r)HfDeepSpeedConfig)Z_trialrrPOPTUNAhp_spaceRAYpopSIGOPT assignmentsitemsWANDBrrrwarningrrsetattrrr:rZtransformers.deepspeedrPhf_deepspeed_config)rrKr:keyvalueold_attrrPrrr_hp_search_setups<         zTrainer._hp_search_setup)rKepochmetricscCs|jdks|dkrdS|j|j|_|jtjkrpddl}|j|j||jr|j j |j |j |j |jn>|jtjkrddlm}|j jr|j|jfd|ji|dS)Nr)tune objective)rcompute_objectivecopyrcrPrQoptunareportZ should_pruner on_train_endrrrZ TrialPrunedrSrayrbr_tune_save_checkpoint)rrKr`rarfrbrrr_report_to_hp_searchs    zTrainer._report_to_hp_searchc Csddlm}|jsdS|j|jjd}tjj|t d|jj}|j |dd|j j r|jj tjj|ttj|jjtjj|ttj|jjtjj|tWdQRXdS)Nr)rb)step-T)_internal_call)rirbrcheckpoint_dirr global_steprpathrrL save_modelrr save_to_jsonTRAINER_STATE_NAMErsaver state_dictOPTIMIZER_NAMErSCHEDULER_NAME)rrbrorrrrrjs zTrainer._tune_save_checkpointcCsLt|j}|dkr|j}n|dkr0|j|}ntd|dkrHtd|S)Nrr z'model_init should have 0 or 1 argument.z"model_init should not return None.)r\rr)rrKZmodel_init_argcountrrrrrs   zTrainer.call_model_initTcCstr.t|jtjjr|jStj||jjdS|jr:|jSt ||k rJ|S|j rp|rpt j ||j |jjd\}|_ |jjdkrtj|}|s|S|jdk r|jtjkrt||j }n`|jjp|jj}tj|jjk}|jtjk}tj|jjkrt|}t||||dj|jj|_}ntr}|} | |j8}|j8| }ntd|j8t?j@|jjAkr |jjBdkrtdn tC|j}|jDdk r:|jDtEjFkp>tG}|j+r~tH|||d\}}}|jI|_||_0||_+||_||_n|s|jJ|dtK|_L|dk |jL_M|jNr|jjO|jP|j0}||jk r||_0|r|jJ|d|jQ|t#j$dt#j$d|t#j$d|t#j$d|jRt#j$d| t#j$d|j3t#j$d|d|jL_StTjT}d}d}d}|dk rXtj j!tj j|tUrXtKjVtj j|tU|_L|jLjW| }|jXs|jLjW| }||j39}nd}t#j$d t#j$d!|t#j$d"|jLjW|jXsXt#j$d#|d$|d%|jYrX|jZ rXt[|d&}|j\d'|j|j]_|j|j]_|j|j]_| |j]_^|j_dk r|j_|nd|jL_`|dk r|jatbjckr|jdn|}te||jL_fnd|jL_f||jL_8||jL_<|jY|jL_Y|jg|jL_gt,jhd(ji|j }d(|_j|jLjW|_k|jl|j]jm||jL|jn|_n|jXsxhto|D]\}tp| d)oht| jqtr}tsjtt,j)tsjtd*ks| rx| D]} PqWn t| jq} qNWxto||D]}t| turt| jqtvr| jqjw|n&tp| d+rt| jxtyr| jxjw|tzr6t{j|| |j gj}|j }!|!}"n| }"|j~dkrLd|_| dk r^t|"n |j8|j3}#|j]j||jL|jn|_ndB}$x~t|"D]p\}$}%|dkr|d8}|dk r|jd|dkr|j|qn|dk r|jd}|$|j3dkr|j]j||jL|jn|_n|$d|j3dkr`|jdCkr`|jr`|j|j||%}&WdQRXn |j||%}&|jrtz rt,j|&st,j|&r||d|jLjW|jk7}n||&7}|jt|j|%7_|j+r|j+j|$d|j3dk s|#|j3k r|$d|#k r|jdk r|jdk r|j+ r|j rvtz rhtj|j}'tjd,|'d-tjd.|jj|jtp|jd/ r|jj|jnBtp|d0 r|j|jn(tjj|j rtj|jn|j|jd}(|j+ rntz r|j r|jj|j|jjn tj|jnH|j rZ|jj})|jj|j|jj|jj}*|)|*k}(n |jj|( r~|j+ r~|jj|jl|jLjWd7_W||$d|#|jL_S|j]j||jL|jn|_n|j|||||n|j]j||jL|jn|_n|jnj s|jnjrPqW|$dk r4t#j*d1|jLjWd2|d3d|jn_|j]j||jL|jn|_n|j|||||t?j|jjAk rtz rtjtjn t#j*d4|jnjrPqW|j~ rtp|d5 rt|d5t#j$d6|j r|jLjdk rtz rtjd7n|jdDk rtjt#j$d8|jLjd9|jLjdtj j|jLjt"}+tj j|+ r|j+ rt|\}}}|jI|_||_0||_+||_||_|j+j|jLjddd:nt,j-|+dd} |j.| nt#j*d;|+d<|jj|j7_j|jj|jLjW},td=|||jLj8d>}-|j|jLj|-d?<|,|-d@<d |_|jj|-|j|-|j]j||jL|jn|_nt|jLjW|,|-S)Ea Main training entry point. Args: resume_from_checkpoint (`str` or `bool`, *optional*): If a `str`, local path to a saved checkpoint as saved by a previous instance of [`Trainer`]. If a `bool` and equals `True`, load the last checkpoint in *args.output_dir* as saved by a previous instance of [`Trainer`]. If present, training will resume from the model/optimizer/scheduler states loaded here. trial (`optuna.Trial` or `Dict[str, Any]`, *optional*): The trial run or the hyperparameter dictionary for hyperparameter search. ignore_keys_for_eval (`List[str]`, *optional*) A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions for evaluation during the training. kwargs: Additional keyword arguments used to hide deprecated arguments NTZ model_pathzi`model_path` is deprecated and will be removed in a future version. Use `resume_from_checkpoint` instead.rz3train() received got unexpected keyword arguments: z, .Fz/No valid checkpoint found in output directory ()z!Can't find a valid checkpoint at zLoading model from z).z9You are resuming training from a checkpoint trained with z- of Transformers but your current version is zJ. This is not recommended and could yield to errors or unwanted behaviors.cpu) map_locationr zYargs.max_steps must be set to a positive value if dataloader does not have a length, was zjCurrently --debug underflow_overflow is not supported under DP. Please use DDP (torch.distributed.launch).)r2r)r2z***** Running training *****z Num examples = z Num Epochs = z( Instantaneous batch size per device = zE Total train batch size (w. parallel, distributed & accumulation) = z Gradient Accumulation steps = z Total optimization steps = zE Continuing training from checkpoint, will skip to saved global_stepz! Continuing training from epoch z' Continuing training from global step z Will skip the first z epochs then the first z batches in the first epoch. If this takes a lot of time, you can add the `--ignore_data_skip` flag to your launch command, but you will resume the training on data already seen by your model.)totalzSkipping the first batchesgr%z1.11rsumg?)scaleclip_grad_normclip_grad_norm_zXThere seems to be not a single sample in your epoch_iterator, stopping training at step zI! This is expected if you're using an IterableDataset and set num_steps (z.) higher than the number of available samples.zYou enabled PyTorch/XLA debug metrics but you don't have a TPU configured. Check your training configuration if this is unexpected._pastzU Training completed. Do not forget to share your model on huggingface.co/models =) load_best_model_at_endzLoading best model from z (score: )Zload_optimizer_statesZload_lr_scheduler_statesz#Could not locate the best model at zi, if you are running a distributed training on multiple nodes, you should activate `--save_on_each_node`.train) num_samples num_steps total_flos train_loss)NNrrr)rrrrrrrrrrrTrrrrrIrrrr_rr]rrrrrboolrZrrrrqisfilercrrrbr#Zfrom_json_fileZtransformers_versionr"rYrrload_load_state_dict_in_modelrrr(rrrr[maxrJrrmathceilnum_train_epochssysmaxsizer'ZUNDERFLOW_OVERFLOWdebugr}r(rrTrrjr)moduler5r9rZis_hyper_param_searchZgradient_checkpointingZgradient_checkpointing_enabler_load_optimizer_and_schedulerrr`timertZload_from_jsonrpZignore_data_skiprrr set_descriptionrtrain_dataloaderrZ trial_namerrPrUrVrZ trial_paramsrtensorr_total_loss_scalar_globalstep_last_loggedZ zero_gradZon_train_beginrrangerr%rrrrr Z set_epochrr=rkplParallelLoaderper_device_loader past_indexrZon_epoch_begin enumeraterD_load_rng_statecloseZ on_step_beginrZ!_no_sync_in_gradient_accumulationZno_sync training_stepZlogging_nan_inf_filterisnanisinfrfloatfloating_point_opsrlrrrZ_fetch_gradientsZ all_reducer*rZunscale_rrrrrrnZ master_paramsrZoptimizer_stepZ get_scaleZ on_step_end_maybe_log_save_evaluateZon_substep_endZshould_epoch_stopZshould_training_stopZ on_epoch_endTPU_METRICS_DEBUG master_printmetmetrics_reportdelattrrbest_model_checkpointrrr best_metricexistsr*Zload_checkpointrr^ store_flosrrlogrhrV).rrrKrrrZmodel_reloadedconfigZcheckpoint_versionrvrZtotal_train_batch_sizeZlen_dataloaderZnum_update_steps_per_epochrJrrZnum_train_samplesZdebug_overflowZdelay_optimizer_creationdeepspeed_enginerrr start_timeZepochs_trainedZsteps_trained_in_current_epochZsteps_trained_progress_barrVtr_lossr`Zis_random_sampler_parallel_loaderZepoch_iteratorZsteps_in_epochrlinputsZ tr_loss_stepZ gradientsZoptimizer_was_runZ scale_beforeZ scale_afterZbest_model_pathrrarrrrOs0                                                                  "                   z Trainer.traincCs|jj|dd}t|jdkr`|jjdk rLt|jt|jjkrL|jjntjd|jdt|j dkrtjd|j ddS)NF)strictrz8There were missing keys in the checkpoint model loaded: rz;There were unexpected keys in the checkpoint model loaded: ) rload_state_dictrZ missing_keysZ_keys_to_ignore_on_saverrrrYZunexpected_keys)rrvZ load_resultrrrr1s  z!Trainer._load_state_dict_in_modelc Cs|jjrtrtji}|j|jj}||8}t||j j |j d|d<|j |d<|j |7_ |j j |_ |j|j|d}|jjr|j|d}|j||||jjr|j|||d|jj|j|j |j|_dS)NlossrC) ignore_keys)ra)rZ should_logrkr mark_step_nested_gathermeanrroundrrprr{rrrZshould_evaluateevaluaterkr_save_checkpointrZon_saver) rrrrKr`rlogsZtr_loss_scalarrarrrr@s&    z Trainer._maybe_log_save_evaluatecCsd|dkr dStrtjn|jj}|dkrntjj|d|d}tjjtjj||st j d|ddSn(tjj|d}tjj|st j ddSt j |}t j|dtj j|d t j j|d t jjrJ|jjdkrt jj j|d nNyt jj j|d Wn6tk rH}zt j d |d WYdd}~XnXtr`tj|ddS)Nr rng_state_z.pthz$Didn't find an RNG file for process zr, if you are resuming a training that wasn't launched in a distributed fashion, reproducibility is not guaranteed.z rng_state.pthzDidn't find an RNG file, if you are resuming a training that was launched in a distributed fashion, reproducibility is not guaranteed.pythonnumpyrrzUDidn't manage to set back the RNG states of the GPU because of the following error: zO This won't yield the same results as if the training had not been interrupted.xlarr)rkrget_local_ordinalrrrrqrrrrrrrandomsetstatenpZ set_stateZ set_rng_stater is_availableZset_rng_state_all Exception)r checkpointrZrng_fileZcheckpoint_rng_stateerrrr_s8    zTrainer._load_rng_statecCsdtd|jj}|jdk r|dk r|jtjkr8|j}nR|jtjkrZddlm }|j }n0|jtj krn|j }n|jtj krddl}|jj }|jdk r|j|nd|}tjj|jj|} n|jj} |jtjj| |} |j| dd|jr|jj| |jtjkr|jjtrt j!dt j"|jj#tjj| t$t%j&dd*} t j"|j'j#tjj| t(t)| WdQRXn2t*r"t+j,dkr|jj#} |jj-rt.j"| tjj| t$t%j&dd"} t.j"|j'j#tjj| t(WdQRXt)| |j/rt.j"|j0j#tjj| t1n|jj-r|j rt.j"|jj#tjj| t$t%j&dd"} t.j"|j'j#tjj| t(WdQRXt)| |j/rt.j"|j0j#tjj| t1|dk rB|jj2dk rB|jj2} | j3d sd | } || }|jj4rt5j6nt5j7}|jj8dks2|jj9dks2|||jj8rB||j_8| |j_9|jj-rb|jj:tjj| t;tt.j To use this method, you need to have provided a `model_init` when initializing your [`Trainer`]: we need to reinitialize the model at each new run. This is incompatible with the `optimizers` argument, so you need to subclass [`Trainer`] and override the method [`~Trainer.create_optimizer_and_scheduler`] for custom optimizer/scheduler. Args: hp_space (`Callable[["optuna.Trial"], Dict[str, float]]`, *optional*): A function that defines the hyperparameter search space. Will default to [`~trainer_utils.default_hp_space_optuna`] or [`~trainer_utils.default_hp_space_ray`] or [`~trainer_utils.default_hp_space_sigopt`] depending on your backend. compute_objective (`Callable[[Dict[str, float]], float]`, *optional*): A function computing the objective to minimize or maximize from the metrics returned by the `evaluate` method. Will default to [`~trainer_utils.default_compute_objective`]. n_trials (`int`, *optional*, defaults to 100): The number of trial runs to test. direction(`str`, *optional*, defaults to `"minimize"`): Whether to optimize greater or lower objects. Can be `"minimize"` or `"maximize"`, you should pick `"minimize"` when optimizing the validation loss, `"maximize"` when optimizing one or several metrics. backend(`str` or [`~training_utils.HPSearchBackend`], *optional*): The backend to use for hyperparameter search. Will default to optuna or Ray Tune or SigOpt, depending on which one is installed. If all are installed, will default to optuna. kwargs: Additional keyword arguments passed along to `optuna.create_study` or `ray.tune.run`. For more information see: - the documentation of [optuna.create_study](https://optuna.readthedocs.io/en/stable/reference/generated/optuna.study.create_study.html) - the documentation of [tune.run](https://docs.ray.io/en/latest/tune/api_docs/execution.html#tune-run) - the documentation of [sigopt](https://app.sigopt.com/docs/endpoints/experiments/create) Returns: [`trainer_utils.BestRun`]: All the information about the best run. NzAt least one of optuna or ray should be installed. To install optuna run `pip install optuna`. To install ray run `pip install ray[tune]`. To install sigopt run `pip install sigopt`.zQYou picked the optuna backend, but it is not installed. Use `pip install optuna`.zXYou picked the Ray Tune backend, but it is not installed. Use `pip install 'ray[tune]'`.zQYou picked the sigopt backend, but it is not installed. Use `pip install sigopt`.zOYou picked the wandb backend, but it is not installed. Use `pip install wandb`.zXTo use hyperparameter search, you need to pass your model through a model_init function.)rrrPrQrrSrrUrrXrrrrXrRrrWrdrrrr) rrRrdrrrrrZ backend_dictZbest_runrrrhyperparameter_search!s:4  zTrainer.hyperparameter_search)rr cCsZ|jjdk rt|jjd|d<|d|jji}|jjj||jj|j|j|j ||_ dS)z Log `logs` on the various objects watching training. Subclass and override this method to inject custom behavior. Args: logs (`Dict[str, float]`): The values to log. Nr`rl) rr`rrpZ log_historyappendrZon_logrr)rroutputrrrr~s z Trainer.log)rr cst|tr(t|fdd|jDSt|ttfrPt|fdd|DSt|tjrtj j d}j r|j tj kr|jtj jj d|jf|S|S)z| Prepares one `data` before feeding it to the model, be it a tensor or a nested list/dictionary of tensors. csi|]\}}j||qSr)_prepare_input)rrrN)rrrrOsz*Trainer._prepare_input..c3s|]}j|VqdS)N)r)rrN)rrr sz)Trainer._prepare_input..)r)r )rrrrWtuplerrTensordictrrrr rrDr[r)rrrr)rrrs   zTrainer._prepare_input)rr cCsR|j|}t|dkr.tddj|jd|jjdkrN|jdk rN|j|d<|S)z Prepare `inputs` before feeding them to the model, converting them to tensors if they are not already and handling potential state. rzThe batch received was empty, your model won't be able to train on it. Double-check that your training dataset contains keys expected by the model: ,rNZmems)rrrrrrrr)rrrrr_prepare_inputss   zTrainer._prepare_inputscCsP|jr2tjtjtjdkr*t|jd}qLt}ntjdkrDt j nt j }|S)z A helper wrapper that creates an appropriate context manager for `autocast` while feeding it the desired arguments, depending on the situation. z1.10)r )rr) rrrrr"rorr version_info contextlibZ nullcontextsuppress)rZ ctx_managerrrrautocast_smart_context_managers z&Trainer.autocast_smart_context_manager)rrr cCs |j|j|}trR|jr$|jnd}t|||jj|d}|jj j |jj S|j |j ||}WdQRX|jjdkr|j}|jjdkr|j r||jj}|jr|jj|jnF|jrtj||j}|jWdQRXn|jr|jj|}n|j|j S)aq Perform a training step on a batch of inputs. Subclass and override to inject custom behavior. Args: model (`nn.Module`): The model to train. inputs (`Dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of the model. The dictionary will be unpacked before being fed to the model. Most models expect the targets under the argument `labels`. Check your model's documentation for all accepted arguments. Return: `torch.Tensor`: The tensor with training loss on this batch. N)rr )rrrjrrrvrr reduce_meandetachrrr compute_lossr}rrrZbackwardrrnZ scale_lossr)rrrrloss_mbrZ scaled_lossrrrrs*    zTrainer.training_stepFcCs|jdk rd|kr|jd}nd}|f|}|jjdkrF||jj|_|dk r\|j||}nt|trn|dn|d}|r||fS|S)z How the loss is computed by Trainer. By default, all models return the loss in the first element. Subclass and override for custom behavior. Nlabelsrr)rrTrrrrr)rrrreturn_outputsroutputsrrrrrs   zTrainer.compute_losscCs |jjdkS)z Whether or not this process is the local (e.g., on one machine if training in a distributed fashion on several machines) main process. r)rZlocal_process_index)rrrrr szTrainer.is_local_process_zerocCs"trtjdkS|jjdkSdS)z Whether or not this process is the global main process (when training in a distributed fashion on several machines, this is only going to be `True` for one process). rN)rjrrrr)rrrrrs zTrainer.is_world_process_zero)rrncCs.|dkr|jj}tr"|j|ntrJ|jj}|jjrH|j||dnt j |jj ksft j |jj kr|j j}|jjr|j||dn|jr|jjr|j|tr|jjrtjj|t}tjj|rtj||jj|tstjd|jj|n|jjr |j||jjr*| r*|jdddS)z Will save the model, so you can reload it using `from_pretrained()`. Will only save from the main process. N)rvzdeepspeed.save_16bit_model didn't save the model, since stage3_gather_16bit_weights_on_model_save=false. Saving the full checkpoint instead, use zero_to_fp32.py to recover weightsz Model save)commit_message)rrrk _save_tpurjrrvr_saverTrrrrrr+rrqrrcrremoveZsave_16bit_modelrrYrr)rrrnrvfilerrrrrs8        zTrainer.save_model)rcCs|dk r |n|jj}tjd|tjrRtj|ddtj |jtj j |t tj dt|jtstt|jtrt|jj||jj|jjtj dqtjd|jj}tj |tj j |tn|jj||jjtj d|jdk o|jjr|jj|dS)NzSaving model checkpoint to T)rZsaving_checkpoint) save_configrv save_functionzETrainer.model is not a `PreTrainedModel`, only saving its state dict.)rr)rrrrrZis_master_ordinalrrrrurqrTRAINING_ARGS_NAMErrrr.r/save_pretrainedrrvrcr)rrrvrrrr Vs&      zTrainer._save_tpucCs|dk r |n|jj}tj|ddtjd|t|jtstt |jtrv|dkr`|jj }t |jj ||dqtjd|dkr|jj }t j |tjj|tn|jj ||d|jdk r|jj |t j |jtjj|tdS)NT)rzSaving model checkpoint to )rvzETrainer.model is not a `PreTrainedModel`, only saving its state dict.)rrrrrrrrr.r/rvrrrurqrrcrr)rrrvrrrr rs       z Trainer._savecCsX|jjdkr<|jjt|jg|jjdjj7_d|_n|jj|j7_d|_dS)Nr )rrr) rrrrrBrrrr)rrrrrs   zTrainer.store_flosc Cs g}ddt|j|dD}xj|D]b}|rH|jtjj||fq(tjd|d|}|dk r(|jdk r(|jt |jd|fq(Wt |}dd|D}|j j dk r|j tt|j j } x.z-*z.*z -([0-9]+)rcSsg|] }|dqS)r r)rrrrrrsrr )rglobrrrqgetmtimerematchgroupsrsortedrrindexrMrr) rrZcheckpoint_prefixrZordering_and_checkpoint_pathZglob_checkpointsrqZ regex_matchcheckpoints_sortedZbest_model_indexirrr_sorted_checkpointss &zTrainer._sorted_checkpointscCs|jjdks|jjdkrdS|j||d}t||jjkr>dS|jj}|jjdk rr|jjdkrr|d|jjkrrd}tdt||}|d|}x(|D] }tjd|dt j |qWdS)Nr)rrr rzDeleting older checkpoint [z] due to args.save_total_limitr) rsave_total_limitrrrrrrrshutilrmtree)rrrrrZnumber_of_checkpoints_to_deleteZcheckpoints_to_be_deletedrrrrrs    zTrainer._rotate_checkpointseval)rrmetric_key_prefixr c Cs|jj|j|}tj}|jjr*|jn|j}||d|jdkrDdnd||d}|jj |jj }|j j t |||jtj|j|d|j|j tj|jjkrtjtj|jj|j|j|j|j |_|jj|j |j S)a$ Run evaluation and returns metrics. The calling script will be responsible for providing a method to compute metrics, as they are task-dependent (pass it to the init `compute_metrics` argument). You can also subclass and override this method to inject custom behavior. Args: eval_dataset (`Dataset`, *optional*): Pass a dataset if you wish to override `self.eval_dataset`. If it is an `datasets.Dataset`, columns not accepted by the `model.forward()` method are automatically removed. It must implement the `__len__` method. ignore_keys (`Lst[str]`, *optional*): A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions. metric_key_prefix (`str`, *optional*, defaults to `"eval"`): An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named "eval_bleu" if the prefix is "eval" (default) Returns: A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The dictionary also contains the epoch number which comes from the training state. Z EvaluationNT)rprediction_loss_onlyrr#)rr)rrr.rrr)prediction_loopevaluation_looprr-rrarDr^rrrrr'rrrrrrrZ on_evaluaterrr) rrrr#eval_dataloaderr eval_looprtotal_batch_sizerrrrs.   zTrainer.evaluater0)r/rr#r c Cs|jj|j|}tj}|jjr*|jn|j}||d||d}|jj|jj }|j j t |||j tj|j |d|jj|j t|j|j|j dS)a Run prediction and returns predictions and potential metrics. Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method will also return metrics, like in `evaluate()`. Args: test_dataset (`Dataset`): Dataset to run the predictions on. If it is an `datasets.Dataset`, columns not accepted by the `model.forward()` method are automatically removed. Has to implement the method `__len__` ignore_keys (`Lst[str]`, *optional*): A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions. metric_key_prefix (`str`, *optional*, defaults to `"test"`): An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named "test_bleu" if the prefix is "test" (default) If your predictions or labels have different sequence length (for instance because you're doing dynamic padding in a token classification task) the predictions will be padded (on the right) to allow for concatenation into one array. The padding index is -100. Returns: *NamedTuple* A namedtuple with the following keys: - predictions (`np.ndarray`): The predictions on `test_dataset`. - label_ids (`np.ndarray`, *optional*): The labels (if the dataset contained some). - metrics (`Dict[str, float]`, *optional*): The potential dictionary of metrics (if the dataset contained labels). Z Prediction)rrr#)rr) predictionsrra)rrr1rrr)r%r&r-rrarDr^rrrrrSr*r) rr/rr#Ztest_dataloaderrr(rr)rrrpredict s$  zTrainer.predict)rFrr$rr#r cCs@|j}|dk r|n|j}|jrP|j rPt|dddd\}}}|j|_||_||_|j|jdd} |js|j r| j t j |j d} n|jr| j t j|j d} |jj} tjd|d t|rtjd |j|n tjd tjd | | j||j_t|d d} tr(tj||j gj|j }|jdkr:d|_d} d} d}d}d}d}d}xt|D]\}}t |}|dk r||7}| dkr|} |j!| |||d\}}}trt"j#|dk r|j$|j%| }| dkr|nt j&| |fdd} |dk r0|j'|}|j$|}|dkr"|n t(||dd}|dk r|j'|}|j$|}|j)dk rf|j)||}| dkrt|n t(| |dd} |jj*||j+|j,|_,|j-dk rb|d|j-dkrb| dk rt.| }|dkr|nt/j0||fdd}| dk rt.| }|dkr |n t(||dd}|dk rFt.|}|dkr8|n t(||dd}d\} } }qbW|jrtt1|drtt2|d| dk rt.| }|dkr|nt/j0||fdd}| dk rt.| }|dkr|n t(||dd}|dk rt.|}|dkr|n t(||d d}t| rt3| }n:t4| t5r6t1| dr6| j}nt|rL|j|}n|}|dk rf|d|}|dk rzt6||}|dk rt6||}|j7dk r|dk r|dk r|j7t8||d}ni}t9|}|dk r|j:j;||d<x@t<|j=D]0}|j>|ds|j?|||d|<qWt@||||dS)!z Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`. Works both with or without labels. NrT)r2rZ inferenceF)r)r rz***** Running z *****z Num examples = z Num examples: Unknownz Batch size = r)r)dimd) padding_indexr )ZaxisrrJ)r*r_lossr)r*rrariiii)NNNii)Arr$rr)rrrrrrrrrrrrr+rrr[rJr"rr'rrkrrrrrrrDprediction_steprrrrepeatcat_pad_across_processesrFron_prediction_steprreval_accumulation_stepsrHrZ concatenaterrrrr=rIrrOrYrrrrrrTrN)rrFrr$rr#rrrrrr losses_host preds_host labels_hostZ all_lossesZ all_predsZ all_labelsZobserved_num_examplesrlrZobserved_batch_sizerlogitsrlossesrrar\rrrr&G s                                      zTrainer.evaluation_loopcCsR|dkr dStr*|dkrd}t||}n$tr:t|}n|jjdkrNt|}|S)z Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before concatenating them to `gathered` NZ nested_gatherr r)rkrJrjrxrrrC)rtensorsr6rrrr s   zTrainer._nested_gatherr-c st|ttfr*t|fdd|DSt|trTt|fdd|jDSt|tjsttdt|dt |j dkr|Stj |j |j dd }j |j}td d|D}|j d |kr|S|j }t|}||d <|jt|}||d d d |d f<|S) z Recursively pad the tensors in a nested list/tuple/dictionary of tensors from all devices to the same size so they can safely be gathered. c3s|]}j|dVqdS)) pad_indexN)r3)rt)r<rrrr sz0Trainer._pad_across_processes..cs i|]\}}j|d|qS))r<)r3)rrrN)r<rrrrO sz1Trainer._pad_across_processes..zCan't pad the values of type z-, only of nested list/tuple/dicts of tensors.r)rNcss|]}|dVqdS)r Nr)rsrrrr sr )rrrrrrWrrrIrshaperrrrrZ new_zeros) rrr<sizesizesmax_sizeZold_sizeZnew_sizeZ new_tensorr)r<rrr3 s(   zTrainer._pad_across_processes)rrr$rr c s`tfdd|jD}|jdkrLt|jdrHt|jjdgng|rttfdd|jD}t |dkr|d}nd}t j t r@t |}|rt|tr|d }tfd d|jD} n|d}|dd} |jjj} t| } n8d} t|tr2tfd d|jD} n|} t| } n|r|j|j|d d \} } WdQRX| jj} t| trtfdd| jD} n | dd} nnd} |j|f} WdQRXt| trtfdd| jD} n| } |jjdkr| |jjd|_WdQRX|r8| ddfSt| } t | dkrV| d} | | |fS)a Perform an evaluation step on `model` using `inputs`. Subclass and override to inject custom behavior. Args: model (`nn.Module`): The model to evaluate. inputs (`Dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of the model. The dictionary will be unpacked before being fed to the model. Most models expect the targets under the argument `labels`. Check your model's documentation for all accepted arguments. prediction_loss_only (`bool`): Whether or not to return the loss only. ignore_keys (`Lst[str]`, *optional*): A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions. Return: Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]: A tuple with the loss, logits and labels (each being optional). c3s|]}j|dk VqdS)N)get)rr)rrrrH sz*Trainer.prediction_step..NrZkeys_to_ignore_at_inferencec3s|]}j|VqdS)N)rC)rr6)rrrrR sr rrc3s$|]\}}|dgkr|VqdS)rNr)rrrN)rrrr^ sc3s|]\}}|kr|VqdS)Nr)rrrN)rrrrh sT)r c3s$|]\}}|dgkr|VqdS)rNr)rrrN)rrrrs sc3s|]\}}|kr|VqdS)Nr)rrrN)rrrr{ s)allrrrrrrrGrrrZno_gradrjrwrrrWrrrryrrrrrr) rrrr$rZ has_labelsrZ raw_outputsrZ logits_mbrr9r r)rrrr0* s`                 zTrainer.prediction_step)rcCs t|jdr|jj|SdSdS)a For models that inherit from [`PreTrainedModel`], uses that method to compute the number of floating point operations for every backward + forward pass. If using another model, either implement such a method in the model or subclass and override this method. Args: inputs (`Dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of the model. Returns: `int`: The number of floating-point operations. rrN)rrr)rrrrrr s  zTrainer.floating_point_ops)rcCs8|js dS|jjdkrdn|jj}|jjdkrDt|jjjj}n|jj}d|krdt||jjd}yt |jj||d|_ WnFt k r|jj r|rt j|jjt |jj||d|_ nYnX|j jtjjtjj|jjd o|jjtjkr.ttjj|jjdddd }|jd gWdQRXd|_dS) a Initializes a git repo in `self.args.hub_model_id`. Args: at_init (`bool`, *optional*, defaults to `False`): Whether this function is called before any training or not. If `self.args.overwrite_output_dir` is `True` and `at_init` is `True`, the path to the repo (which is `self.args.output_dir`) might be wiped out. NT/)token)Z clone_fromuse_auth_tokenz .gitignorewzutf-8)encodingz checkpoint-*/)rrZ hub_token hub_model_idrrabsoluter6rer!repoEnvironmentErrorZoverwrite_output_dirr r!Zgit_pullrrqrr hub_strategyrQZALL_CHECKPOINTSopen writelinespush_in_progress)rrrG repo_namewriterrrrr s6     zTrainer.init_git_repo) languagelicensetags model_namefinetuned_fromtasks dataset_tagsr dataset_argsc Csd|js dStj|||||||||| d } | j} ttjj|jj dd} | j | WdQRXdS)N) rTrUrVrWrXrYrZrr[z README.mdrH) rr-Z from_trainerZ to_model_cardrOrrqrrrwrite) rrTrUrVrWrXrYrZrr[Ztraining_summaryZ model_cardfrrrcreate_model_card s zTrainer.create_model_cardc Csf|j s|jjtjkrdS|jdk r4|jj r4dS|jj}tt g}xB|D]:}t j j t j j ||rJtjt j j ||t j j ||qJW|jdk r|jj|tj|jt j j |tz|jjtjkrt j j |d}t j j|rtj|tj|||jjtjkrd|jj}ndt|jj}|j j!|ddd\}|_Wd|jjtjkr`tj||XdS)Nzlast-checkpointzTraining in progress, step zTraining in progress, epoch FT)r blockingauto_lfs_prune)"rrrNrQZENDrQZis_donerrbrcrrqrrr rerrrrur CHECKPOINTisdirr!moveZ save_strategyrRZSTEPSrrprr`rLr)rrrZmodeling_filesZ modeling_fileZtmp_checkpointr rrrrr s2 $     zTrainer._push_from_checkpointEnd of training)r r_r cKst|ds|j|jjrH|jjdkr6t|jjj}n|jjjdd }|j dd|j s`dS|j j ||dd}|jjr|j fd|i|y|j j d |ddWn2tk r}ztjd |WYdd}~XnX|S) u Upload *self.model* and *self.tokenizer* to the 🤗 model hub on the repo *self.args.hub_model_id*. Parameters: commit_message (`str`, *optional*, defaults to `"End of training"`): Message to commit while pushing. blocking (`bool`, *optional*, defaults to `True`): Whether the function should return only when the `git push` has finished. kwargs: Additional keyword arguments passed along to [`~Trainer.create_model_card`]. Returns: The url of the commit of your model in the given repository if `blocking=False`, a tuple with the url of the commit and an object to track the progress of the commit if `blocking=True` rLNrEr T)rn)r r_r`rWzupdate model card README.mdzEError pushing update to the model card. Please read logs and retry. $r)rrrrrJrrr6splitrrrrLrr^rMrerror)rr r_rrWZgit_head_commit_urlexcrrrr s&    "zTrainer.push_to_hubcCs |j}t|std|dk r"|n|j}|jrl|j rlt|ddd\}}}|j|_||_||_d|j _ d|_ |j |jdd} |j s|j r| jtj|jd} n|jr| jtj|jd} |j} |j|} tjd|d tjd | tjd | d} d} d}td |j}t|| | d }|sdd}t|drHt|jtrH|jj}t|| |d }t|| |d }| jt rt!j"||jgj#|j}|j$dkrd|_%||j&_'x,t(|D]\}}|j)| |||d\}}}|dk r|j*| }| dkr|ntj+| |fdd} |dk r.| dkr |n t,| |dd} |dk rT|dkrF|n t,||dd}|j&j-||j.|j/|_/|j0dk r|d |j0dkr|j1|j2| d|s|j1|j2| d|j1|j2|dd\} } }qW|j$rt|drt3|d|j1|j2| d|s0|j1|j2| d|j1|j2|d|j4}|sF|j4nd}|sX|j4nd}|j5dk r|dk r|dk r|j5t6||d}ni}t7|}|dk r|j8j9||d<x@t:|j;D]0}|j<|ds|j=|||d|<qWt>|||dS)z Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`. Works both with or without labels. z+dataloader must implement a working __len__Nr)r2rF)r)r rz***** Running z *****z Num examples = z Batch size = r )make_multiple_ofr%)r)r,r-)r.Z eval_lossesZ eval_predsZeval_label_idsr)r*rr/r)r*rraii)NNN)?rr[rr$rr)rrrrrrrrrrrrrrrrJrrrrr<rrr%r@r"rkrrrrrrr'rr0r1r2rFr4rrr5Z add_arrays_gather_and_numpifyrfinalizerrOrYrrrrrrTrS)rrFrr$rr#rrrrrrJr6r7r8rZeval_losses_gathererrhZpreds_gathererZlabels_gathererrlrrr9rr:Z eval_losspredsrrar\rrrr%N s             zTrainer.prediction_loopcCsJ|dkr dStrt||}n$tr.t|}n|jjdkrBt|}t|S)z Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before concatenating them to `gathered` Nr r)rkrJrjrxrrrCrH)rr;r6rrrri s   zTrainer._gather_and_numpifyNN) NNNNNNNNNrlN)N)N)N)N)T)NNN)N)NNrrNN)F)NF)N)NN)FN)NNr")Nr0)NNr")N)rm)N)F) NNNNNNNNN)rdT)NNr")er __module__ __qualname____doc__trainer_pt_utilsr{r|r}r~rr r.rModulerar r$rr2rrOrrr7r rr<Z OptimizerrZLambdaLRrrrrrrrMr rrZSamplerrrr(r,r.r1rr5r3 staticmethodrr=r4rJr_rrkrjrrrrrrrrrrPrMrrrrrrrrrrrr r rrLrrrrSr+rNr&rr3r0rrr^rrr%rirrrrrzsP[  I./+ %/ (*  K8a) u&TT$4(1  : A=+  %&*[ 4h*:zrz)rprrrrrrr rrrcollections.abcrpathlibrtypingrrrrrr r r Z tqdm.autor Z integrationsrrrrrrrrrrrrrrrZtorch.distributedZ distributedr packagingrrZtorch.utils.datarrrrZtorch.utils.data.distributedr Zhuggingface_hubr!rr"Zconfiguration_utilsr#Zdata.data_collatorr$r%r&Z debug_utilsr'r(rr)r*r+Zdependency_versions_checkr,Z modelcardr-Zmodeling_utilsr.r/rEr0r1Ztokenization_utils_baser2Ztrainer_callbackr3r4r5r6r7r8r9rqr:r;r<r=r>r?r@rArBrCrDrErFrGrHrIrJrKZ trainer_utilsrLrMrNrOrPrQrRrSrTrUrVrWrXrYrZr[r\r]r^Z training_argsr_r`rarrbrcrdrerfrgrhrirjrkrlrrrrZutils.notebookrmrrnrZtorch.cuda.amprorZtorch_xla.core.xla_modelcoreZ xla_modelrZtorch_xla.debug.metricsrrarZ%torch_xla.distributed.parallel_loaderrrrpZfairscale.nn.data_parallelrqrrrr~Zfairscale.nn.wraprsZfairscale.optimrtZfairscale.optim.grad_scalerruZ!smdistributed.modelparallel.torchZ modelparallelrrvrwrxryrf get_loggerrrrrtrwrxrrzrrrrs  ( 8          $ PT4