o �J�h m�@s�ddlZddlZddlZddlZddlZddlZddlmZmZm Z m Z ddl m Z ddl mZddlmZddlmZmZmZmZmZddlmZddlmZd d lmZd d lmZmZm Z m!Z!m"Z"m#Z#d d l$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9d d l:m;Z;d dl<m=Z=e8�>e?�Z@e8�A��B�ZCeDd0ieC�ddi��ZEe-�r�ddlFZFddlGmHZId dlJmKZKe(�r�ddlLmMZMmNZNddlOmPZPd dlQmRZRe6�r�ddlSmTmUZVe3dd��r-ejW�Xd��r-e=��re@�Yd�n*e@�Zd�ddl[mHm\Z]e^eIj_j`e]ja��s-eIjbdd�e^eIj_j`e]ja��s-ecd��e,��r>ddldmemFZfef�g�dehfdd�Zid d!�Zjd"d#deehfd$d%�ZkGd&d'�d'e&�Zlgd(�Zmd)eDfd*d+�ZneGd,d-�d-��ZoGd.d/�d/e�ZpdS)1�N)�asdict� dataclass�field�fields)� timedelta)�Enum)�Path)�Any�Dict�List�Optional�Union)�get_full_repo_name)�version��� DebugOption)�EvaluationStrategy� FSDPOption� HubStrategy�IntervalStrategy� SaveStrategy� SchedulerType)�ACCELERATE_MIN_VERSION� ExplicitEnum�cached_property�is_accelerate_available�is_ipex_available�is_safetensors_available�is_sagemaker_dp_enabled�is_sagemaker_mp_enabled�is_torch_available�is_torch_bf16_cpu_available�is_torch_bf16_gpu_available�is_torch_mlu_available�is_torch_mps_available�is_torch_musa_available�is_torch_neuroncore_available�is_torch_npu_available�is_torch_tf32_available�is_torch_xla_available�is_torch_xpu_available�logging�requires_backends)� strtobool)�is_optimum_neuron_available�passive�����)�"is_torch_greater_or_equal_than_2_0)�AcceleratorState� PartialState)�DistributedType)�AcceleratorConfigF)� check_device�TORCHELASTIC_RUN_IDzuMake sure that you are performing the training with the NeuronTrainer from optimum[neuron], this will fail otherwise.z�Please use the NeuronTrainer from optimum[neuron] instead of the Transformers library to perform training on AWS Trainium instances. More information here: https://github.com/huggingface/optimum-neuron�xla)�backendzGFailed to initialize torch.distributed process group using XLA backend.�returncCs<ddl}ddlm}|���d�}tj�d|d|���S)z! Same default as PyTorch rN)�datetimez %b%d_%H-%M-%S�runs�_)�socketr<�now�strftime�os�path�join� gethostname)r?r<� current_time�rG�XC:\pinokio\api\whisper-webui.git\app\env\lib\site-packages\transformers\training_args.py�default_logdirrs rIcCs0|D]}ttj�|d��}|dkr|Sq|S)zQReturns the first positive env value found in the `env_keys` list or the default.r1r)�intrB�environ�get)Zenv_keys�default�e�valrGrGrH�get_int_from_env}s �rP�device� torch.devicecCs2t�r|jdkr dSt�|g�d�d�dSdS)z^ Returns the xla device type (CPU|GPU|TPU) or None if the device is a non-xla device. �cpu�CPUr�:N)r*�type�xmZxla_real_devices�split)rQrGrGrH�get_xla_device_type�s  rYc@s�eZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!d Z"d!Z#d"Z$d#Z%d$Z&d%Z'd&Z(d'Z)d(S))�OptimizerNameszB Stores the acceptable string identifiers for optimizers. Zadamw_hf� adamw_torchZadamw_torch_fusedZadamw_torch_xlaZadamw_torch_npu_fusedZadamw_apex_fused� adafactorZadamw_anyprecisionZadamw_torch_4bitZademamix�sgd�adagradZadamw_bnb_8bitZ adamw_8bitZ ademamix_8bitZ lion_8bitZ lion_32bitZpaged_adamw_32bitZpaged_adamw_8bitZpaged_ademamix_32bitZpaged_ademamix_8bitZpaged_lion_32bitZpaged_lion_8bit�rmspropZ rmsprop_bnbZrmsprop_bnb_8bitZrmsprop_bnb_32bitZ galore_adamwZgalore_adamw_8bitZgalore_adafactorZgalore_adamw_layerwiseZgalore_adamw_8bit_layerwiseZgalore_adafactor_layerwiseZlomoZadalomoZ grokadamwZschedule_free_adamwZschedule_free_sgdN)*�__name__� __module__� __qualname__�__doc__ZADAMW_HFZ ADAMW_TORCH�ADAMW_TORCH_FUSEDZADAMW_TORCH_XLAZADAMW_TORCH_NPU_FUSEDZADAMW_APEX_FUSED� ADAFACTORZADAMW_ANYPRECISIONZADAMW_TORCH_4BITZADEMAMIX�SGDZADAGRADZ ADAMW_BNBZ ADAMW_8BITZ ADEMAMIX_8BITZ LION_8BITZLIONZ PAGED_ADAMWZPAGED_ADAMW_8BITZPAGED_ADEMAMIXZPAGED_ADEMAMIX_8BITZ PAGED_LIONZPAGED_LION_8BITZRMSPROPZ RMSPROP_BNBZ RMSPROP_8BITZ RMSPROP_32BITZ GALORE_ADAMWZGALORE_ADAMW_8BITZGALORE_ADAFACTORZGALORE_ADAMW_LAYERWISEZGALORE_ADAMW_8BIT_LAYERWISEZGALORE_ADAFACTOR_LAYERWISEZLOMOZADALOMOZ GROKADAMWZSCHEDULE_FREE_ADAMWZSCHEDULE_FREE_SGDrGrGrGrHrZ�sPrZ)�accelerator_config� fsdp_config� deepspeed�gradient_checkpointing_kwargs�lr_scheduler_kwargs� passed_valuecCs�|��D]>\}}t|t�rt|�||<qt|t�rB|��dvr(|��dk||<q|��r3t|�||<q|�ddd���rBt |�||<q|S)zlSafely checks that a passed value is a dictionary and converts any string values to their appropriate types.)�true�falserm�.�r) �items� isinstance�dict�_convert_str_dict�str�lower�isdigitrJ�replace�float)rl�key�valuerGrGrHrt�s    �rtc@s�eZdZUdZdZeddid�Zeed<edddid �Z e ed <eddd id �Z e ed <eddd id �Z e ed<edddid �Z e ed<edddid �Zeeefed<edddid �Ze ed<edddid �Zeed<edddid �Zeed<edddid �Zeeed<edddid �Zeeed<ed dd!id �Zeed"<eddd#id �Zeeed$<ed%dd&id �Zeeed'<eddd(id �Zeeed)<ed*dd+id �Zeed,<ed-dd.id �Zeed/<ed0dd1id �Zeed2<ed3dd4id �Z eed5<ed6dd7id �Z!eed8<ed9dd:id �Z"eed;<ed<dd=id �Z#eed><ed?dd@id �Z$eedA<edBddCid �Z%ee&efedD<ee'ddEidF�Z(eee'efedG<ed-ddHid �Z)eedI<ed%ddJid �Z*eedK<edLdMe+�,�dN�d �Z-eeedO<edPdQe+�,�dN�d �Z.eeedR<edSddTid �Z/e edU<edddVid �Z0eeedW<edXddYid �Z1eeefedZ<eddd[id �Z2e ed\<ed]dd^id �Z3eed_<edSdd`id �Z4e eda<edXddbid �Z5ee6efedc<ed]dddid �Z7eede<edddfid �Z8eeedg<edSddhid �Z9ee edi<edddjid �Z:e edk<edddlid �Z;e edm<edddnid �Z<e edo<edddpid �Z=e edq<edddrid �Z>e eds<edddtid �Z?e edu<edvddwid �Z@eedx<edddyid �ZAeeedz<eddd{id �ZBe ed|<eddd}id �ZCe ed~<edddid �ZDe ed�<eddd�id �ZEe ed�<ed�dd�id �ZFeed�<ed�d�gd��dN�d �ZGeed�<eddd�id �ZHe ed�<eddd�id �ZIe ed�<eddd�id �ZJee ed�<ed?dd�id �ZKeed�<edd�gd��dN�d �ZLeeed�<eddd�id �ZMeeed�<eddd�id �ZNe ed�<ed�dd�id �ZOeeePeQfed�<eddd�id �ZRe ed�<eddd�id �ZSeeed�<ed%dd�id �ZTeed�<eeU��rVeV�rXdnd�dd�id �ZWeeed�<ed?dd�id �ZXeed�<eddd�id �ZYeeed�<eddd�id �ZZee ed�<edSdd�id �Z[ee ed�<eddd�id �Z\eePeed�<eddd�id �Z]ee ed�<eddd�id �Z^eeed�<eddd�id �Z_ee ed�<eddd�id �Z`e ed�<ed�dd�id �ZaeeePebefed�<ed%dd�id �Zceed�<eddd�id �Zdeee'efed�<eddd�id �Zeeeed�<eddd�id �Zfeee'efed�<eddd�id �Zgeee'efed�<ed-dd�id �Zheed�<d�Zieeidd�id �Zjeekefed�<eddd�id �Zleeed�<eddd�id �Zme ed�<eddd�id �Zne ed�<ed�dd�id �Zoeeed�<eddd�id �ZpedeePefed�<eddd�id �Zqee ed�<eddd�id �Zreeed�<eddd�id �Zsee ed�<edSdd�id �Zte ed�<eddd�id �Zue ed�<edSdd�id �Zve ed�<eddd�id �Zwe ed�<eddd�id �Zxe ed�<eddd�id �Zyeeed�<eddd�id �Zzeeed�<ed�dd�id �Z{ee|efed�<eddd�id �Z}eeed�<eddd�id �Z~ee ed�<eddd�id �Ze ed�<eddd�id �Z�e ed�<eddd�id �Z�eee'efed�<eddd�id �Z�e ed�<ee�dd�idF�Z�ePeed�<edSdd�id �Z�e ed�<ed�d�gd��dN�d �Z�eed�<eddd�id �Z�eeefed�<eddd�id �Z�eeed�<edd�did �Z�eee�d<eddd�id �Z�eee�d<eddd?�d�Z�ee�d<ed�d�did �Z�ee�d<edd�did �Z�e e�d<edd�d id �Z�e e�d <edd�d id �Z�eee�d <e�d d�did �Z�eee�d<e�dd�did �Z�eee�d<edd�did �Z�e e�d<edd�did �Z�eee�d<edd�did �Z�eee�d<edd�did �Z�ee e�d<edd�did �Z�ee e�d<edd�did �Z�ee e�d<edd�did �Z�ee e�d <edd�d!id �Z�eee�d"<edd�d#id �Z�edeePefe�d$<edd�d%id �Z�e e�d&<edd�d'id �Z�e e�d(<edd�d)id �Z�ee e�d*<edd�d+id �Z�ee e�d,<edd�d-id �Z�ee e�d.<�d/�d0�Z��d1�d2�Z�e�Z�e��d3ef�d4�d5��Z�e��d3ef�d6�d7��Z�e��d3e�f�d8�d9��Z�e��d��d;�d<��Z�e��d��d=�d>��Z�e��d?�d@��Z�e��dA�dB��Z�e��dC�dD��Z�e��dE�dF��Z�e��dG�dH��Z�e��dI�dJ��Z�e��dK�dL��Z��dM�dN�Z�e��dO�dP��Z�e��dQ�dR��Z�e�j��d��dT�dU��Z��dVef�dW�dX�Z��dYe�ee�f�d3df�dZ�d[�Z��d\�d]�Z��d^�d_�Z��d3e�ee�ff�d`�da�Z� *  %� b ? v �d�d,e�dced/e�ddedAed"edxed�e f�de�df�Z�  ]     �d��dgeeefdXe�dce�dhee�diee�dje �dke f�dl�dm�Z�   �d��dce�dje �dke f�dn�do�Z� X ]  �d��dgeeefdXe�dpee�dqe f�dr�ds�Z� X ]� t L    L�d��dgeeefdXed�eeePef�due�dve �dwe �dqe �dxef�dy�dz�Z� �   �d��d{e�dgeee|f�d|ee�d}ee �d~e f �d�d��Z� � * % 0 3 6 �d��d�eeekfd,ed/e�d�e�d�e�d�e�d�eef�d��d��Z� B < ? % %�d��d�eee&f�ddedAedIedKef �d��d��Z�    % S     �d��d�e�d�e�d�e �d�e�d�e �d�e �d�ee�de d�e �d�eef�d��d��Z�dS(��TrainingArgumentsu�� TrainingArguments is the subset of the arguments we use in our example scripts **which relate to the training loop itself**. Using [`HfArgumentParser`] we can turn this class into [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the command line. Parameters: output_dir (`str`): The output directory where the model predictions and checkpoints will be written. overwrite_output_dir (`bool`, *optional*, defaults to `False`): If `True`, overwrite the content of the output directory. Use this to continue training if `output_dir` points to a checkpoint directory. do_train (`bool`, *optional*, defaults to `False`): Whether to run training or not. This argument is not directly used by [`Trainer`], it's intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details. do_eval (`bool`, *optional*): Whether to run evaluation on the validation set or not. Will be set to `True` if `eval_strategy` is different from `"no"`. This argument is not directly used by [`Trainer`], it's intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details. do_predict (`bool`, *optional*, defaults to `False`): Whether to run predictions on the test set or not. This argument is not directly used by [`Trainer`], it's intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details. eval_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"no"`): The evaluation strategy to adopt during training. Possible values are: - `"no"`: No evaluation is done during training. - `"steps"`: Evaluation is done (and logged) every `eval_steps`. - `"epoch"`: Evaluation is done at the end of each epoch. prediction_loss_only (`bool`, *optional*, defaults to `False`): When performing evaluation and generating predictions, only returns the loss. per_device_train_batch_size (`int`, *optional*, defaults to 8): The batch size per GPU/XPU/TPU/MPS/NPU core/CPU for training. per_device_eval_batch_size (`int`, *optional*, defaults to 8): The batch size per GPU/XPU/TPU/MPS/NPU core/CPU for evaluation. gradient_accumulation_steps (`int`, *optional*, defaults to 1): Number of updates steps to accumulate the gradients for, before performing a backward/update pass. <Tip warning={true}> When using gradient accumulation, one step is counted as one step with backward pass. Therefore, logging, evaluation, save will be conducted every `gradient_accumulation_steps * xxx_step` training examples. </Tip> eval_accumulation_steps (`int`, *optional*): Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU. If left unset, the whole predictions are accumulated on GPU/NPU/TPU before being moved to the CPU (faster but requires more memory). eval_delay (`float`, *optional*): Number of epochs or steps to wait for before the first evaluation can be performed, depending on the eval_strategy. torch_empty_cache_steps (`int`, *optional*): Number of steps to wait before calling `torch.<device>.empty_cache()`. If left unset or set to None, cache will not be emptied. <Tip> This can help avoid CUDA out-of-memory errors by lowering peak VRAM usage at a cost of about [10% slower performance](https://github.com/huggingface/transformers/issues/31372). </Tip> learning_rate (`float`, *optional*, defaults to 5e-5): The initial learning rate for [`AdamW`] optimizer. weight_decay (`float`, *optional*, defaults to 0): The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in [`AdamW`] optimizer. adam_beta1 (`float`, *optional*, defaults to 0.9): The beta1 hyperparameter for the [`AdamW`] optimizer. adam_beta2 (`float`, *optional*, defaults to 0.999): The beta2 hyperparameter for the [`AdamW`] optimizer. adam_epsilon (`float`, *optional*, defaults to 1e-8): The epsilon hyperparameter for the [`AdamW`] optimizer. max_grad_norm (`float`, *optional*, defaults to 1.0): Maximum gradient norm (for gradient clipping). num_train_epochs(`float`, *optional*, defaults to 3.0): Total number of training epochs to perform (if not an integer, will perform the decimal part percents of the last epoch before stopping training). max_steps (`int`, *optional*, defaults to -1): If set to a positive number, the total number of training steps to perform. Overrides `num_train_epochs`. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) until `max_steps` is reached. lr_scheduler_type (`str` or [`SchedulerType`], *optional*, defaults to `"linear"`): The scheduler type to use. See the documentation of [`SchedulerType`] for all possible values. lr_scheduler_kwargs ('dict', *optional*, defaults to {}): The extra arguments for the lr_scheduler. See the documentation of each scheduler for possible values. warmup_ratio (`float`, *optional*, defaults to 0.0): Ratio of total training steps used for a linear warmup from 0 to `learning_rate`. warmup_steps (`int`, *optional*, defaults to 0): Number of steps used for a linear warmup from 0 to `learning_rate`. Overrides any effect of `warmup_ratio`. log_level (`str`, *optional*, defaults to `passive`): Logger log level to use on the main process. Possible choices are the log levels as strings: 'debug', 'info', 'warning', 'error' and 'critical', plus a 'passive' level which doesn't set anything and keeps the current log level for the Transformers library (which will be `"warning"` by default). log_level_replica (`str`, *optional*, defaults to `"warning"`): Logger log level to use on replicas. Same choices as `log_level`" log_on_each_node (`bool`, *optional*, defaults to `True`): In multinode distributed training, whether to log using `log_level` once per node, or only on the main node. logging_dir (`str`, *optional*): [TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***. logging_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`): The logging strategy to adopt during training. Possible values are: - `"no"`: No logging is done during training. - `"epoch"`: Logging is done at the end of each epoch. - `"steps"`: Logging is done every `logging_steps`. logging_first_step (`bool`, *optional*, defaults to `False`): Whether to log the first `global_step` or not. logging_steps (`int` or `float`, *optional*, defaults to 500): Number of update steps between two logs if `logging_strategy="steps"`. Should be an integer or a float in range `[0,1)`. If smaller than 1, will be interpreted as ratio of total training steps. logging_nan_inf_filter (`bool`, *optional*, defaults to `True`): Whether to filter `nan` and `inf` losses for logging. If set to `True` the loss of every step that is `nan` or `inf` is filtered and the average loss of the current logging window is taken instead. <Tip> `logging_nan_inf_filter` only influences the logging of loss values, it does not change the behavior the gradient is computed or applied to the model. </Tip> save_strategy (`str` or [`~trainer_utils.SaveStrategy`], *optional*, defaults to `"steps"`): The checkpoint save strategy to adopt during training. Possible values are: - `"no"`: No save is done during training. - `"epoch"`: Save is done at the end of each epoch. - `"steps"`: Save is done every `save_steps`. - `"best"`: Save is done whenever a new `best_metric` is achieved. If `"epoch"` or `"steps"` is chosen, saving will also be performed at the very end of training, always. save_steps (`int` or `float`, *optional*, defaults to 500): Number of updates steps before two checkpoint saves if `save_strategy="steps"`. Should be an integer or a float in range `[0,1)`. If smaller than 1, will be interpreted as ratio of total training steps. save_total_limit (`int`, *optional*): If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in `output_dir`. When `load_best_model_at_end` is enabled, the "best" checkpoint according to `metric_for_best_model` will always be retained in addition to the most recent ones. For example, for `save_total_limit=5` and `load_best_model_at_end`, the four last checkpoints will always be retained alongside the best model. When `save_total_limit=1` and `load_best_model_at_end`, it is possible that two checkpoints are saved: the last one and the best one (if they are different). save_safetensors (`bool`, *optional*, defaults to `True`): Use [safetensors](https://huggingface.co/docs/safetensors) saving and loading for state dicts instead of default `torch.load` and `torch.save`. save_on_each_node (`bool`, *optional*, defaults to `False`): When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on the main one. This should not be activated when the different nodes use the same storage as the files will be saved with the same names for each node. save_only_model (`bool`, *optional*, defaults to `False`): When checkpointing, whether to only save the model, or also the optimizer, scheduler & rng state. Note that when this is true, you won't be able to resume training from checkpoint. This enables you to save storage by not storing the optimizer, scheduler & rng state. You can only load the model using `from_pretrained` with this option set to `True`. restore_callback_states_from_checkpoint (`bool`, *optional*, defaults to `False`): Whether to restore the callback states from the checkpoint. If `True`, will override callbacks passed to the `Trainer` if they exist in the checkpoint." use_cpu (`bool`, *optional*, defaults to `False`): Whether or not to use cpu. If set to False, we will use cuda or mps device if available. seed (`int`, *optional*, defaults to 42): Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use the [`~Trainer.model_init`] function to instantiate the model if it has some randomly initialized parameters. data_seed (`int`, *optional*): Random seed to be used with data samplers. If not set, random generators for data sampling will use the same seed as `seed`. This can be used to ensure reproducibility of data sampling, independent of the model seed. jit_mode_eval (`bool`, *optional*, defaults to `False`): Whether or not to use PyTorch jit trace for inference. use_ipex (`bool`, *optional*, defaults to `False`): Use Intel extension for PyTorch when it is available. [IPEX installation](https://github.com/intel/intel-extension-for-pytorch). bf16 (`bool`, *optional*, defaults to `False`): Whether to use bf16 16-bit (mixed) precision training instead of 32-bit training. Requires Ampere or higher NVIDIA architecture or using CPU (use_cpu) or Ascend NPU. This is an experimental API and it may change. fp16 (`bool`, *optional*, defaults to `False`): Whether to use fp16 16-bit (mixed) precision training instead of 32-bit training. fp16_opt_level (`str`, *optional*, defaults to 'O1'): For `fp16` training, Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. See details on the [Apex documentation](https://nvidia.github.io/apex/amp). fp16_backend (`str`, *optional*, defaults to `"auto"`): This argument is deprecated. Use `half_precision_backend` instead. half_precision_backend (`str`, *optional*, defaults to `"auto"`): The backend to use for mixed precision training. Must be one of `"auto", "apex", "cpu_amp"`. `"auto"` will use CPU/CUDA AMP or APEX depending on the PyTorch version detected, while the other choices will force the requested backend. bf16_full_eval (`bool`, *optional*, defaults to `False`): Whether to use full bfloat16 evaluation instead of 32-bit. This will be faster and save memory but can harm metric values. This is an experimental API and it may change. fp16_full_eval (`bool`, *optional*, defaults to `False`): Whether to use full float16 evaluation instead of 32-bit. This will be faster and save memory but can harm metric values. tf32 (`bool`, *optional*): Whether to enable the TF32 mode, available in Ampere and newer GPU architectures. The default value depends on PyTorch's version default of `torch.backends.cuda.matmul.allow_tf32`. For more details please refer to the [TF32](https://huggingface.co/docs/transformers/perf_train_gpu_one#tf32) documentation. This is an experimental API and it may change. local_rank (`int`, *optional*, defaults to -1): Rank of the process during distributed training. ddp_backend (`str`, *optional*): The backend to use for distributed training. Must be one of `"nccl"`, `"mpi"`, `"ccl"`, `"gloo"`, `"hccl"`. tpu_num_cores (`int`, *optional*): When training on TPU, the number of TPU cores (automatically passed by launcher script). dataloader_drop_last (`bool`, *optional*, defaults to `False`): Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size) or not. eval_steps (`int` or `float`, *optional*): Number of update steps between two evaluations if `eval_strategy="steps"`. Will default to the same value as `logging_steps` if not set. Should be an integer or a float in range `[0,1)`. If smaller than 1, will be interpreted as ratio of total training steps. dataloader_num_workers (`int`, *optional*, defaults to 0): Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in the main process. past_index (`int`, *optional*, defaults to -1): Some models like [TransformerXL](../model_doc/transformerxl) or [XLNet](../model_doc/xlnet) can make use of the past hidden states for their predictions. If this argument is set to a positive int, the `Trainer` will use the corresponding output (usually index 2) as the past state and feed it to the model at the next training step under the keyword argument `mems`. run_name (`str`, *optional*, defaults to `output_dir`): A descriptor for the run. Typically used for [wandb](https://www.wandb.com/), [mlflow](https://www.mlflow.org/) and [comet](https://www.comet.com/site) logging. If not specified, will be the same as `output_dir`. disable_tqdm (`bool`, *optional*): Whether or not to disable the tqdm progress bars and table of metrics produced by [`~notebook.NotebookTrainingTracker`] in Jupyter Notebooks. Will default to `True` if the logging level is set to warn or lower (default), `False` otherwise. remove_unused_columns (`bool`, *optional*, defaults to `True`): Whether or not to automatically remove the columns unused by the model forward method. label_names (`List[str]`, *optional*): The list of keys in your dictionary of inputs that correspond to the labels. Will eventually default to the list of argument names accepted by the model that contain the word "label", except if the model used is one of the `XxxForQuestionAnswering` in which case it will also include the `["start_positions", "end_positions"]` keys. load_best_model_at_end (`bool`, *optional*, defaults to `False`): Whether or not to load the best model found during training at the end of training. When this option is enabled, the best checkpoint will always be saved. See [`save_total_limit`](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.save_total_limit) for more. <Tip> When set to `True`, the parameters `save_strategy` needs to be the same as `eval_strategy`, and in the case it is "steps", `save_steps` must be a round multiple of `eval_steps`. </Tip> metric_for_best_model (`str`, *optional*): Use in conjunction with `load_best_model_at_end` to specify the metric to use to compare two different models. Must be the name of a metric returned by the evaluation with or without the prefix `"eval_"`. Will default to `"loss"` if unspecified and `load_best_model_at_end=True` (to use the evaluation loss). If you set this value, `greater_is_better` will default to `True`. Don't forget to set it to `False` if your metric is better when lower. greater_is_better (`bool`, *optional*): Use in conjunction with `load_best_model_at_end` and `metric_for_best_model` to specify if better models should have a greater metric or not. Will default to: - `True` if `metric_for_best_model` is set to a value that doesn't end in `"loss"`. - `False` if `metric_for_best_model` is not set, or set to a value that ends in `"loss"`. ignore_data_skip (`bool`, *optional*, defaults to `False`): When resuming training, whether or not to skip the epochs and batches to get the data loading at the same stage as in the previous training. If set to `True`, the training will begin faster (as that skipping step can take a long time) but will not yield the same results as the interrupted training would have. fsdp (`bool`, `str` or list of [`~trainer_utils.FSDPOption`], *optional*, defaults to `''`): Use PyTorch Distributed Parallel Training (in distributed training only). A list of options along the following: - `"full_shard"`: Shard parameters, gradients and optimizer states. - `"shard_grad_op"`: Shard optimizer states and gradients. - `"hybrid_shard"`: Apply `FULL_SHARD` within a node, and replicate parameters across nodes. - `"hybrid_shard_zero2"`: Apply `SHARD_GRAD_OP` within a node, and replicate parameters across nodes. - `"offload"`: Offload parameters and gradients to CPUs (only compatible with `"full_shard"` and `"shard_grad_op"`). - `"auto_wrap"`: Automatically recursively wrap layers with FSDP using `default_auto_wrap_policy`. fsdp_config (`str` or `dict`, *optional*): Config to be used with fsdp (Pytorch Distributed Parallel Training). The value is either a location of fsdp json config file (e.g., `fsdp_config.json`) or an already loaded json file as `dict`. A List of config and its options: - min_num_params (`int`, *optional*, defaults to `0`): FSDP's minimum number of parameters for Default Auto Wrapping. (useful only when `fsdp` field is passed). - transformer_layer_cls_to_wrap (`List[str]`, *optional*): List of transformer layer class names (case-sensitive) to wrap, e.g, `BertLayer`, `GPTJBlock`, `T5Block` .... (useful only when `fsdp` flag is passed). - backward_prefetch (`str`, *optional*) FSDP's backward prefetch mode. Controls when to prefetch next set of parameters (useful only when `fsdp` field is passed). A list of options along the following: - `"backward_pre"` : Prefetches the next set of parameters before the current set of parameter's gradient computation. - `"backward_post"` : This prefetches the next set of parameters after the current set of parameter’s gradient computation. - forward_prefetch (`bool`, *optional*, defaults to `False`) FSDP's forward prefetch mode (useful only when `fsdp` field is passed). If `"True"`, then FSDP explicitly prefetches the next upcoming all-gather while executing in the forward pass. - limit_all_gathers (`bool`, *optional*, defaults to `False`) FSDP's limit_all_gathers (useful only when `fsdp` field is passed). If `"True"`, FSDP explicitly synchronizes the CPU thread to prevent too many in-flight all-gathers. - use_orig_params (`bool`, *optional*, defaults to `True`) If `"True"`, allows non-uniform `requires_grad` during init, which means support for interspersed frozen and trainable paramteres. Useful in cases such as parameter-efficient fine-tuning. Please refer this [blog](https://dev-discuss.pytorch.org/t/rethinking-pytorch-fully-sharded-data-parallel-fsdp-from-first-principles/1019 - sync_module_states (`bool`, *optional*, defaults to `True`) If `"True"`, each individually wrapped FSDP unit will broadcast module parameters from rank 0 to ensure they are the same across all ranks after initialization - cpu_ram_efficient_loading (`bool`, *optional*, defaults to `False`) If `"True"`, only the first process loads the pretrained model checkpoint while all other processes have empty weights. When this setting as `"True"`, `sync_module_states` also must to be `"True"`, otherwise all the processes except the main process would have random weights leading to unexpected behaviour during training. - activation_checkpointing (`bool`, *optional*, defaults to `False`): If `"True"`, activation checkpointing is a technique to reduce memory usage by clearing activations of certain layers and recomputing them during a backward pass. Effectively, this trades extra computation time for reduced memory usage. - xla (`bool`, *optional*, defaults to `False`): Whether to use PyTorch/XLA Fully Sharded Data Parallel Training. This is an experimental feature and its API may evolve in the future. - xla_fsdp_settings (`dict`, *optional*) The value is a dictionary which stores the XLA FSDP wrapping parameters. For a complete list of options, please see [here]( https://github.com/pytorch/xla/blob/master/torch_xla/distributed/fsdp/xla_fully_sharded_data_parallel.py). - xla_fsdp_grad_ckpt (`bool`, *optional*, defaults to `False`): Will use gradient checkpointing over each nested XLA FSDP wrapped layer. This setting can only be used when the xla flag is set to true, and an auto wrapping policy is specified through fsdp_min_num_params or fsdp_transformer_layer_cls_to_wrap. deepspeed (`str` or `dict`, *optional*): Use [Deepspeed](https://github.com/microsoft/deepspeed). This is an experimental feature and its API may evolve in the future. The value is either the location of DeepSpeed json config file (e.g., `ds_config.json`) or an already loaded json file as a `dict`" <Tip warning={true}> If enabling any Zero-init, make sure that your model is not initialized until *after* initializing the `TrainingArguments`, else it will not be applied. </Tip> accelerator_config (`str`, `dict`, or `AcceleratorConfig`, *optional*): Config to be used with the internal `Accelerator` implementation. The value is either a location of accelerator json config file (e.g., `accelerator_config.json`), an already loaded json file as `dict`, or an instance of [`~trainer_pt_utils.AcceleratorConfig`]. A list of config and its options: - split_batches (`bool`, *optional*, defaults to `False`): Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. If `True` the actual batch size used will be the same on any kind of distributed processes, but it must be a round multiple of the `num_processes` you are using. If `False`, actual batch size used will be the one set in your script multiplied by the number of processes. - dispatch_batches (`bool`, *optional*): If set to `True`, the dataloader prepared by the Accelerator is only iterated through on the main process and then the batches are split and broadcast to each process. Will default to `True` for `DataLoader` whose underlying dataset is an `IterableDataset`, `False` otherwise. - even_batches (`bool`, *optional*, defaults to `True`): If set to `True`, in cases where the total batch size across all processes does not exactly divide the dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among all workers. - use_seedable_sampler (`bool`, *optional*, defaults to `True`): Whether or not use a fully seedable random sampler ([`accelerate.data_loader.SeedableRandomSampler`]). Ensures training results are fully reproducable using a different sampling technique. While seed-to-seed results may differ, on average the differences are neglible when using multiple different seeds to compare. Should also be ran with [`~utils.set_seed`] for the best results. - use_configured_state (`bool`, *optional*, defaults to `False`): Whether or not to use a pre-configured `AcceleratorState` or `PartialState` defined before calling `TrainingArguments`. If `True`, an `Accelerator` or `PartialState` must be initialized. Note that by doing so, this could lead to issues with hyperparameter tuning. label_smoothing_factor (`float`, *optional*, defaults to 0.0): The label smoothing factor to use. Zero means no label smoothing, otherwise the underlying onehot-encoded labels are changed from 0s and 1s to `label_smoothing_factor/num_labels` and `1 - label_smoothing_factor + label_smoothing_factor/num_labels` respectively. debug (`str` or list of [`~debug_utils.DebugOption`], *optional*, defaults to `""`): Enable one or more debug features. This is an experimental feature. Possible options are: - `"underflow_overflow"`: detects overflow in model's input/outputs and reports the last frames that led to the event - `"tpu_metrics_debug"`: print debug metrics on TPU The options should be separated by whitespaces. optim (`str` or [`training_args.OptimizerNames`], *optional*, defaults to `"adamw_torch"`): The optimizer to use, such as "adamw_hf", "adamw_torch", "adamw_torch_fused", "adamw_apex_fused", "adamw_anyprecision", "adafactor". See `OptimizerNames` in [training_args.py](https://github.com/huggingface/transformers/blob/main/src/transformers/training_args.py) for a full list of optimizers. optim_args (`str`, *optional*): Optional arguments that are supplied to optimizers such as AnyPrecisionAdamW, AdEMAMix, and GaLore. group_by_length (`bool`, *optional*, defaults to `False`): Whether or not to group together samples of roughly the same length in the training dataset (to minimize padding applied and be more efficient). Only useful if applying dynamic padding. length_column_name (`str`, *optional*, defaults to `"length"`): Column name for precomputed lengths. If the column exists, grouping by length will use these values rather than computing them on train startup. Ignored unless `group_by_length` is `True` and the dataset is an instance of `Dataset`. report_to (`str` or `List[str]`, *optional*, defaults to `"all"`): The list of integrations to report the results and logs to. Supported platforms are `"azure_ml"`, `"clearml"`, `"codecarbon"`, `"comet_ml"`, `"dagshub"`, `"dvclive"`, `"flyte"`, `"mlflow"`, `"neptune"`, `"tensorboard"`, and `"wandb"`. Use `"all"` to report to all integrations installed, `"none"` for no integrations. ddp_find_unused_parameters (`bool`, *optional*): When using distributed training, the value of the flag `find_unused_parameters` passed to `DistributedDataParallel`. Will default to `False` if gradient checkpointing is used, `True` otherwise. ddp_bucket_cap_mb (`int`, *optional*): When using distributed training, the value of the flag `bucket_cap_mb` passed to `DistributedDataParallel`. ddp_broadcast_buffers (`bool`, *optional*): When using distributed training, the value of the flag `broadcast_buffers` passed to `DistributedDataParallel`. Will default to `False` if gradient checkpointing is used, `True` otherwise. dataloader_pin_memory (`bool`, *optional*, defaults to `True`): Whether you want to pin memory in data loaders or not. Will default to `True`. dataloader_persistent_workers (`bool`, *optional*, defaults to `False`): If True, the data loader will not shut down the worker processes after a dataset has been consumed once. This allows to maintain the workers Dataset instances alive. Can potentially speed up training, but will increase RAM usage. Will default to `False`. dataloader_prefetch_factor (`int`, *optional*): Number of batches loaded in advance by each worker. 2 means there will be a total of 2 * num_workers batches prefetched across all workers. skip_memory_metrics (`bool`, *optional*, defaults to `True`): Whether to skip adding of memory profiler reports to metrics. This is skipped by default because it slows down the training and evaluation speed. push_to_hub (`bool`, *optional*, defaults to `False`): Whether or not to push the model to the Hub every time the model is saved. If this is activated, `output_dir` will begin a git directory synced with the repo (determined by `hub_model_id`) and the content will be pushed each time a save is triggered (depending on your `save_strategy`). Calling [`~Trainer.save_model`] will also trigger a push. <Tip warning={true}> If `output_dir` exists, it needs to be a local clone of the repository to which the [`Trainer`] will be pushed. </Tip> resume_from_checkpoint (`str`, *optional*): The path to a folder with a valid checkpoint for your model. This argument is not directly used by [`Trainer`], it's intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details. hub_model_id (`str`, *optional*): The name of the repository to keep in sync with the local *output_dir*. It can be a simple model ID in which case the model will be pushed in your namespace. Otherwise it should be the whole repository name, for instance `"user_name/model"`, which allows you to push to an organization you are a member of with `"organization_name/model"`. Will default to `user_name/output_dir_name` with *output_dir_name* being the name of `output_dir`. Will default to the name of `output_dir`. hub_strategy (`str` or [`~trainer_utils.HubStrategy`], *optional*, defaults to `"every_save"`): Defines the scope of what is pushed to the Hub and when. Possible values are: - `"end"`: push the model, its configuration, the processing class e.g. tokenizer (if passed along to the [`Trainer`]) and a draft of a model card when the [`~Trainer.save_model`] method is called. - `"every_save"`: push the model, its configuration, the processing class e.g. tokenizer (if passed along to the [`Trainer`]) and a draft of a model card each time there is a model save. The pushes are asynchronous to not block training, and in case the save are very frequent, a new push is only attempted if the previous one is finished. A last push is made with the final model at the end of training. - `"checkpoint"`: like `"every_save"` but the latest checkpoint is also pushed in a subfolder named last-checkpoint, allowing you to resume training easily with `trainer.train(resume_from_checkpoint="last-checkpoint")`. - `"all_checkpoints"`: like `"checkpoint"` but all checkpoints are pushed like they appear in the output folder (so you will get one checkpoint folder per folder in your final repository) hub_token (`str`, *optional*): The token to use to push the model to the Hub. Will default to the token in the cache folder obtained with `huggingface-cli login`. hub_private_repo (`bool`, *optional*): Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists. hub_always_push (`bool`, *optional*, defaults to `False`): Unless this is `True`, the `Trainer` will skip pushing a checkpoint when the previous push is not finished. gradient_checkpointing (`bool`, *optional*, defaults to `False`): If True, use gradient checkpointing to save memory at the expense of slower backward pass. gradient_checkpointing_kwargs (`dict`, *optional*, defaults to `None`): Key word arguments to be passed to the `gradient_checkpointing_enable` method. include_inputs_for_metrics (`bool`, *optional*, defaults to `False`): This argument is deprecated. Use `include_for_metrics` instead, e.g, `include_for_metrics = ["inputs"]`. include_for_metrics (`List[str]`, *optional*, defaults to `[]`): Include additional data in the `compute_metrics` function if needed for metrics computation. Possible options to add to `include_for_metrics` list: - `"inputs"`: Input data passed to the model, intended for calculating input dependent metrics. - `"loss"`: Loss values computed during evaluation, intended for calculating loss dependent metrics. eval_do_concat_batches (`bool`, *optional*, defaults to `True`): Whether to recursively concat inputs/losses/labels/predictions across batches. If `False`, will instead store them as lists, with each batch kept separate. auto_find_batch_size (`bool`, *optional*, defaults to `False`) Whether to find a batch size that will fit into memory automatically through exponential decay, avoiding CUDA Out-of-Memory errors. Requires accelerate to be installed (`pip install accelerate`) full_determinism (`bool`, *optional*, defaults to `False`) If `True`, [`enable_full_determinism`] is called instead of [`set_seed`] to ensure reproducible results in distributed training. Important: this will negatively impact the performance, so only use it for debugging. torchdynamo (`str`, *optional*): If set, the backend compiler for TorchDynamo. Possible choices are `"eager"`, `"aot_eager"`, `"inductor"`, `"nvfuser"`, `"aot_nvfuser"`, `"aot_cudagraphs"`, `"ofi"`, `"fx2trt"`, `"onnxrt"` and `"ipex"`. ray_scope (`str`, *optional*, defaults to `"last"`): The scope to use when doing hyperparameter search with Ray. By default, `"last"` will be used. Ray will then use the last checkpoint of all trials, compare those, and select the best one. However, other options are also available. See the [Ray documentation]( https://docs.ray.io/en/latest/tune/api_docs/analysis.html#ray.tune.ExperimentAnalysis.get_best_trial) for more options. ddp_timeout (`int`, *optional*, defaults to 1800): The timeout for `torch.distributed.init_process_group` calls, used to avoid GPU socket timeouts when performing slow operations in distributed runnings. Please refer the [PyTorch documentation] (https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group) for more information. use_mps_device (`bool`, *optional*, defaults to `False`): This argument is deprecated.`mps` device will be used if it is available similar to `cuda` device. torch_compile (`bool`, *optional*, defaults to `False`): Whether or not to compile the model using PyTorch 2.0 [`torch.compile`](https://pytorch.org/get-started/pytorch-2.0/). This will use the best defaults for the [`torch.compile` API](https://pytorch.org/docs/stable/generated/torch.compile.html?highlight=torch+compile#torch.compile). You can customize the defaults with the argument `torch_compile_backend` and `torch_compile_mode` but we don't guarantee any of them will work as the support is progressively rolled in in PyTorch. This flag and the whole compile API is experimental and subject to change in future releases. torch_compile_backend (`str`, *optional*): The backend to use in `torch.compile`. If set to any value, `torch_compile` will be set to `True`. Refer to the PyTorch doc for possible values and note that they may change across PyTorch versions. This flag is experimental and subject to change in future releases. torch_compile_mode (`str`, *optional*): The mode to use in `torch.compile`. If set to any value, `torch_compile` will be set to `True`. Refer to the PyTorch doc for possible values and note that they may change across PyTorch versions. This flag is experimental and subject to change in future releases. split_batches (`bool`, *optional*): Whether or not the accelerator should split the batches yielded by the dataloaders across the devices during distributed training. If set to `True`, the actual batch size used will be the same on any kind of distributed processes, but it must be a round multiple of the number of processes you are using (such as GPUs). include_tokens_per_second (`bool`, *optional*): Whether or not to compute the number of tokens per second per device for training speed metrics. This will iterate over the entire training dataloader once beforehand, and will slow down the entire process. include_num_input_tokens_seen (`bool`, *optional*): Whether or not to track the number of input tokens seen throughout training. May be slower in distributed training as gather operations must be called. neftune_noise_alpha (`Optional[float]`): If not `None`, this will activate NEFTune noise embeddings. This can drastically improve model performance for instruction fine-tuning. Check out the [original paper](https://arxiv.org/abs/2310.05914) and the [original code](https://github.com/neelsjain/NEFTune). Support transformers `PreTrainedModel` and also `PeftModel` from peft. The original paper used values in the range [5.0, 15.0]. optim_target_modules (`Union[str, List[str]]`, *optional*): The target modules to optimize, i.e. the module names that you would like to train, right now this is used only for GaLore algorithm https://arxiv.org/abs/2403.03507 See: https://github.com/jiaweizzhao/GaLore for more details. You need to make sure to pass a valid GaloRe optimizer, e.g. one of: "galore_adamw", "galore_adamw_8bit", "galore_adafactor" and make sure that the target modules are `nn.Linear` modules only. batch_eval_metrics (`Optional[bool]`, defaults to `False`): If set to `True`, evaluation will call compute_metrics at the end of each batch to accumulate statistics rather than saving all eval logits in memory. When set to `True`, you must pass a compute_metrics function that takes a boolean argument `compute_result`, which when passed `True`, will trigger the final global summary statistics from the batch-level summary statistics you've accumulated over the evaluation set. eval_on_start (`bool`, *optional*, defaults to `False`): Whether to perform a evaluation step (sanity check) before the training to ensure the validation steps works correctly. eval_use_gather_object (`bool`, *optional*, defaults to `False`): Whether to run recursively gather object in a nested list/tuple/dictionary of objects from all devices. This should only be enabled if users are not just returning tensors, and this is actively discouraged by PyTorch. use_liger_kernel (`bool`, *optional*, defaults to `False`): Whether enable [Liger](https://github.com/linkedin/Liger-Kernel) Kernel for LLM model training. It can effectively increase multi-GPU training throughput by ~20% and reduces memory usage by ~60%, works out of the box with flash attention, PyTorch FSDP, and Microsoft DeepSpeed. Currently, it supports llama, mistral, mixtral and gemma models. �pt�helpzQThe output directory where the model predictions and checkpoints will be written.)�metadata� output_dirFz|Overwrite the content of the output directory. Use this to continue training if output_dir points to a checkpoint directory.)rMr�overwrite_output_dirzWhether to run training.�do_trainz#Whether to run eval on the dev set.�do_evalz+Whether to run predictions on the test set.� do_predict�nozThe evaluation strategy to use.� eval_strategyzBWhen performing evaluation and predictions, only returns the loss.�prediction_loss_only�z5Batch size per GPU/TPU/MPS/NPU core/CPU for training.�per_device_train_batch_sizez7Batch size per GPU/TPU/MPS/NPU core/CPU for evaluation.�per_device_eval_batch_sizeNzrDeprecated, the use of `--per_device_train_batch_size` is preferred. Batch size per GPU/TPU core/CPU for training.�per_gpu_train_batch_sizezsDeprecated, the use of `--per_device_eval_batch_size` is preferred. Batch size per GPU/TPU core/CPU for evaluation.�per_gpu_eval_batch_sizerzONumber of updates steps to accumulate before performing a backward/update pass.�gradient_accumulation_stepszONumber of predictions steps to accumulate before moving the tensors to the CPU.�eval_accumulation_stepsrzsNumber of epochs or steps to wait for before the first evaluation can be performed, depending on the eval_strategy.� eval_delaya.Number of steps to wait before calling `torch.<device>.empty_cache()`.This can help avoid CUDA out-of-memory errors by lowering peak VRAM usage at a cost of about [10% slower performance](https://github.com/huggingface/transformers/issues/31372).If left unset or set to None, cache will not be emptied.�torch_empty_cache_steps�-C��6 ?z$The initial learning rate for AdamW.� learning_rategz(Weight decay for AdamW if we apply some.� weight_decay��������?zBeta1 for AdamW optimizer� adam_beta1�+�����?zBeta2 for AdamW optimizer� adam_beta2�:�0�yE>zEpsilon for AdamW optimizer.� adam_epsilong�?zMax gradient norm.� max_grad_norm�@z+Total number of training epochs to perform.�num_train_epochsr1zQIf > 0: set total number of training steps to perform. Override num_train_epochs.� max_steps�linearzThe scheduler type to use.�lr_scheduler_typezbExtra parameters for the lr_scheduler such as {'num_cycles': 1} for the cosine with hard restarts.)�default_factoryrrkz8Linear warmup over warmup_ratio fraction of total steps.� warmup_ratioz Linear warmup over warmup_steps.� warmup_stepsr0z�Logger log level to use on the main node. Possible choices are the log levels as strings: 'debug', 'info', 'warning', 'error' and 'critical', plus a 'passive' level which doesn't set anything and lets the application set the level. Defaults to 'passive'.)r~�choices� log_level�warningzTLogger log level to use on replica nodes. Same choices and defaults as ``log_level``�log_level_replicaTzhWhen doing a multinode distributed training, whether to log once per node or just once on the main node.�log_on_each_nodezTensorboard log dir.� logging_dir�stepszThe logging strategy to use.�logging_strategyzLog the first global_step�logging_first_step��z�Log every X updates steps. Should be an integer or a float in range `[0,1)`. If smaller than 1, will be interpreted as ratio of total training steps.� logging_stepsz&Filter nan and inf losses for logging.�logging_nan_inf_filterz$The checkpoint save strategy to use.� save_strategyz�Save checkpoint every X updates steps. Should be an integer or a float in range `[0,1)`. If smaller than 1, will be interpreted as ratio of total training steps.� save_stepsakIf a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in `output_dir`. When `load_best_model_at_end` is enabled, the 'best' checkpoint according to `metric_for_best_model` will always be retained in addition to the most recent ones. For example, for `save_total_limit=5` and `load_best_model_at_end=True`, the four last checkpoints will always be retained alongside the best model. When `save_total_limit=1` and `load_best_model_at_end=True`, it is possible that two checkpoints are saved: the last one and the best one (if they are different). Default is unlimited checkpoints�save_total_limitz`Use safetensors saving and loading for state dicts instead of default torch.load and torch.save.�save_safetensorszxWhen doing multi-node distributed training, whether to save models and checkpoints on each node, or only on the main one�save_on_each_nodeaWWhen checkpointing, whether to only save the model, or also the optimizer, scheduler & rng state.Note that when this is true, you won't be able to resume training from checkpoint.This enables you to save storage by not storing the optimizer, scheduler & rng state.You can only load the model using from_pretrained with this option set to True.�save_only_modelz�Whether to restore the callback states from the checkpoint. If `True`, will override callbacks passed to the `Trainer` if they exist in the checkpoint.�'restore_callback_states_from_checkpointuTThis argument is deprecated. It will be removed in version 5.0 of 🤗 Transformers.�no_cudaz]Whether or not to use cpu. If set to False, we will use cuda/tpu/mps/npu device if available.�use_cpuu�This argument is deprecated. `mps` device will be used if available similar to `cuda` device. It will be removed in version 5.0 of 🤗 Transformers�use_mps_device�*z:Random seed that will be set at the beginning of training.�seedz*Random seed to be used with data samplers.� data_seedz5Whether or not to use PyTorch jit trace for inference� jit_mode_evalzzUse Intel extension for PyTorch when it is available, installation: 'https://github.com/intel/intel-extension-for-pytorch'�use_ipexz�Whether to use bf16 (mixed) precision instead of 32-bit. Requires Ampere or higher NVIDIA architecture or using CPU (use_cpu) or Ascend NPU. This is an experimental API and it may change.�bf16z7Whether to use fp16 (mixed) precision instead of 32-bit�fp16ZO1z�For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. See details at https://nvidia.github.io/apex/amp.html�fp16_opt_level�autoz*The backend to be used for half precision.)r��apexZcpu_amp�half_precision_backendziWhether to use full bfloat16 evaluation instead of 32-bit. This is an experimental API and it may change.�bf16_full_evalz8Whether to use full float16 evaluation instead of 32-bit�fp16_full_evalz|Whether to enable tf32 mode, available in Ampere and newer GPU architectures. This is an experimental API and it may change.�tf32z$For distributed training: local_rank� local_rankz/The backend to be used for distributed training)�nccl�gloo�mpiZcclZhcclZcnclZmccl� ddp_backendzBTPU: Number of TPU cores (automatically passed by launcher script)� tpu_num_coreszdDeprecated, the use of `--debug tpu_metrics_debug` is preferred. TPU: Whether to print debug metrics�tpu_metrics_debugrpz�Whether or not to enable debug mode. Current options: `underflow_overflow` (Detect underflow and overflow in activations and weights), `tpu_metrics_debug` (print debug metrics on TPU).�debugzHDrop the last incomplete batch if it is not divisible by the batch size.�dataloader_drop_lastz�Run an evaluation every X steps. Should be an integer or a float in range `[0,1)`. If smaller than 1, will be interpreted as ratio of total training steps.� eval_stepszxNumber of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in the main process.�dataloader_num_workers�z�Number of batches loaded in advance by each worker. 2 means there will be a total of 2 * num_workers batches prefetched across all workers. Default is 2 for PyTorch < 2.0.0 and otherwise None.�dataloader_prefetch_factorzRIf >=0, uses the corresponding part of the output as the past state for next step.� past_indexzUAn optional descriptor for the run. Notably used for wandb, mlflow and comet logging.�run_namez1Whether or not to disable the tqdm progress bars.� disable_tqdmzCRemove columns not required by the model when using an nlp.Dataset.�remove_unused_columnszLThe list of keys in your dictionary of inputs that correspond to the labels.� label_namesz�Whether or not to load the best model found during training at the end of training. When this option is enabled, the best checkpoint will always be saved. See `save_total_limit` for more.�load_best_model_at_endz2The metric to use to compare two different models.�metric_for_best_modelz?Whether the `metric_for_best_model` should be maximized or not.�greater_is_betterzmWhen resuming training, whether or not to skip the first epochs and batches to get to the same training data.�ignore_data_skipa�Whether or not to use PyTorch Fully Sharded Data Parallel (FSDP) training (in distributed training only). The base option should be `full_shard`, `shard_grad_op` or `no_shard` and you can add CPU-offload to `full_shard` or `shard_grad_op` like this: full_shard offload` or `shard_grad_op offload`. You can add auto-wrap to `full_shard` or `shard_grad_op` with the same syntax: full_shard auto_wrap` or `shard_grad_op auto_wrap`.�fsdpz�This parameter is deprecated. FSDP's minimum number of parameters for Default Auto Wrapping. (useful only when `fsdp` field is passed).�fsdp_min_num_paramsz�Config to be used with FSDP (Pytorch Fully Sharded Data Parallel). The value is either a fsdp json config file (e.g., `fsdp_config.json`) or an already loaded json file as `dict`.rhz�This parameter is deprecated. Transformer layer class name (case-sensitive) to wrap, e.g, `BertLayer`, `GPTJBlock`, `T5Block` .... (useful only when `fsdp` flag is passed).�"fsdp_transformer_layer_cls_to_wrapz�Config to be used with the internal Accelerator object initializtion. The value is either a accelerator json config file (e.g., `accelerator_config.json`) or an already loaded json file as `dict`.rgz�Enable deepspeed and pass the path to deepspeed json config file (e.g. `ds_config.json`) or an already loaded json file as a dictrizEThe label smoothing epsilon to apply (zero means no label smoothing).�label_smoothing_factorr[zThe optimizer to use.�optimz*Optional arguments to supply to optimizer.� optim_argsz-Whether or not to replace AdamW by Adafactor.r\zRWhether or not to group samples of roughly the same length together when batching.�group_by_length�lengthzDColumn name with precomputed lengths to use when grouping by length.�length_column_namez;The list of integrations to report the results and logs to.� report_toztWhen using distributed training, the value of the flag `find_unused_parameters` passed to `DistributedDataParallel`.�ddp_find_unused_parameterszkWhen using distributed training, the value of the flag `bucket_cap_mb` passed to `DistributedDataParallel`.�ddp_bucket_cap_mbzoWhen using distributed training, the value of the flag `broadcast_buffers` passed to `DistributedDataParallel`.�ddp_broadcast_buffersz,Whether or not to pin memory for DataLoader.�dataloader_pin_memoryz�If True, the data loader will not shut down the worker processes after a dataset has been consumed once. This allows to maintain the workers Dataset instances alive. Can potentially speed up training, but will increase RAM usage.�dataloader_persistent_workerszDWhether or not to skip adding of memory profiler reports to metrics.�skip_memory_metricsz@Whether or not to use the legacy prediction_loop in the Trainer.�use_legacy_prediction_loopzKWhether or not to upload the trained model to the model hub after training.� push_to_hubz<The path to a folder with a valid checkpoint for your model.�resume_from_checkpointzGThe name of the repository to keep in sync with the local `output_dir`.� hub_model_id� every_savez:The hub strategy to use when `--push_to_hub` is activated.� hub_strategyz*The token to use to push to the Model Hub.� hub_tokenz�Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.�hub_private_repozTUnless `True`, the Trainer will skip pushes if the previous one wasn't finished yet.�hub_always_pushzZIf True, use gradient checkpointing to save memory at the expense of slower backward pass.�gradient_checkpointingz�Gradient checkpointing key word arguments such as `use_reentrant`. Will be passed to `torch.utils.checkpoint.checkpoint` through `model.gradient_checkpointing_enable`.rjuuThis argument is deprecated and will be removed in version 5 of 🤗 Transformers. Use `include_for_metrics` instead.�include_inputs_for_metricszrList of strings to specify additional data to include in the `compute_metrics` function.Options: 'inputs', 'loss'.�include_for_metricsz�Whether to recursively concat inputs/losses/labels/predictions across batches. If `False`, will instead store them as lists, with each batch kept separate.�eval_do_concat_batchesz.Deprecated. Use half_precision_backend instead� fp16_backendz'Deprecated. Use `eval_strategy` instead�evaluation_strategyz7The name of the repository to which push the `Trainer`.�push_to_hub_model_idzAThe name of the organization in with to which push the `Trainer`.�push_to_hub_organization�push_to_hub_token)�init�reprrM�_n_gpuzKUsed by the SageMaker launcher to send mp-specific args. Ignored in Trainer� mp_parametersz�Whether to automatically decrease the batch size in half and rerun the training loop again each time a CUDA Out-of-Memory was reached�auto_find_batch_sizez�Whether to call enable_full_determinism instead of set_seed for reproducibility in distributed training. Important: this will negatively impact the performance, so only use it for debugging.�full_determinismzCThis argument is deprecated, use `--torch_compile_backend` instead.� torchdynamo�lastayThe scope to use when doing hyperparameter search with Ray. By default, `"last"` will be used. Ray will then use the last checkpoint of all trials, compare those, and select the best one. However, other options are also available. See the Ray documentation (https://docs.ray.io/en/latest/tune/api_docs/analysis.html#ray.tune.ExperimentAnalysis.get_best_trial) for more options.� ray_scopeizZOverrides the default timeout for distributed training (value should be given in seconds).� ddp_timeoutz?If set to `True`, the model will be wrapped in `torch.compile`.� torch_compilezXWhich backend to use with `torch.compile`, passing one will trigger a model compilation.�torch_compile_backendzUWhich mode to use with `torch.compile`, passing one will trigger a model compilation.�torch_compile_modezDDeprecated. Pass {'dispatch_batches':VALUE} to `accelerator_config`.�dispatch_batchesz@Deprecated. Pass {'split_batches':True} to `accelerator_config`.� split_batcheszVIf set to `True`, the speed metrics will include `tgs` (tokens per second per device).�include_tokens_per_secondzyIf set to `True`, will track the number of input tokens seen throughout training. (May be slower in distributed training)�include_num_input_tokens_seenaUActivates neftune noise embeddings into the model. NEFTune has been proven to drastically improve model performances for instrcution fine-tuning. Check out the original paper here: https://arxiv.org/abs/2310.05914 and the original code here: https://github.com/neelsjain/NEFTune. Only supported for `PreTrainedModel` and `PeftModel` classes.�neftune_noise_alphazsTarget modules for the optimizer defined in the `optim` argument. Only used for the GaLore optimizer at the moment.�optim_target_modulesz;Break eval metrics calculation into batches to save memory.�batch_eval_metricszhWhether to run through the entire `evaluation` step at the very beginning of training as a sanity check.� eval_on_startz=Whether or not to enable the Liger Kernel for model training.�use_liger_kernelzgWhether to run recursively gather object in a nested list/tuple/dictionary of objects from all devices.�eval_use_gather_objectz�Whether or not to average tokens across devices. If enabled, will use all_reduce to synchronize num_tokens_in_batch for precise loss calculation. Reference: https://github.com/huggingface/transformers/issues/34242�average_tokens_across_devicesc Cs<tD] }t||�}t|t�r"|�d�r"t�|�}t|�}t|||�q|j dur0t j � |j �|_ |j durD|j durDt j �|j t��|_ |j durQt j � |j �|_ |jdur^t��tjk|_|jdurmt�dt�|j|_t|jt�r~t�dt�|jj|_|jr�t�dt�|j|_t|j�|_t|j�|_t |j!�|_!t"|j#�|_#t$|j%�|_%|j&dur�|jtj'kr�d|_&|j(dur�t|j(t)�s�|j(dks�t*d|j(�d ���|jtj+kr�|j,dus�|j,dkr�|j-dkr�t�.d |j-���|j-|_,n t*d |j�d ���|jtj+k�r|j-dk�rt*d |j�d���|jtj+k�r6|j-dk�r6|j-t)|j-�k�r0t*d|j-����t)|j-�|_-|jtj+k�rZ|j,dk�rZ|j,t)|j,�k�rTt*d|j,����t)|j,�|_,|j!t j+k�r~|j/dk�r~|j/t)|j/�k�rxt*d|j/����t)|j/�|_/|j0�r�|j|j!k�r�t*d|j�d|j!����|jtj+k�r�|j/|j,dk�r�|j,dk�s�|j/dk�r�|j,dk�r�|j/dk�s�t*d|j/�d|j,�d ���d}|j/||j,|dk�r�t*d|j/�d|j,�d ���t*d|j/�d|j,�d ���t1�}|j2�r|�st*d|j2�d���|j2�s|�rt�.d|j2�d��|j0�s"|j%t$j3k�r+|j4du�r+d |_4|j5du�r?|j4du�r?|j4�6d � |_5|j7du�rI|j |_7|j8d!k�r�t9��r�|j:�rg|j:d"k�rgt�d#t�|j:|_;|j<�so|j=�r�|j�rt>��st?��st*d$��|j�s�t@jA�B��r�tC��s�t*d%��tD��s�dd&lEmF}|�s�t*d'��|jG�r�|j<�r�t*d(��|jH�r�|j=�r�t*d)��|j<�r�|j;d*k�r�t*d+��|j%t$j3k�r�|jtj'k�r�t*d,��t9��s�t*d-��tI|jJ�|_J|jK�r�t�d.t�tIjL|_J|jJtIjMk�r-t9��r-tN�OtN�Ot@jP�jQ�tN�Od/�k�rt*d0��tN�OtN�Ot@jP�jQ�tN�Od/�k�r-|jG�r-t*d1��tR��r�t|jStT��sf|jSdu�rCtT�|_Sn#t|jStU��rTtTd�i|jS��|_Snt|jStV��r_tWd2��tT�X|jS�|_S|jYdu�rwt�d3t�|jY|jS_Y|jZdu�r�t�d4t�|jZ|jS_Z|j8d!k�r�t9��r�|j[|j\�r�z|j]dk�r�t�^d5�d|_\Wnt_�y�}zt�^d6|�d7��d|_\WYd}~nd}~ww|j`du�r�t�d8t�|j`|_a|jbdu�s�|jadu�r�|jc�s�d|_c|jc�r�|jadu�r�d9|_a|jc�rd:}|jat jd|d;<|jbdu�r|jbt jd|d<<|j8d!k�rKt9��rK|jc�rKte��rF|jfdu�r1|jG�r5|j<�rEt�.d=�dt@jgjAjh_idt@jgjj_int�^d>�|j8d!k�r�t9��r�|jfdu�r�|jf�rste��rodt@jgjAjh_idt@jgjj_int*d?��te��r�dt@jgjAjh_idt@jgjj_i|j;d*k�r�t jd�kd@dA�} |jG�r�dB} n|j<�r�dC} | t jdd@<|jldu�r�t�.dD�dE|_l|jldEk�s�|jldEgk�r�ddFlmmn} | �|_ldG|jlv�r�t@jNjo�r�t�^dH�|jl�pdG�n|jldIk�s�|jldIgk�r�g|_ln t|jltq��s�|jlg|_l|jrdk�s|jrdk�r t*dJ��|jrdk�r|jsdk�rt�.dK�t|jst)��r(|jsdk�r,t*dL��t|jttu��r>|jt�r;tvjwgndM|_tt|jtt��rPdNdO�|jt�x�D�|_t|jttvjygk�r\t*dP��tvjw|jtv�rntvjz|jtv�rnt*dQ��|j{�r�tvjw|jtv�s�tvj||jtv�r�t�^dR�|j}du�r�i|_}t|j}t��r�t~|jt�dk�r�t�dS�tj�|j}dTdUdV��.} t��| �|_}tq|j}����D]} | �dW��r�|j}��| �} | |j}| dXd�<�q�Wd�n 1�s�wY|j�dk�r�t�dYt�t�|j}�kdZd�|j��|j}dZ<t|j}�kd[d�t��r|j}d[g|j}d[<|j�du�r*t�d\t�|j}�kd[g�|j�g|j}d[<t~|jt�dk�r?|j}dZdk�r?t�d]�t~|jt�dk�rV|j}�kd[d�du�rVt�d^�t~|jt�dk�rt|j}dZdk�rt|j}�kd[d�du�rtt*d_��|j}�kd`d�|j}d`<|j}�kdad�|j}da<|j}�kdbd�|j}db<|j}d`�r�t~|jt�dk�r�|j}�kdci����|_�dd|j�v�r�tt@|j�dd�|j�dd<de|j�v�r�tt@|j�de�|j�de<nt�df�n |j}db�r�t�dg�t~|jt�dk�r�|j}d`�s�dht jddi<ddjl�m�}m�}dk}|jtD]v}|���|v�rt|��|����d�t jd|�dl�<�q�|tvjyk�r*dht jd|�dm�<�q�|tvj�k�rs|dt jd|�dn�<|j}dZdk�r[t|j}dZ�t jd|�do�<|dt jd|�dn�<�q�|j}�kd[d�du�rsdp�|j}d[�t jd|�dq�<�q�|j}�kdrds�}|���t jd|�dt�<t|j}�kdudv�����t jd|�dw�<t|j}�kdxdh�����}t|j}�kdydv�����}|dvk�r�|dhk�r�t*dz��|t jd|�d{�<|t jd|�d|�<t|j}�kd}dh�����t jd|�d~�<|j��r�t�dt�|j�du�r�d�|_�n|j�d�7_�d|_�t|j�t��r d�dO�|j��x�D�|_�n |j�du�rg|_�d|_�|j��rNtR��s)t*d�t��d����dd�l�m�}||j��|_�|j���|�dd�l�m�}dht jdd�<||j�d��|_�n&t�t jd�kd�dv���rtdd�l�m�}|�|_�t jd�kd@dA�}|j���|�|j����|j�r{d|_�t9��r�t��r�|j�dk�r�|j�du�r�t*d���|j�du�r�t�d�t�|j�|_�|j�du�r�t�|j�|j�|j�d��|_�|j�du�r�t�d�|j��d��t�n*t�d�|j��d��t�n|j�du�r�|j��d�t�|j �j���|_�t�d�|j��d��t�|j��r�tRd���s�t*d���|j�du� r tRd��� s tWd���|j�� rt�^d��|j���d��dSdS)�N�{uy`evaluation_strategy` is deprecated and will be removed in version 4.46 of 🤗 Transformers. Use `eval_strategy` insteadu�using `EvaluationStrategy` for `eval_strategy` is deprecated and will be removed in version 5 of 🤗 Transformers. Use `IntervalStrategy` insteadulusing `no_cuda` is deprecated and will be removed in version 5.0 of 🤗 Transformers. Use `use_cpu` insteadFTrz@`torch_empty_cache_steps` must be an integer bigger than 0, got roz4using `logging_steps` to initialize `eval_steps` to zevaluation strategy z9 requires either non-zero --eval_steps or --logging_stepszlogging strategy z" requires non-zero --logging_stepsrz5--logging_steps must be an integer if bigger than 1: z2--eval_steps must be an integer if bigger than 1: z2--save_steps must be an integer if bigger than 1: zh--load_best_model_at_end requires the save and eval strategy to match, but found - Evaluation strategy: z - Save strategy: z�--load_best_model_at_end requires the saving steps to be a multiple of the evaluation steps, which cannot get guaranteed when mixing ratio and absolute steps for save_steps z and eval_steps i@Bzg--load_best_model_at_end requires the saving steps to be a multiple of the evaluation steps, but found z, which is not a multiple of zm--load_best_model_at_end requires the saving steps to be a round multiple of the evaluation steps, but found z#, which is not a round multiple of z--save_safetensors=z& requires safetensors to be installed!z7Found safetensors installation, but --save_safetensors=z�. Safetensors should be a preferred weights saving format due to security and performance reasons. If your model cannot be saved by safetensors please feel free to open an issue at https://github.com/huggingface/safetensors!�lossr}r�ux`fp16_backend` is deprecated and will be removed in version 5 of 🤗 Transformers. Use `half_precision_backend` insteadzLYour setup doesn't support bf16/(cpu, tpu, neuroncore). You need torch>=1.10z[Your setup doesn't support bf16/gpu. You need torch>=1.10, using Ampere GPU with cuda>=11.0)�#is_torch_greater_or_equal_than_1_12zbYour setup doesn't support bf16/xpu. You need torch>=1.12, using Intel XPU/GPU with IPEX installedz6At most one of fp16 and bf16 can be True, but not bothzDAt most one of fp16 and bf16 can be True for full eval, but not bothr�zD `--half_precision_backend apex`: GPU bf16 is not supported by apex.z@lr_scheduler_type reduce_lr_on_plateau requires an eval strategyz<lr_scheduler_type reduce_lr_on_plateau requires torch>=0.2.0ur`--adafactor` is deprecated and will be removed in version 5 of 🤗 Transformers. Use `--optim adafactor` insteadz2.0.0z8--optim adamw_torch_fused requires PyTorch 2.0 or higherz:--optim adamw_torch_fused with --fp16 requires PyTorch>2.0z�Tried passing in a callable to `accelerator_config`, but this is not supported. Please pass in a fully constructed `AcceleratorConfig` object instead.u�Using `--dispatch_batches` is deprecated and will be removed in version 4.41 of 🤗 Transformers. Use `--accelerator_config {'dispatch_batches':VALUE} insteadu�Using `--split_batches` is deprecated and will be removed in version 4.41 of 🤗 Transformers. Use `--accelerator_config {'split_batches':VALUE} insteadzsaverage_tokens_across_devices is set to True but it is invalid when world size is1. Turn it to False automatically.z"Can not specify world size due to z.. Turn average_tokens_across_devices to False.uv`torchdynamo` is deprecated and will be removed in version 5 of 🤗 Transformers. Use `torch_compile_backend` instead�inductorZACCELERATE_DYNAMO_�BACKEND�MODEz`Setting TF32 in CUDA backends to speedup torch compile, you won't see any improvement otherwise.zaThe speedups for torchdynamo mostly come wih GPU Ampere or higher and which is not detected here.zC--tf32 requires Ampere or a newer GPU arch, cuda>=11 and torch>=1.7ZACCELERATE_MIXED_PRECISIONr�r�r�a The default value for the training argument `--report_to` will change in v5 (from all installed integrations to none). In v5, you will need to use `--report_to all` to get the same behavior as now. You should start updating your code and make this info disappear :-).�all)�$get_available_reporting_integrations� codecarbonaRWhen using the Trainer, CodeCarbonCallback requires the `codecarbon` package, which is not compatible with AMD ROCm (https://github.com/mlco2/codecarbon/pull/490). Automatically disabling the codecarbon callback. Reference: https://huggingface.co/docs/transformers/v4.39.3/en/main_classes/trainer#transformers.TrainingArguments.report_to.�nonez$warmup_ratio must lie in range [0,1]zoBoth warmup_ratio and warmup_steps given, warmup_steps will override any effect of warmup_ratio during trainingzEwarmup_steps must be of type int and must be 0 or a positive integer.rpcS�g|]}t|��qSrG)r��.0�srGrGrH� <listcomp>`�z3TrainingArguments.__post_init__.<locals>.<listcomp>z�`--fsdp offload` can't work on its own. It needs to be added to `--fsdp full_shard` or `--fsdp shard_grad_op`. For example, `--fsdp "full_shard offload"`.zB`--fsdp full_shard` is not compatible with `--fsdp shard_grad_op`.aWhen using FSDP full shard, instead of using `gradient_checkpointing` in TrainingArguments, please use `activation_checkpointing` in `fsdp_config`. The former introduces a redundant AllGather operation in backward pass. Reference: https://github.com/huggingface/transformers/issues/30404z:`--fsdp_config` is useful only when `--fsdp` is specified.�rzutf-8)�encodingZfsdp_�zEusing `--fsdp_min_num_params` is deprecated. Use fsdp_config instead �min_num_paramsZtransformer_layer_cls_to_wrapzTusing `--fsdp_transformer_layer_cls_to_wrap` is deprecated. Use fsdp_config instead z;`min_num_params` is useful only when `--fsdp` is specified.zJ`transformer_layer_cls_to_wrap` is useful only when `--fsdp` is specified.zL`min_num_params` and `transformer_layer_cls_to_wrap` are mutually exclusive.r9Z xla_fsdp_v2Zxla_fsdp_grad_ckptZxla_fsdp_settings� compute_dtype� buffer_dtypez5XLA FSDP can be used only when `--fsdp` is specified.zB`--xla_fsdp_grad_ckpt` is useful only when `--xla` is set to true.rm�ACCELERATE_USE_FSDP)�FSDP_AUTO_WRAP_POLICY�FSDP_SHARDING_STRATEGYZFSDP_ZSHARDING_STRATEGYZOFFLOAD_PARAMSZAUTO_WRAP_POLICYZMIN_NUM_PARAMS�,ZTRANSFORMER_CLS_TO_WRAP�backward_prefetchZ NO_PREFETCHZBACKWARD_PREFETCH�forward_prefetchrnZFORWARD_PREFETCH�sync_module_states�cpu_ram_efficient_loadingzP`sync_module_states` must be `"True"` if `cpu_ram_efficient_loading` is `"True"`ZSYNC_MODULE_STATESZCPU_RAM_EFFICIENT_LOADING�use_orig_paramsZUSE_ORIG_PARAMSu�using `--tpu_metrics_debug` is deprecated and will be removed in version 5 of 🤗 Transformers. Use `--debug tpu_metrics_debug` insteadz tpu_metrics_debugcSr!rGrr"rGrGrHr%�r&zK--deepspeed requires Accelerate to be installed: `pip install 'accelerate>=z'`.)�HfTrainerDeepSpeedConfig)�DeepSpeedPlugin�ACCELERATE_USE_DEEPSPEED)� hf_ds_configz�--dataloader_prefetch_factor can only be set when data is loaded in a different process, i.e. when --dataloader_num_workers > 1.uu`--push_to_hub_token` is deprecated and will be removed in version 5 of 🤗 Transformers. Use `--hub_token` instead.)� organization�tokenu�`--push_to_hub_model_id` and `--push_to_hub_organization` are deprecated and will be removed in version 5 of 🤗 Transformers. Use `--hub_model_id` instead and pass the full repo name to this argument (in this case z).u�`--push_to_hub_model_id` is deprecated and will be removed in version 5 of 🤗 Transformers. Use `--hub_model_id` instead and pass the full repo name to this argument (in this case �/u�`--push_to_hub_organization` is deprecated and will be removed in version 5 of 🤗 Transformers. Use `--hub_model_id` instead and pass the full repo name to this argument (in this case z0.30.0z�--eval_use_gather_object requires Accelerate to be version of `accelerate` > 0.30.0.This is not supported and we recommend you to update your version.z1.1.0zdata_seed requires Accelerate version `accelerate` >= 1.1.0. This is not supported and we recommend you to update your version.u�Using `include_inputs_for_metrics` is deprecated and will be removed in version 5 of 🤗 Transformers. Please use `include_for_metrics` list argument instead.�inputsrG)��_VALID_DICT_FIELDS�getattrrrru� startswith�json�loadsrt�setattrr�rBrC� expanduserr�rDrIr��logger�getEffectiveLevelr,�WARNr��warnings�warn� FutureWarningr�rr{r�r�rr�rr�rr�rr�r��NOr�rJ� ValueError�STEPSr�r��infor�r�rr�ZREDUCE_ON_PLATEAUr�r��endswithr�� frameworkr!r�r�r�r�r"r*�torch�cuda� is_availabler#r+� pytorch_utilsrr�r�rZr�r\rerdr�parse� __version__� base_versionrrgr6rsrV�NotImplementedError�from_json_filer r rQr� world_sizer�� ImportErrorrr r r rKr)r��backends�matmul� allow_tf32�cudnnrLr�� integrationsr�hip�remove�listr�r�r��boolr� FULL_SHARDrXZOFFLOAD� SHARD_GRAD_OPr�� HYBRID_SHARDrh�len�io�open�load�keys�popr��maxr��copyZxla_fsdp_configZaccelerate.utils.constantsr.r/�upper�indexZ AUTO_WRAPrvr�r��deepspeed_pluginrirZ#transformers.integrations.deepspeedr6�hf_deepspeed_config�trainer_config_process�accelerate.utilsr7r.Zset_mixed_precisionZset_deepspeed_weakrefr�r2r�r�r�r�r�rr�r�r�namerr�r�r��append)�selfrrlZ loaded_dictZLARGE_MULTIPLIERZsafetensors_availablerrN�prefixZmixed_precision_dtyper�f�k�vr.r/Z fsdp_optionZprefetch_policyr3r4r6r7�mixed_precisionrGrGrH� __post_init__ s�   �    � � �       �    �   ��� ��������� ��  �� �  � (  � �  �  ���� �  �  ��        � � � ���     ���   �� �  $    �     �  ��""�   �        ��  � �  � ���� ���  ���zTrainingArguments.__post_init__cCsVt|�}|d=|d=dd�|��D�}dd�t|���D�}|jj�dd�|��d �S) Nr�r�cSs0i|]\}}||�d�rd|���d�n|�qS)�_token�<�>)rOrp�r#r{r|rGrGrH� <dictcomp>Ss0z-TrainingArguments.__str__.<locals>.<dictcomp>cSs g|] \}}|�d|�d��qS)�=z, rGr�rGrGrHr%Us z-TrainingArguments.__str__.<locals>.<listcomp>z( rp�))rrq�sorted� __class__r`rD)rxZ self_as_dictZ attrs_as_strrGrGrH�__str__Ks zTrainingArguments.__str__r;cC�0|jrt�d�|jp |j}|td|j�}|S)zz The actual batch size for training (may differ from `per_gpu_train_batch_size` in distributed training). z�Using deprecated `--per_gpu_train_batch_size` argument which will be removed in a future version. Using `--per_device_train_batch_size` is preferred.r)r�rEr�r�rn�n_gpu)rx�per_device_batch_size�train_batch_sizerGrGrHr�Z�� z"TrainingArguments.train_batch_sizecCr�)z{ The actual batch size for evaluation (may differ from `per_gpu_eval_batch_size` in distributed training). z�Using deprecated `--per_gpu_eval_batch_size` argument which will be removed in a future version. Using `--per_device_eval_batch_size` is preferred.r)r�rEr�r�rnr�)rxr��eval_batch_sizerGrGrHr�hr�z!TrainingArguments.eval_batch_sizecCs t|jd�S)zt The actual timeout for torch.distributed.init_process_group since it expects a timedelta variable. ��seconds)rr�rxrGrGrH�ddp_timeout_deltavs z#TrainingArguments.ddp_timeout_deltarRcCs�t|dg�t�d�t�st�stdt�d���ddd�}t|jt �r-|j� dd�|d<|drPt j ikr:t d ��t |jd �|_|jrO|jjtjkrOtd ��n tjdd �d|_|jsfd tjvrfdtjd <d|_|jsuttj�dd��r�d|d<|j|d<d|_n=t�r�d|d<t��}t �!d|�}t j"�#|�n%t$�r�d|d<n|jr�d|d<t%|j&d�|d<n |j|d<t%|j&d�|d<|� dd�r�|� dd�s�|� dd�}|r�dtjd<t d)i|��|_|r�tjd=t�s�|jj!}|jj'|_t(�)��rt(�*��r|j+t,j-k�rt�.d�t/��r|jj!}d|_|St$��st��r |S|jjtj0k�r�|j1�r;t2�3d�|j4dk�r;t d ��|j�rFt �!d�}|St5��rQt �!d�}|St6��rot7��sbtd!��sbtd"��t �!d#�}t j8�#|�|St9��r�t �!d$�}t j:�#|�|St;��r�t �!d%�}t j<�#|�|St=��r�t �!d&�}t j>�#|�|St �!t j"�)��r�d'ntj�d(d��}t j"�?�|_|j4dk�r�t j"�#|�|S)*NrQzPyTorch: setting up devicesz9Using the `Trainer` with `PyTorch` requires `accelerate>=zg`: Please run `pip install transformers[torch]` or `pip install 'accelerate>={ACCELERATE_MIN_VERSION}'`TF)�enabled�use_configured_stater�z�Passing `'use_configured_state':True` to the AcceleratorConfig requires a pre-configured `AcceleratorState` or `PartialState` to be defined before calling `TrainingArguments`. )rSaTried to use an already configured `Accelerator` or `PartialState` that was not initialized for DeepSpeed, but also passed in a `deepspeed` configuration to the `TrainingArguments`. Please set `use_configured_state:False` instead or setup your `Accelerator` or `PartialState` properly.)Zreset_partial_stateZACCELERATE_USE_IPEXrnrZACCELERATE_USE_CPU�FalserSr:rr�rRZ_use_sagemaker_dp� use_deepspeedr��timeoutrmr8z�torch.distributed process group is initialized, but parallel_mode != ParallelMode.DISTRIBUTED. In order to use Torch DDP, launch your script with `python -m torch.distributed.launchu�`use_mps_device` is deprecated and will be removed in version 5.0 of 🤗 Transformers. `mps` device will be used by default if available similar to the way `cuda` device is used.Therefore, no action from user is required. �mpsz�Either you do not have an MPS-enabled device on this machine or MacOS version is not 12.3+ or current PyTorch install was not built with MPS enabled.z 0.32.0.devz?Using the XPU PyTorch backend requires `accelerate>=0.32.0.dev`zxpu:0zmlu:0zmusa:0znpu:0zcuda:0ZACCELERATE_TORCH_DEVICErG)@r-rErNr rr[rrrrgr6rmr4� _shared_staterLr��distributed_stateri�distributed_typer5Z DEEPSPEED� RuntimeErrorr3� _reset_stater�rBrKrr.rLr��smpr�rQrQrR� set_devicerrr�local_process_index�distrS�is_initialized� parallel_mode� ParallelMode� DISTRIBUTEDr�r*rKr�rHrIrVr%r+r�xpur$�mlur&�musar(�npu� device_count)rxZaccelerator_state_kwargsr�rQr�rGrGrH�_setup_devices}s�   �  � ���      �   "�1�.�� �  � �  �  �  �  ��   z TrainingArguments._setup_devicescCst|dg�|jS)z2 The device used by this process. rQ)r-r�r�rGrGrHrQ�s zTrainingArguments.devicecCs"t|dg�t|d�s|j}|jS)a The number of GPUs used by this process. Note: This will only be greater than one when you have multiple GPUs available but are not using distributed training. For distributed training, it will always be 1. rQr)r-�hasattrr�r)rxr>rGrGrHr� s zTrainingArguments.n_gpucCsxt|dg�t�r tjSt�rtjSt�rtjS|jdur$|jj t j ks.|jdur1|j dkr1tj S|jdkr9tjStjS)a� The current mode used for parallelism if multiple GPUs/TPU cores are available. One of: - `ParallelMode.NOT_PARALLEL`: no parallelism (CPU or one GPU). - `ParallelMode.NOT_DISTRIBUTED`: several GPUs in one single process (uses `torch.nn.DataParallel`). - `ParallelMode.DISTRIBUTED`: several GPUs, each having its own process (uses `torch.nn.DistributedDataParallel`). - `ParallelMode.TPU`: several TPU cores. rQNr1r)r-r*r��TPUr �SAGEMAKER_MODEL_PARALLELr�SAGEMAKER_DATA_PARALLELr�r�r5rKr�r�r��NOT_DISTRIBUTED� NOT_PARALLELr�rGrGrHr� s  zTrainingArguments.parallel_modecC�Bt|dg�|jdur|jjSt�rtjjjst��St� �SdS)z; The number of processes used in parallel. rQNr) r-r�� num_processesr r��state�cfg�prescaled_batchZdp_sizeZrdp_sizer�rGrGrHrZ. �  zTrainingArguments.world_sizecCr�)z8 The index of the current process used. rQNr) r-r�� process_indexr r�r�r�r�Zdp_rankZrdp_rankr�rGrGrHr�: r�zTrainingArguments.process_indexcCs0t|dg�|jdur|jjSt�rt��SdS)z6 The index of the local process used. rQNr)r-r�r�r r�r�r�rGrGrHr�F s  z%TrainingArguments.local_process_indexcC�,|jr|jdkSt�rt��dkS|jdkS)zH Whether or not the current process should produce log. r)r�r�r r��rankr�r�rGrGrH� should_logS �    zTrainingArguments.should_logcCr�)zp Whether or not the current process should write to disk, e.g., to save models and checkpoints. r)r�r�r r�r�r�r�rGrGrH� should_save` r�zTrainingArguments.should_savecCsJt|j}t|j}|dkrt��n|}|dkrt��n|}|jr#|S|S)a` Returns the log level to be used depending on whether this process is the main process of node 0, main process of node non-0, or a non-main process. For the main process the log level defaults to the logging level set (`logging.WARNING` if you didn't do anything) unless overridden by `log_level` argument. For the replica processes the log level defaults to `logging.WARNING` unless overridden by `log_level_replica` argument. The choice between the main and replica process settings is made according to the return value of `should_log`. r1)�trainer_log_levelsr�r�r,� get_verbosityr�)rxr�r�Zlog_level_main_nodeZlog_level_replica_noderGrGrH�get_process_log_levelm s  z'TrainingArguments.get_process_log_levelcCst� S)zR Can be subclassed and overridden for some specific integrations. )r r�rGrGrH�place_model_on_device� sz'TrainingArguments.place_model_on_devicecCs|jp t�p t�p t� S)zc Whether or not to use no_sync for the gradients when doing gradient accumulation. )rirr r'r�rGrGrH�!_no_sync_in_gradient_accumulation� s�z3TrainingArguments._no_sync_in_gradient_accumulation�workccs$�t�r�|jdkr�|r dnd}|jdur|r|jjn|jj}n t�r(t��dk}zD|sFt� |j �d|�d|���t �rBt � |�nt��dVW|rkt� |j �d|�d |�d ��t �ret � |�dSt��dSdS|r�t� |j �d|�d |�d ��t �r�t � |�wt��wwdVdS) ax A context manager for torch distributed environment where on needs to do something on the main process, while blocking replicas, and when it's finished releasing the replicas. One such use is for `datasets`'s `map` feature which to be efficient should be run once on the main process, which upon completion saves a cached version of results and which then automatically gets loaded by the replicas. Args: local (`bool`, *optional*, defaults to `True`): if `True` first means process of rank 0 of each node if `False` first means process of rank 0 of node rank 0 In multi-node environment with a shared filesystem you most likely will want to use `local=False` so that only the main process of the first node will do the processing. If however, the filesystem is not shared, then the main process of each node will need to do the processing, which is the default behavior. desc (`str`, *optional*, defaults to `"work"`): a work description to be used in debug logs rzmain local processz main processNrz: waiting for the z to perform z: z completed z, releasing all replicas)r!rZr�Zis_local_main_process�is_main_processr r�r�rEr�r�r*rW� rendezvousr��barrier)rx�local�descZmain_process_descr�rGrGrH�main_process_first� s6�  �   �  � z$TrainingArguments.main_process_first�num_training_stepscCs(|jdkr |j}|St�||j�}|S)z? Get number of steps used for a linear warmup. r)r��math�ceilr�)rxr�r�rGrGrH�get_warmup_steps� s ���z"TrainingArguments.get_warmup_steps�dcCs^|�dd�durt|dt�st|d��d�d|d<|��D] }t|t�r,|�|�q dS)a. Checks whether the passed dictionary and its nested dicts have a *torch_dtype* key and if it's not None, converts torch.dtype to a string of just the type. For example, `torch.float32` get converted into *"float32"* string, which can then be stored in the json format. � torch_dtypeNror)rLrrrurX�valuesrs�_dict_torch_dtype_to_str)rxr�r{rGrGrHr�� s   ��z*TrainingArguments._dict_torch_dtype_to_strcs��fdd�t��D�}|��D]F\}}t|t�r|j||<t|t�r8t|�dkr8t|dt�r8dd�|D�||<|�d�rGd|���d�||<t �rUt|t �rU|� �||<q�� |�|S) z� Serializes this instance while replace `Enum` by their values (for JSON serialization support). It obfuscates the token values by removing their value. cs"i|] }|jr|jt�|j��qSrG)r�rvr?)r#rr�rGrHr�� s"z-TrainingArguments.to_dict.<locals>.<dictcomp>rcSsg|]}|j�qSrG)r{)r#�xrGrGrHr%� sz-TrainingArguments.to_dict.<locals>.<listcomp>rr�r�) rrqrrrr{rcrhrOrprr6�to_dictr�)rxr�r{r|rGr�rHr�� s  $  � zTrainingArguments.to_dictcCstj|��dd�S)z< Serializes this instance to a JSON string. r�)�indent)rA�dumpsr�r�rGrGrH�to_json_string� sz TrainingArguments.to_json_stringcsR|��}i|�|j|jd��}ttttg�t�r��t j ��fdd�|� �D�S)uM Sanitized serialization to use with TensorBoard’s hparams )r�r�cs*i|]\}}|t|��vr|nt|��qSrG)rVrur��� valid_typesrGrHr� s*z7TrainingArguments.to_sanitized_dict.<locals>.<dictcomp>) r�r�r�rdrJryrur!rwrQ�Tensorrq)rxr�rGr�rH�to_sanitized_dict� s   z#TrainingArguments.to_sanitized_dict�� batch_size� num_epochsc Cs:d|_||_||_||_||_||_||_||_||_|S)a� A method that regroups all basic arguments linked to the training. <Tip> Calling this method will automatically set `self.do_train` to `True`. </Tip> Args: learning_rate (`float`, *optional*, defaults to 5e-5): The initial learning rate for the optimizer. batch_size (`int` *optional*, defaults to 8): The batch size per device (GPU/TPU core/CPU...) used for training. weight_decay (`float`, *optional*, defaults to 0): The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in the optimizer. num_train_epochs(`float`, *optional*, defaults to 3.0): Total number of training epochs to perform (if not an integer, will perform the decimal part percents of the last epoch before stopping training). max_steps (`int`, *optional*, defaults to -1): If set to a positive number, the total number of training steps to perform. Overrides `num_train_epochs`. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) until `max_steps` is reached. gradient_accumulation_steps (`int`, *optional*, defaults to 1): Number of updates steps to accumulate the gradients for, before performing a backward/update pass. <Tip warning={true}> When using gradient accumulation, one step is counted as one step with backward pass. Therefore, logging, evaluation, save will be conducted every `gradient_accumulation_steps * xxx_step` training examples. </Tip> seed (`int`, *optional*, defaults to 42): Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use the [`~Trainer.model_init`] function to instantiate the model if it has some randomly initialized parameters. gradient_checkpointing (`bool`, *optional*, defaults to `False`): If True, use gradient checkpointing to save memory at the expense of slower backward pass. Example: ```py >>> from transformers import TrainingArguments >>> args = TrainingArguments("working_dir") >>> args = args.set_training(learning_rate=1e-4, batch_size=32) >>> args.learning_rate 1e-4 ``` T) r�r�r�r�r�r�r�r�r�) rxr�r�r�r�r�r�r�r�rGrGrH� set_training s@zTrainingArguments.set_training�strategy�accumulation_steps�delay� loss_only�jit_modecCs\t|�|_|jtjkr|dkrtd��|jtjk|_||_||_||_||_ ||_ ||_ |S)al A method that regroups all arguments linked to evaluation. Args: strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"no"`): The evaluation strategy to adopt during training. Possible values are: - `"no"`: No evaluation is done during training. - `"steps"`: Evaluation is done (and logged) every `steps`. - `"epoch"`: Evaluation is done at the end of each epoch. Setting a `strategy` different from `"no"` will set `self.do_eval` to `True`. steps (`int`, *optional*, defaults to 500): Number of update steps between two evaluations if `strategy="steps"`. batch_size (`int` *optional*, defaults to 8): The batch size per device (GPU/TPU core/CPU...) used for evaluation. accumulation_steps (`int`, *optional*): Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU. If left unset, the whole predictions are accumulated on GPU/TPU before being moved to the CPU (faster but requires more memory). delay (`float`, *optional*): Number of epochs or steps to wait for before the first evaluation can be performed, depending on the eval_strategy. loss_only (`bool`, *optional*, defaults to `False`): Ignores all outputs except the loss. jit_mode (`bool`, *optional*): Whether or not to use PyTorch jit trace for inference. Example: ```py >>> from transformers import TrainingArguments >>> args = TrainingArguments("working_dir") >>> args = args.set_evaluate(strategy="steps", steps=100) >>> args.eval_steps 100 ``` r�DSetting `strategy` as 'steps' requires a positive value for `steps`.) rr�rMrLrKr�r�r�r�r�r�r�)rxr�r�r�r�r�r�r�rGrGrH� set_evaluateP s 1zTrainingArguments.set_evaluatecCsd|_||_||_||_|S)a[ A method that regroups all basic arguments linked to testing on a held-out dataset. <Tip> Calling this method will automatically set `self.do_predict` to `True`. </Tip> Args: batch_size (`int` *optional*, defaults to 8): The batch size per device (GPU/TPU core/CPU...) used for testing. loss_only (`bool`, *optional*, defaults to `False`): Ignores all outputs except the loss. jit_mode (`bool`, *optional*): Whether or not to use PyTorch jit trace for inference. Example: ```py >>> from transformers import TrainingArguments >>> args = TrainingArguments("working_dir") >>> args = args.set_testing(batch_size=32) >>> args.per_device_eval_batch_size 32 ``` T)r�r�r�r�)rxr�r�r�rGrGrH� set_testing� s "zTrainingArguments.set_testing� total_limit� on_each_nodecCs<t|�|_|jtjkr|dkrtd��||_||_||_|S)a� A method that regroups all arguments linked to checkpoint saving. Args: strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`): The checkpoint save strategy to adopt during training. Possible values are: - `"no"`: No save is done during training. - `"epoch"`: Save is done at the end of each epoch. - `"steps"`: Save is done every `save_steps`. steps (`int`, *optional*, defaults to 500): Number of updates steps before two checkpoint saves if `strategy="steps"`. total_limit (`int`, *optional*): If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in `output_dir`. on_each_node (`bool`, *optional*, defaults to `False`): When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on the main one. This should not be activated when the different nodes use the same storage as the files will be saved with the same names for each node. Example: ```py >>> from transformers import TrainingArguments >>> args = TrainingArguments("working_dir") >>> args = args.set_save(strategy="steps", steps=100) >>> args.save_steps 100 ``` rr�)rr�rMrLr�r�r�)rxr�r�r�r�rGrGrH�set_save� s )zTrainingArguments.set_saver �level� first_step�nan_inf_filter� replica_levelc CsTt|�|_|jtjkr|dkrtd��||_||_||_||_||_||_ ||_ |S)a� A method that regroups all arguments linked to logging. Args: strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`): The logging strategy to adopt during training. Possible values are: - `"no"`: No logging is done during training. - `"epoch"`: Logging is done at the end of each epoch. - `"steps"`: Logging is done every `logging_steps`. steps (`int`, *optional*, defaults to 500): Number of update steps between two logs if `strategy="steps"`. level (`str`, *optional*, defaults to `"passive"`): Logger log level to use on the main process. Possible choices are the log levels as strings: `"debug"`, `"info"`, `"warning"`, `"error"` and `"critical"`, plus a `"passive"` level which doesn't set anything and lets the application set the level. report_to (`str` or `List[str]`, *optional*, defaults to `"all"`): The list of integrations to report the results and logs to. Supported platforms are `"azure_ml"`, `"clearml"`, `"codecarbon"`, `"comet_ml"`, `"dagshub"`, `"dvclive"`, `"flyte"`, `"mlflow"`, `"neptune"`, `"tensorboard"`, and `"wandb"`. Use `"all"` to report to all integrations installed, `"none"` for no integrations. first_step (`bool`, *optional*, defaults to `False`): Whether to log and evaluate the first `global_step` or not. nan_inf_filter (`bool`, *optional*, defaults to `True`): Whether to filter `nan` and `inf` losses for logging. If set to `True` the loss of every step that is `nan` or `inf` is filtered and the average loss of the current logging window is taken instead. <Tip> `nan_inf_filter` only influences the logging of loss values, it does not change the behavior the gradient is computed or applied to the model. </Tip> on_each_node (`bool`, *optional*, defaults to `True`): In multinode distributed training, whether to log using `log_level` once per node, or only on the main node. replica_level (`str`, *optional*, defaults to `"passive"`): Logger log level to use on replicas. Same choices as `log_level` Example: ```py >>> from transformers import TrainingArguments >>> args = TrainingArguments("working_dir") >>> args = args.set_logging(strategy="steps", steps=100) >>> args.logging_steps 100 ``` rr�) rr�rMrLr�r�r�r�r�r�r�) rxr�r�r�r�r�r�r�r�rGrGrH� set_logging� s ?zTrainingArguments.set_logging�model_idr;� private_repo� always_pushcCs,d|_||_t|�|_||_||_||_|S)a� A method that regroups all arguments linked to synchronizing checkpoints with the Hub. <Tip> Calling this method will set `self.push_to_hub` to `True`, which means the `output_dir` will begin a git directory synced with the repo (determined by `model_id`) and the content will be pushed each time a save is triggered (depending on your `self.save_strategy`). Calling [`~Trainer.save_model`] will also trigger a push. </Tip> Args: model_id (`str`): The name of the repository to keep in sync with the local *output_dir*. It can be a simple model ID in which case the model will be pushed in your namespace. Otherwise it should be the whole repository name, for instance `"user_name/model"`, which allows you to push to an organization you are a member of with `"organization_name/model"`. strategy (`str` or [`~trainer_utils.HubStrategy`], *optional*, defaults to `"every_save"`): Defines the scope of what is pushed to the Hub and when. Possible values are: - `"end"`: push the model, its configuration, the processing_class e.g. tokenizer (if passed along to the [`Trainer`]) and a draft of a model card when the [`~Trainer.save_model`] method is called. - `"every_save"`: push the model, its configuration, the processing_class e.g. tokenizer (if passed along to the [`Trainer`]) and a draft of a model card each time there is a model save. The pushes are asynchronous to not block training, and in case the save are very frequent, a new push is only attempted if the previous one is finished. A last push is made with the final model at the end of training. - `"checkpoint"`: like `"every_save"` but the latest checkpoint is also pushed in a subfolder named last-checkpoint, allowing you to resume training easily with `trainer.train(resume_from_checkpoint="last-checkpoint")`. - `"all_checkpoints"`: like `"checkpoint"` but all checkpoints are pushed like they appear in the output folder (so you will get one checkpoint folder per folder in your final repository) token (`str`, *optional*): The token to use to push the model to the Hub. Will default to the token in the cache folder obtained with `huggingface-cli login`. private_repo (`bool`, *optional*, defaults to `False`): Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists. always_push (`bool`, *optional*, defaults to `False`): Unless this is `True`, the `Trainer` will skip pushing a checkpoint when the previous push is not finished. Example: ```py >>> from transformers import TrainingArguments >>> args = TrainingArguments("working_dir") >>> args = args.set_push_to_hub("me/awesome-model") >>> args.hub_model_id 'me/awesome-model' ``` T)r�r�rr�r�r�r�)rxr�r�r;r�r�rGrGrH�set_push_to_hub1 s> z!TrainingArguments.set_push_to_hubrv�beta1�beta2�epsilon�argscCs2t|�|_||_||_||_||_||_||_|S)a A method that regroups all arguments linked to the optimizer and its hyperparameters. Args: name (`str` or [`training_args.OptimizerNames`], *optional*, defaults to `"adamw_torch"`): The optimizer to use: `"adamw_hf"`, `"adamw_torch"`, `"adamw_torch_fused"`, `"adamw_apex_fused"`, `"adamw_anyprecision"` or `"adafactor"`. learning_rate (`float`, *optional*, defaults to 5e-5): The initial learning rate. weight_decay (`float`, *optional*, defaults to 0): The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights. beta1 (`float`, *optional*, defaults to 0.9): The beta1 hyperparameter for the adam optimizer or its variants. beta2 (`float`, *optional*, defaults to 0.999): The beta2 hyperparameter for the adam optimizer or its variants. epsilon (`float`, *optional*, defaults to 1e-8): The epsilon hyperparameter for the adam optimizer or its variants. args (`str`, *optional*): Optional arguments that are supplied to AnyPrecisionAdamW (only useful when `optim="adamw_anyprecision"`). Example: ```py >>> from transformers import TrainingArguments >>> args = TrainingArguments("working_dir") >>> args = args.set_optimizer(name="adamw_torch", beta1=0.8) >>> args.optim 'adamw_torch' ``` )rZr�r�r�r�r�r�r�)rxrvr�r�r�r�r�r�rGrGrH� set_optimizerw s *zTrainingArguments.set_optimizercCs&t|�|_||_||_||_||_|S)a A method that regroups all arguments linked to the learning rate scheduler and its hyperparameters. Args: name (`str` or [`SchedulerType`], *optional*, defaults to `"linear"`): The scheduler type to use. See the documentation of [`SchedulerType`] for all possible values. num_epochs(`float`, *optional*, defaults to 3.0): Total number of training epochs to perform (if not an integer, will perform the decimal part percents of the last epoch before stopping training). max_steps (`int`, *optional*, defaults to -1): If set to a positive number, the total number of training steps to perform. Overrides `num_train_epochs`. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) until `max_steps` is reached. warmup_ratio (`float`, *optional*, defaults to 0.0): Ratio of total training steps used for a linear warmup from 0 to `learning_rate`. warmup_steps (`int`, *optional*, defaults to 0): Number of steps used for a linear warmup from 0 to `learning_rate`. Overrides any effect of `warmup_ratio`. Example: ```py >>> from transformers import TrainingArguments >>> args = TrainingArguments("working_dir") >>> args = args.set_lr_scheduler(name="cosine", warmup_ratio=0.05) >>> args.warmup_ratio 0.05 ``` )rr�r�r�r�r�)rxrvr�r�r�r�rGrGrH�set_lr_scheduler� s &z"TrainingArguments.set_lr_schedulerr�r�� drop_last� num_workers� pin_memory�persistent_workers�prefetch_factor� sampler_seedc Cs@||_||_||_||_||_||_||_||_| |_| |_ |S)aS A method that regroups all arguments linked to the dataloaders creation. Args: drop_last (`bool`, *optional*, defaults to `False`): Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size) or not. num_workers (`int`, *optional*, defaults to 0): Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in the main process. pin_memory (`bool`, *optional*, defaults to `True`): Whether you want to pin memory in data loaders or not. Will default to `True`. persistent_workers (`bool`, *optional*, defaults to `False`): If True, the data loader will not shut down the worker processes after a dataset has been consumed once. This allows to maintain the workers Dataset instances alive. Can potentially speed up training, but will increase RAM usage. Will default to `False`. prefetch_factor (`int`, *optional*): Number of batches loaded in advance by each worker. 2 means there will be a total of 2 * num_workers batches prefetched across all workers. auto_find_batch_size (`bool`, *optional*, defaults to `False`) Whether to find a batch size that will fit into memory automatically through exponential decay, avoiding CUDA Out-of-Memory errors. Requires accelerate to be installed (`pip install accelerate`) ignore_data_skip (`bool`, *optional*, defaults to `False`): When resuming training, whether or not to skip the epochs and batches to get the data loading at the same stage as in the previous training. If set to `True`, the training will begin faster (as that skipping step can take a long time) but will not yield the same results as the interrupted training would have. sampler_seed (`int`, *optional*): Random seed to be used with data samplers. If not set, random generators for data sampling will use the same seed as `self.seed`. This can be used to ensure reproducibility of data sampling, independent of the model seed. Example: ```py >>> from transformers import TrainingArguments >>> args = TrainingArguments("working_dir") >>> args = args.set_dataloader(train_batch_size=16, eval_batch_size=64) >>> args.per_device_train_batch_size 16 ``` ) r�r�r�r�r�r�r�rr�r�) rxr�r�r�r�r�r�r�rr�r�rGrGrH�set_dataloader� s8z TrainingArguments.set_dataloader)r;rR)Tr�)r�r�rr�r1rr�F)r�r�r�NNFF)r�FF)r�r�NF)r�r�r r0FFFr0)r�NNF)r[r�rr�r�r�N)r�r�r1rr) r�r�FrTFNFFN)�r`rarbrcrPrr�ru�__annotations__r�rdr�r�r�r�r rr�r�rJr�r�r r�r�r�r�ryr�r�r�r�r�r�r�r�r�r�rrsrkr�r�r�rlr�r�r�r�r�r�r�r�r�rr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r rr�r�r�r!r2r�r�r�r�r�r�r�r�r�r�r�rr�rhr�rgrir�Z default_optimr�rZr�r\r�r�r�r�r�r�r�r�r�r�r�r�r�r�rr�r�r�r�rjr�rcr�r�r�r�r�r�r�rrrrrrrr r r r r rrrrrrrrrr~r��__repr__�propertyr�r�rr�rr�rQr�r�rZr�r�r�r�r�r�r�� contextlib�contextmanagerr�r�r r r�r�r�r�r�r�r�r�r�r�r�r�r�rGrGrGrHr|�s  S��� ������ �� ���� �� ������� ���� ��� ��� ������ �� ���������� �� ��� ���� ��� ������� ��� �� �� ������� ���� �� �� �� �� �� �� ������� �� �� �������������������������� ����� �� ���� �� ����������������������  B   ~     2" �������� �M� �������?����*� ����3� ������� �N�� ����H� �������5� �����/�������� � � �r|c@s$eZdZdZdZdZdZdZdZdS)r�Z not_parallelZnot_distributed� distributedZsagemaker_model_parallelZsagemaker_data_parallel�tpuN) r`rarbr�r�r�r�r�r�rGrGrGrHr� sr�rG)qrrirAr�rBrH� dataclassesrrrrr<r�enumr�pathlibr�typingr r r r r �huggingface_hubr� packagingr� debug_utilsr� trainer_utilsrrrrrr�utilsrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-Z utils.genericr.Zutils.import_utilsr/� get_loggerr`rE�get_log_levels_dictro� log_levelsrsr�rQ�torch.distributedrr�rTr2Zaccelerate.stater3r4rur5�trainer_pt_utilsr6�torch_xla.core.xla_model�core� xla_modelrWrKrLrNr�Z!torch_xla.distributed.xla_backendZ xla_backendZxbnrr�group�WORLDZProcessGroupXla�init_process_group�AssertionErrorZ!smdistributed.modelparallel.torchZ modelparallelr�r�rurIrPrYrZr>rtr|r�rGrGrGrH�<module>s�       \         ��    1 S
Memory