o
    hm                    @   s  d dl Z d dlZd dlZd dlZd dlZd dlmZmZmZm	Z	 d dl
mZ d dlmZ d dlmZ d dlmZmZmZ d dlmZ d dlmZ d	d
lmZ d	dlmZmZm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,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7 d	dl8m9Z9 d	dl:m;Z; e6<e=Z>e6? @ ZAeBd.i eAddiZCe* rd dlDZDd dlEmFZG e% rd dlHmIZImJZJ d dlKmLZL d	dlMmNZN e4 rd dlOmP  mQZR e1ddr ejSTdr e; re>Ud n*e>Vd d dlWmF  mXZY eZeGj[j\eYj]s eGj^dd eZeGj[j\eYj]s e_de) r1d dl`ma  mDZb ebc  dedfddZedd  Zfd!d"deed fd#d$ZgG d%d& d&e#Zhd'eBfd(d)ZieG d*d+ d+ZjG d,d- d-eZkdS )/    N)asdict	dataclassfieldfields)	timedelta)Enum)Path)Any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_hpu_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)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.zPlease 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.returnc                  C   s<   ddl } ddlm} | d}tjd|d |   S )z!
    Same default as PyTorch
    r   N)datetimez%b%d_%H-%M-%Sruns_)socketr:   nowstrftimeospathjoingethostname)r=   r:   current_time rE   n/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/transformers/training_args.pydefault_logdirp   s   rG   c                 C   s0   | D ]}t tj|d}|dkr|  S q|S )zQReturns the first positive env value found in the `env_keys` list or the default.r0   r   )intr@   environget)env_keysdefaultevalrE   rE   rF   get_int_from_env{   s   rO   devicetorch.devicec                 C   s2   t  r| jdkr
dS t| gd dd S dS )z^
    Returns the xla device type (CPU|GPU|TPU) or None if the device is a non-xla device.
    cpuCPUr   :N)r)   typexmxla_real_devicessplit)rP   rE   rE   rF   get_xla_device_type   s
   
rY   c                   @   s   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!d Z"d!Z#d"Z$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.
    adamw_torchadamw_torch_fusedadamw_torch_xlaadamw_torch_npu_fusedadamw_apex_fused	adafactoradamw_anyprecisionadamw_torch_4bitadamw_torch_8bitademamixsgdadagradadamw_bnb_8bit
adamw_8bitademamix_8bit	lion_8bit
lion_32bitpaged_adamw_32bitpaged_adamw_8bitpaged_ademamix_32bitpaged_ademamix_8bitpaged_lion_32bitpaged_lion_8bitrmsproprmsprop_bnbrmsprop_bnb_8bitrmsprop_bnb_32bitgalore_adamwgalore_adamw_8bitgalore_adafactorgalore_adamw_layerwisegalore_adamw_8bit_layerwisegalore_adafactor_layerwiselomoadalomo	grokadamwschedule_free_radamschedule_free_adamwschedule_free_sgdapollo_adamwapollo_adamw_layerwiseN)-__name__
__module____qualname____doc__ADAMW_TORCHADAMW_TORCH_FUSEDADAMW_TORCH_XLAADAMW_TORCH_NPU_FUSEDADAMW_APEX_FUSED	ADAFACTORADAMW_ANYPRECISIONADAMW_TORCH_4BITADAMW_TORCH_8BITADEMAMIXSGDADAGRAD	ADAMW_BNB
ADAMW_8BITADEMAMIX_8BIT	LION_8BITLIONPAGED_ADAMWPAGED_ADAMW_8BITPAGED_ADEMAMIXPAGED_ADEMAMIX_8BIT
PAGED_LIONPAGED_LION_8BITRMSPROPRMSPROP_BNBRMSPROP_8BITRMSPROP_32BITGALORE_ADAMWGALORE_ADAMW_8BITGALORE_ADAFACTORGALORE_ADAMW_LAYERWISEGALORE_ADAMW_8BIT_LAYERWISEGALORE_ADAFACTOR_LAYERWISELOMOADALOMO	GROKADAMWSCHEDULE_FREE_RADAMSCHEDULE_FREE_ADAMWSCHEDULE_FREE_SGDAPOLLO_ADAMWAPOLLO_ADAMW_LAYERWISErE   rE   rE   rF   rZ      sV    rZ   passed_valuec                 C   s   |   D ]>\}}t|trt|| |< qt|trB| dv r(| dk| |< q| r3t|| |< q|ddd rBt	|| |< q| S )zlSafely checks that a passed value is a dictionary and converts any string values to their appropriate types.)truefalser   . r   )
items
isinstancedict_convert_str_dictstrlowerisdigitrH   replacefloat)r   keyvaluerE   rE   rF   r      s   

r   c                   @   s  e Zd ZU dZg dZdZedddidZee	 e
d< ed	dd
idZee
d< ed	ddidZee
d< ed	ddidZee
d< ed	ddidZee
d< edddidZeee	f e
d< ed	ddidZee
d< edddidZee
d< edddidZee
d< edddidZee e
d< edddidZee e
d< ed dd!idZee
d"< eddd#idZee e
d$< ed%dd&idZee e
d'< eddd(idZee e
d)< ed*dd+idZee
d,< ed-dd.idZee
d/< ed0dd1idZ ee
d2< ed3dd4idZ!ee
d5< ed6dd7idZ"ee
d8< ed9dd:idZ#ee
d;< ed<dd=idZ$ee
d>< ed?dd@idZ%ee
dA< edBddCidZ&ee'e	f e
dD< ee(ddEidFZ)eee(e	f  e
dG< ed-ddHidZ*ee
dI< ed%ddJidZ+ee
dK< edLdMe,- dNdZ.ee	 e
dO< edPdQe,- dNdZ/ee	 e
dR< edSddTidZ0ee
dU< edddVidZ1ee	 e
dW< edXddYidZ2eee	f e
dZ< ed	dd[idZ3ee
d\< ed]dd^idZ4ee
d_< edSdd`idZ5ee
da< edXddbidZ6ee7e	f e
dc< ed]dddidZ8ee
de< edddfidZ9ee e
dg< edSddhidZ:ee e
di< ed	ddjidZ;ee
dk< ed	ddlidZ<ee
dm< ed	ddnidZ=ee
do< ed	ddpidZ>ee
dq< ed	ddridZ?ee
ds< ed	ddtidZ@ee
du< edvddwidZAee
dx< edddyidZBee e
dz< ed	dd{idZCee
d|< ed	dd}idZDee
d~< ed	ddidZEee
d< ed	ddidZFee
d< edddidZGe	e
d< eddg ddNdZHe	e
d< ed	ddidZIee
d< ed	ddidZJee
d< edddidZKee e
d< ed?ddidZLee
d< eddg ddNdZMee	 e
d< edddidZNee e
d< ed	ddidZOee
d< edddidZPee	eQeR f e
d< ed	ddidZSee
d< edddidZTee e
d< ed%ddidZUee
d< edddidZVee e
d< ed?ddidZWee
d< edddidZXee	 e
d< edddidZYee e
d< edSddidZZee e
d< edddidZ[eeQe	  e
d< ed	ddidZ\ee e
d< edddidZ]ee	 e
d< edddidZ^ee e
d< ed	ddidZ_ee
d< edddidZ`eeeQea e	f  e
d< ed%ddidZbee
d< edddidZceee(e	f  e
d< ed%ddidZdee e
d< edddidZeee	 e
d< edddidZfeee(e	f  e
d< edddidZgeee(e	f  e
d< ed-ddidZhee
d< dZieeiddidZjeeke	f e
d< edddidZlee	 e
d< ed	ddidZmee
d< ed	ddidZnee
d< edddidZoee	 e
d< edddidZpede	eQe	 f e
d< edddidZqee e
d< edddidZree e
d< edddidZsee e
d< edSddidZtee
d< ed	ddidZuee
d< edSddidZvee
d< ed	ddidZwee
d< ed	ddidZxee
d< edddidZyee	 e
d< edddidZzee	 e
d< edddidZ{ee|e	f e
d< edddidZ}ee	 e
d< edddidZ~ee e
d< ed	ddidZee
d< ed	ddidZee
d< edddidZeee(e	f  e
d< ed	ddidZee
d< eeQddidFZeQe	 e
d< edSddidZee
d< eddg ddNdZe	e
d< edddidZee	 e
d< edddidZee	 e
d < edddidZee	 e
d< ed	d	d?dZee
d< edddidZe	e
d< ed	ddidZee
d< ed	ddidZee
d	< eddd
idZee	 e
d< edddidZee	 e
d< edddidZee e
d< ed	ddidZee
d< edddidZee	 e
d< edddidZee	 e
d< ed	ddidZee e
d< ed	ddidZee e
d< edddidZee e
d< edddidZede	eQe	 f e
d< ed	dd idZee
d!< ed	dd"idZee
d#< ed	dd$idZee e
d%< ed	dd&idZee e
d'< ed	dd(idZee e
d)< d*d+ Zd,d- ZeZed.efd/d0Zed.efd1d2Zed.efd3d4Zedd6d7Zedd8d9Zed:d; Zed<d= Zed>d? Zed@dA ZedBdC ZedDdE ZedFdG ZdHdI ZedJdK ZedLdM ZejddOdPZdQefdRdSZdTe(e	ef d.dfdUdVZdWdX ZdYdZ Zd.e(e	ef fd[d\Z	*		%	]	?	 	v		dd,ed^ed/ed_edAed"edxedefd`daZ		]							ddbee	ef dXed^edcee ddee deedfefdgdhZ					dd^edeedfefdidjZ	X	]			ddbee	ef dXedkee dlefdmdnZ	X	]	o	L							Lddbee	ef dXedee	eQe	 f dpe	dqedredledse	fdtduZ					ddve	dbee	e|f dwee	 dxee dyef
dzd{Z		*	%	0	3	6	dd|ee	ekf d,ed/ed}ed~ededee	 fddZ	B	<	?	%	%dd|ee	e'f d_edAedIedKef
ddZ					%	S								ddededededededee dededee fddZdS (  TrainingArgumentsup  
    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`, *optional*, defaults to `"trainer_output"`):
            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 device accelerator core/CPU for training.
        per_device_eval_batch_size (`int`, *optional*, defaults to 8):
            The batch size per device accelerator 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 the device accelerator 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/), [comet](https://www.comet.com/site) and [swanlab](https://swanlab.cn)
            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_"`.

            If not specified, this will default to `"loss"` when either `load_best_model_at_end == True`
            or `lr_scheduler_type == SchedulerType.REDUCE_ON_PLATEAU` (to use the evaluation loss).

            If you set this value, `greater_is_better` will default to `True` unless the name ends with "loss".
            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 parameters. 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.
        tp_size (`int`, *optional*):
            Use tp_size to enable PyTorch tensor parallelism. Tensor parallelism support is only available to models having `base_tp_plan`
            in their respective config classes.
            Set a value greater than 1 to activate TP. The same is used to prepare device mesh internally. Requires accelerate>1.3.0.
        deepspeed (`str` or `dict`, *optional*):
            Use [Deepspeed](https://github.com/deepspeedai/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 reproducible using a different sampling technique. While seed-to-seed results
                    may differ, on average the differences are negligible 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_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"`,
            `"swanlab"`, `"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.
        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.
            Currently used for the GaLore algorithm (https://arxiv.org/abs/2403.03507) and APOLLO algorithm (https://arxiv.org/abs/2412.05270).
            See GaLore implementation (https://github.com/jiaweizzhao/GaLore) and APOLLO implementation (https://github.com/zhuhanqing/APOLLO) for more details.
            You need to make sure to pass a valid GaLore or APOLLO optimizer, e.g., one of: "apollo_adamw", "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.

        average_tokens_across_devices (`bool`, *optional*, defaults to `False`):
            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
    )accelerator_configfsdp_config	deepspeedgradient_checkpointing_kwargslr_scheduler_kwargsptNhelpzThe output directory where the model predictions and checkpoints will be written. Defaults to 'trainer_output' if not provided.)rL   metadata
output_dirFz|Overwrite the content of the output directory. Use this to continue training if output_dir points to a checkpoint directory.overwrite_output_dirzWhether 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nozThe evaluation strategy to use.eval_strategyzBWhen performing evaluation and predictions, only returns the loss.prediction_loss_only   z8Batch size per device accelerator core/CPU for training.per_device_train_batch_sizez:Batch size per device accelerator core/CPU for evaluation.per_device_eval_batch_sizezrDeprecated, 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_sizer   zONumber 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_stepsr   zsNumber 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_rateg        z(Weight decay for AdamW if we apply some.weight_decay?zBeta1 for AdamW optimizer
adam_beta1+?zBeta2 for AdamW optimizer
adam_beta2:0yE>zEpsilon for AdamW optimizer.adam_epsilong      ?zMax gradient norm.max_grad_norm      @z+Total number of training epochs to perform.num_train_epochsr0   zQIf > 0: set total number of training steps to perform. Override num_train_epochs.	max_stepslinearzThe scheduler type to use.lr_scheduler_typezbExtra parameters for the lr_scheduler such as {'num_cycles': 1} for the cosine with hard restarts.)default_factoryr   r   z8Linear warmup over warmup_ratio fraction of total steps.warmup_ratioz Linear warmup over warmup_steps.warmup_stepsr/   zLogger 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_nodezTensorboard log dir.logging_dirstepszThe logging strategy to use.logging_strategyzLog the first global_steplogging_first_step  zLog 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_strategyzSave 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_stepsak  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=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_nodeaW  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.save_only_modelzWhether 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_checkpointuT   This argument is deprecated. It will be removed in version 5.0 of 🤗 Transformers.no_cudazsWhether or not to use cpu. If left to False, we will use the available torch device/backend (cuda/mps/xpu/hpu etc.)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_ipexzWhether 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fp16O1zFor 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  apexcpu_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mpicclhcclcnclmccl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_debugr   zWhether 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_lastzRun 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_workerszNumber 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_indexz]An optional descriptor for the run. Notably used for wandb, mlflow comet and swanlab 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_nameszWhether 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`.fsdpzThis parameter is deprecated. FSDP's minimum number of parameters for Default Auto Wrapping. (useful only when `fsdp` field is passed).fsdp_min_num_paramszConfig 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`.r   a  Use tp_size to enable pytorch tensor parallelism.Tensor parallelism support is only available to models having `base_tp_plan` in their respective config classes.Set a value greater than 1 to activate TP.The same is used to prepare device mesh internally.Requires accelerate>1.3.0.tp_sizezThis 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_wrapzConfig to be used with the internal Accelerator object initialization. The value is either a accelerator json config file (e.g., `accelerator_config.json`) or an already loaded json file as `dict`.r   zEnable deepspeed and pass the path to deepspeed json config file (e.g. `ds_config.json`) or an already loaded json file as a dictr   zEThe label smoothing epsilon to apply (zero means no label smoothing).label_smoothing_factorr[   zThe 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_memoryzIf 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_tokenzWhether 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_checkpointingzGradient checkpointing key word arguments such as `use_reentrant`. Will be passed to `torch.utils.checkpoint.checkpoint` through `model.gradient_checkpointing_enable`.r   uu   This 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_metricszWhether 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_backendz7The 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reprrL   _n_gpuzKUsed by the SageMaker launcher to send mp-specific args. Ignored in Trainermp_parameterszWhether 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_sizezWhether 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lastay  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.	ray_scopei  zZOverrides 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_modezVIf 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_seenaU  Activates neftune noise embeddings into the model. NEFTune has been proven to drastically improve model performances for instruction 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_objectzWhether 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              
   C   s   | j d u rd| _ td | jD ] }t| |}t|tr0|dr0t	|}t
|}t| || q| j d ur>tj| j | _ | jd u rR| j d urRtj| j t | _| jd ur_tj| j| _| jd u rlt tjk| _t| jtr}tdt | jj| _| jrtdt | j| _t| j| _t| j| _t | j!| _!t"| j#| _#t$| j%| _%| j&du r| jtj'krd| _&| j(d urt| j(t)r| j(dkst*d	| j( d
| jtj+kr| j,d u s| j,dkr| j-dkrtd| j-  | j-| _,n	t*d| j d| jtj+kr| j-dkrt*d| j d| jtj+kr5| j-dkr5| j-t)| j-kr/t*d| j- t)| j-| _-| jtj+krY| j,dkrY| j,t)| j,krSt*d| j, t)| j,| _,| j!t j+kr}| j.dkr}| j.t)| j.krwt*d| j. t)| j.| _.| j/r| j!t j0kr| j| j!krt*d| j d| j! | jtj+kr| j.| j, dkr| j,dk s| j.dk r| j,dk r| j.dk st*d| j. d| j, d
d}| j.| | j,|  dkrt*d| j. d| j, d
t*d| j. d| j, d
t1 }| j2r|st*d| j2 d| j2s|rtd| j2 d  | j/s(| j%t$j3kr1| j4d u r1d!| _4| j5d u rE| j4d urE| j46d! | _5| j7d u rO| j | _7| j8d"krt9 r| j:rm| j:d#krmtd$t | j:| _;| j<su| j=r| jrt> st? st*d%| jst@jAB rtC st*d&| jDr| j<rt*d'| jEr| j=rt*d(| j<r| j;d)krt*d*| j%t$j3kr| jtj'krt*d+t9 st*d,tF| jG| _G| jHrtd-t tFjI| _G| jGtFjJkr"t9 r"tKLtKLt@jMjNtKLd.k r
t*d/tKLtKLt@jMjNtKLd.kr"| jDr"t*d0tO r[t| jPtQs[| jPd u r8tQ | _Pn#t| jPtRrItQdi | jP| _Pnt| jPtSrTtTd1tQU| jP| _P| j8d"krht9 rh| jV | jWrz| jXdkr{tYd2 d| _WW n tZy } ztYd3| d4 d| _WW Y d }~nd }~ww | j[d urtd5t | j[| _\| j]d us| j\d ur| j^sd| _^| j^r| j\d u r| jst_ rd6| _\nd7| _\| j^rd8}| j\tj`|d9 < | j]d ur| j]tj`|d: < | j8d"kr*t9 r*| j^r*ta r%| jbd u r| jDr| j<r$td; dt@jcjAjd_edt@jcjf_entYd< | j8d"krat9 ra| jbd ura| jbrRta rNdt@jcjAjd_edt@jcjf_ent*d=ta radt@jcjAjd_edt@jcjf_e| j;d)krtj`gd>d?}| jDrud@}n| j<r{dA}|tj`d>< | jhd u rtdB dC| _h| jhdCks| jhdCgkrddDlimj}	 |	 | _hdE| jhv rt@jKjkrtYdF | jhldE n| jhdGks| jhdGgkrg | _hnt| jhtms| jhg| _h| jndk s| jndkrt*dH| jndkr| jodkrtdI t| jot)r| jodk rt*dJt| jptqr| jprtrjsgndK| _pt| jptr/dLdM | jpt D | _p| jptrjugkr;t*dNtrjs| jpv rMtrjv| jpv rMt*dO| jwrdtrjs| jpv s_trjx| jpv rdtYdP | jyd u rmi | _yt| jytrtz| jpdkrtdQ t{| jydRdS.}
t||
| _ytm| jy} D ]}|dTr| jy~|}|| jy|dUd  < qW d    n	1 sw   Y  | jdkrtdVt t| jygdWd| j| jydW< t| jygdXd tr| jydX g| jydX< | jd urtdYt | jygdXg | jg | jydX< tz| jpdkr| jydW dkrtdZ tz| jpdkr3| jygdXd d ur3td[ tz| jpdkrQ| jydW dkrQ| jygdXd d urQt*d\| jygd]d| jyd]< | jygd^d| jyd^< | jygd_d| jyd_< | jyd] rtz| jpdkr| jygd`i  | _da| jv rtt@| jda | jda< db| jv rtt@| jdb | jdb< ntdc n| jyd_ rtdd | jdkrtOdestTdfdgtj`dh< t| jtj`di< tz| jpdkr| jyd] sdgtj`dj< ddklm}m} dl}| jpD ]v}| |v rt|| d tj`| dm< q|trjukr#dgtj`| dn< q|trjkrl|d tj`| do< | jydW dkrTt| jydW tj`| dp< |d tj`| do< q| jygdXd d urldq| jydX tj`| dr< q| jygdsdt}| tj`| du< t| jygdvdw tj`| dx< t| jygdydg }t| jygdzdw }|dwkr|dgkrt*d{|tj`| d|< |tj`| d}< t| jygd~dg tj`| d< | jrtdt | jd u rd| _n|  jd7  _d| _t| jtrddM | jt D | _n	| jd u rg | _d | _| jrGtO s"t*dt dddlm} || j| _| j|  ddlm} dgtj`d< || jd| _n&ttj`gddwrmddlm} | | _tj`gd>d?}| j| | j  | jrtd| _| jdkr| jd urt*d| jd urtdt | j| _| jd urt| j| j| jd| _| jd urtd| j dt n*td| j dt n| jd ur| j dt| j j | _td| j dt | jrtOdst*d| jd urtOdstTd| j	rtYd | jd d S d S )Ntrainer_outputzNo output directory specified, defaulting to 'trainer_output'. To change this behavior, specify --output_dir when creating TrainingArguments.{u   using `EvaluationStrategy` for `eval_strategy` is deprecated and will be removed in version 5 of 🤗 Transformers. Use `IntervalStrategy` insteadul   using `no_cuda` is deprecated and will be removed in version 5.0 of 🤗 Transformers. Use `use_cpu` insteadFTr   z@`torch_empty_cache_steps` must be an integer bigger than 0, got r   z4using `logging_steps` to initialize `eval_steps` to zevaluation strategy z9 requires either non-zero --eval_steps or --logging_stepszlogging strategy z" requires non-zero --logging_stepsr   z5--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@B zg--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.0z6At 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` insteadz2.0.0z8--optim adamw_torch_fused requires PyTorch 2.0 or higherz:--optim adamw_torch_fused with --fp16 requires PyTorch>2.0zTried passing in a callable to `accelerator_config`, but this is not supported. Please pass in a fully constructed `AcceleratorConfig` object instead.zsaverage_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hpu_backendinductorACCELERATE_DYNAMO_BACKENDMODEz`Setting TF32 in CUDA backends to speedup torch compile, you won't see any improvement otherwise.zbThe speedups for torchdynamo mostly come with GPU Ampere or higher and which is not detected here.zC--tf32 requires Ampere or a newer GPU arch, cuda>=11 and torch>=1.7ACCELERATE_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
codecarbonaR  When 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.r   c                 S      g | ]}t |qS rE   )r   .0srE   rE   rF   
<listcomp>P      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`.a  When 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.zutf-8)encodingfsdp_   zEusing `--fsdp_min_num_params` is deprecated. Use fsdp_config instead min_num_paramstransformer_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.r7   xla_fsdp_v2xla_fsdp_grad_ckptxla_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.z1.3.1zTP using PyTorch requires Accelerate version `accelerate` >= 1.3.1. This is not supported and we recommend you to update your version.r   ACCELERATE_USE_TPTP_SIZEACCELERATE_USE_FSDP)FSDP_AUTO_WRAP_POLICYFSDP_SHARDING_STRATEGYFSDP_SHARDING_STRATEGYOFFLOAD_PARAMSAUTO_WRAP_POLICYMIN_NUM_PARAMS,TRANSFORMER_CLS_TO_WRAPbackward_prefetchNO_PREFETCHBACKWARD_PREFETCHforward_prefetchr   FORWARD_PREFETCHsync_module_statescpu_ram_efficient_loadingzP`sync_module_states` must be `"True"` if `cpu_ram_efficient_loading` is `"True"`SYNC_MODULE_STATESCPU_RAM_EFFICIENT_LOADINGuse_orig_paramsUSE_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_debugc                 S   rq  rE   r   rr  rE   rE   rF   ru    rv  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 z0.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.z1.1.0zdata_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.inputsrE   )r   loggerinfo_VALID_DICT_FIELDSgetattrr   r   
startswithjsonloadsr   setattrr@   rA   
expanduserr   rB   rG   r%  getEffectiveLevelr+   WARNr   r   warningswarnFutureWarningr   r   r  r   r   r   r   r   rB  r   r   r   NOr   rH   
ValueErrorSTEPSr   r   r   r(  BESTr   r   REDUCE_ON_PLATEAUr)  r*  endswithr$  	frameworkr   rJ  r  r  r  r    r)   torchcudais_availabler!   r	  r  rZ   r1  r`   r   r   r   parse__version__base_versionr   r   r4   r   rU   NotImplementedErrorfrom_json_filerP   rc  
world_sizer   ImportErrorrT  rY  rZ  rX  r"   rI   r(   r  backendsmatmul
allow_tf32cudnnrJ   r6  integrationsrn  hipremovelistr   r   r,  boolr   
FULL_SHARDrX   OFFLOADSHARD_GRAD_OPrF  HYBRID_SHARDr   lenopenloadkeyspopr-  maxr/  copyxla_fsdp_configr.  accelerate.utils.constantsr  r  upperindex	AUTO_WRAPr   r  r  deepspeed_pluginr   r   #transformers.integrations.deepspeedr  hf_deepspeed_configtrainer_config_processaccelerate.utilsr  r-   set_mixed_precisionset_deepspeed_weakrefr:  r!  r"  rM  rC  rK  r   rL  r@  r   namerb  r  rG  rH  append)selfr   r   loaded_dictLARGE_MULTIPLIERsafetensors_availablerM   prefixmixed_precision_dtypern  fkvr  r  fsdp_optionprefetch_policyr  r  r  r  mixed_precisionrE   rE   rF   __post_init__  sl  








 

  (
 
 




 
$





""



zTrainingArguments.__post_init__c                 C   sV   t | }|d= |d= dd | D }dd t| D }| jj dd| d	S )
Nr   r   c                 S   s0   i | ]\}}|| d rd|  dn|qS )_token<>)r  r  rs  r  r  rE   rE   rF   
<dictcomp>G  s   0 z-TrainingArguments.__str__.<locals>.<dictcomp>c                 S   s    g | ]\}}| d | dqS )=z,
rE   r  rE   rE   rF   ru  I  s     z-TrainingArguments.__str__.<locals>.<listcomp>z(
r   ))r   r   sorted	__class__r   rB   )r  self_as_dictattrs_as_strrE   rE   rF   __str__?  s   zTrainingArguments.__str__r9   c                 C   0   | j rtd | j p| j}|td| j }|S )zz
        The actual batch size for training (may differ from `per_gpu_train_batch_size` in distributed training).
        zUsing 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   r  r   r   r  n_gpu)r  per_device_batch_sizetrain_batch_sizerE   rE   rF   r  N     z"TrainingArguments.train_batch_sizec                 C   r  )z{
        The actual batch size for evaluation (may differ from `per_gpu_eval_batch_size` in distributed training).
        zUsing 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   r  r   r   r  r  )r  r  eval_batch_sizerE   rE   rF   r  \  r  z!TrainingArguments.eval_batch_sizec                 C   s   t | jdS )zt
        The actual timeout for torch.distributed.init_process_group since it expects a timedelta variable.
        seconds)r   rW  r  rE   rE   rF   ddp_timeout_deltaj  s   z#TrainingArguments.ddp_timeout_deltarQ   c                 C   s  t | dg td t st stdt dt dddd}t| jt	r0| j
d	d|d	< |d	 rStji kr=td
t| jd| _| jrR| jjtjkrRtdn	tjdd d | _| jsidtjvridtjd< d| _| jsxttjddrd|d< | j|d< d| _n=t rd|d< t }t !d|}t j"#| n%t$ rd|d< n| jrd|d< t%| j&d|d< n| j|d< t%| j&d|d< |
ddr|
d	ds|
dd}|rdtjd< td+i || _|rtjd= t s| jj!}| jj'| _t() rt(* r| j+t,j-krt.d t/ r| jj!}d| _|S t$ s t r#	 |S | jjtj0kr| j1r>t23d |j4d kr>td!| jrIt !d}|S t5 rTt !d }|S t6 rrt7 setd"setd#t !d$}t j8#| |S t9 rt !d%}t j:#| |S t; rt !d&}t j<#| |S t= rt !d'}t j>#| |S t? rt !d(}t j@#| |S t !t j") rd)ntjd*d}t j"A | _|j4dkrt j"#| |S ),Nr  zPyTorch: setting up devicesz9Using the `Trainer` with `PyTorch` requires `accelerate>=zM`: Please run `pip install transformers[torch]` or `pip install 'accelerate>=z'`TF)enableduse_configured_stater  zPassing `'use_configured_state':True` to the AcceleratorConfig requires a pre-configured `AcceleratorState` or `PartialState` to be defined before calling `TrainingArguments`. )rR   a  Tried 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.)reset_partial_stateACCELERATE_USE_IPEXr   r   ACCELERATE_USE_CPUFalserR   r8   r   r  r  _use_sagemaker_dpuse_deepspeedr   timeoutr   r  ztorch.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. mpszEither 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`zxpu:0zmlu:0zmusa:0znpu:0zhpu:0zcuda:0ACCELERATE_TORCH_DEVICErE   )Br,   r  r  r   r   r  r   r   r   r4   r  r2   _shared_stater  r  distributed_stater   distributed_typer3   	DEEPSPEEDRuntimeErrorr1   _reset_stater  r@   rI   rP  r-   rJ   r  smpr  r  rP   r  
set_devicer   r   rW  local_process_indexdistr  is_initializedparallel_modeParallelModeDISTRIBUTEDr   r)   r  r  r  r  rU   r$   r*   r   xpur#   mlur%   musar'   npur"   hpudevice_count)r  accelerator_state_kwargsr  rP   r  rE   rE   rF   _setup_devicesq  s   








"41
#
!




z TrainingArguments._setup_devicesc                 C   s   t | dg | jS )z2
        The device used by this process.
        r  )r,   r$  r  rE   rE   rF   rP     s   zTrainingArguments.devicec                 C   s"   t | dg t| ds| j}| jS )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.
        r  rP  )r,   hasattrr$  rP  )r  r<   rE   rE   rF   r    s   	
zTrainingArguments.n_gpuc                 C   sx   t | dg t rtjS t rtjS t rtjS | jdur$| jj	t
jks.| jdu r1| jdkr1tjS | jdkr9tjS tjS )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.
        r  Nr0   r   )r,   r)   r  TPUr   SAGEMAKER_MODEL_PARALLELr   SAGEMAKER_DATA_PARALLELr  r  r3   r  r  r  r  NOT_DISTRIBUTEDNOT_PARALLELr  rE   rE   rF   r  
	  s   
zTrainingArguments.parallel_modec                 C   B   t | dg | jdur| jjS t rtjjjst S t	 S dS )z;
        The number of processes used in parallel.
        r  Nr   )
r,   r  num_processesr   r  statecfgprescaled_batchdp_sizerdp_sizer  rE   rE   rF   r  %	     
zTrainingArguments.world_sizec                 C   r+  )z8
        The index of the current process used.
        r  Nr   )
r,   r  process_indexr   r  r-  r.  r/  dp_rankrdp_rankr  rE   rE   rF   r3  1	  r2  zTrainingArguments.process_indexc                 C   s0   t | dg | jdur| jjS t rt S dS )z6
        The index of the local process used.
        r  Nr   )r,   r  r  r   r  r  r  rE   rE   rF   r  =	  s   
z%TrainingArguments.local_process_indexc                 C   ,   | j r| jdkS t rt dkS | jdkS )zH
        Whether or not the current process should produce log.
        r   )r   r  r   r  rankr3  r  rE   rE   rF   
should_logJ	  
   

zTrainingArguments.should_logc                 C   r6  )zp
        Whether or not the current process should write to disk, e.g., to save models and checkpoints.
        r   )r   r  r   r  r7  r3  r  rE   rE   rF   should_saveW	  r9  zTrainingArguments.should_savec                 C   sJ   t | j }t | j }|dkrt n|}|dkrt n|}| jr#|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`.
        r0   )trainer_log_levelsr   r   r+   get_verbosityr8  )r  r   r   log_level_main_nodelog_level_replica_noderE   rE   rF   get_process_log_leveld	  s
   

z'TrainingArguments.get_process_log_levelc                 C   s   t   S )zR
        Can be subclassed and overridden for some specific integrations.
        )r   r  rE   rE   rF   place_model_on_devicez	  s   z'TrainingArguments.place_model_on_devicec                 C   s   | j pt pt pt  S )zc
        Whether or not to use no_sync for the gradients when doing gradient accumulation.
        )r   r   r   r&   r  rE   rE   rF   !_no_sync_in_gradient_accumulation	  s   z3TrainingArguments._no_sync_in_gradient_accumulationworkc                 c   s$   t  r| jdkr|rdnd}| jdur|r| jjn| jj}n	t r(t dk}zD|sFt	| j
 d| d|  t rBt| nt  dV  W |rkt	| j
 d| d	| d
 t ret| dS t  dS dS |rt	| j
 d| d	| d
 t rt| w t  w w dV  dS )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

        r   zmain local processzmain processNr   z: waiting for the z to perform z: z completed z, releasing all replicas)r   r  r  is_local_main_processis_main_processr   r  r7  r  r  r3  r)   rV   
rendezvousr  barrier)r  localdescmain_process_descrD  rE   rE   rF   main_process_first	  s6   


z$TrainingArguments.main_process_firstnum_training_stepsc                 C   s(   | j dkr
| j }|S t|| j }|S )z?
        Get number of steps used for a linear warmup.
        r   )r   mathceilr   )r  rK  r   rE   rE   rF   get_warmup_steps	  s   z"TrainingArguments.get_warmup_stepsdc                 C   s^   | dddurt|d tst|d dd |d< | D ]}t|tr,| | q dS )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_dtypeNr   r   )rJ   r   r   rX   valuesr   _dict_torch_dtype_to_str)r  rO  r   rE   rE   rF   rR  	  s   

z*TrainingArguments._dict_torch_dtype_to_strc                    s    fddt  D }| D ]F\}}t|tr|j||< t|tr8t|dkr8t|d tr8dd |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.
        c                    s"   i | ]}|j r|jt |jqS rE   )rN  r  r  )rs  r   r  rE   rF   r  	  s   " z-TrainingArguments.to_dict.<locals>.<dictcomp>r   c                 S   s   g | ]}|j qS rE   )r   )rs  xrE   rE   rF   ru  	  s    z-TrainingArguments.to_dict.<locals>.<listcomp>r  r  r  )r   r   r   r   r   r  r  r  r  r   r4   to_dictrR  )r  rO  r  r  rE   r  rF   rT  	  s   

$

zTrainingArguments.to_dictc                 C   s   t j|  ddS )z<
        Serializes this instance to a JSON string.
           )indent)r  dumpsrT  r  rE   rE   rF   to_json_string	  s   z TrainingArguments.to_json_stringc                    sR   |   }i || j| jd}ttttg t r t	j
  fdd| D S )uM   
        Sanitized serialization to use with TensorBoard’s hparams
        )r  r  c                    s*   i | ]\}}|t | v r|nt|qS rE   )rU   r   r  valid_typesrE   rF   r  	  s   * z7TrainingArguments.to_sanitized_dict.<locals>.<dictcomp>)rT  r  r  r  rH   r   r   r   r  r  Tensorr   )r  rO  rE   rY  rF   to_sanitized_dict	  s   z#TrainingArguments.to_sanitized_dict   
batch_size
num_epochsc	           	      C   s:   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  rF  )	r  r   r^  r   r_  r   r   r  rF  rE   rE   rF   set_training	  s   @zTrainingArguments.set_trainingstrategyaccumulation_stepsdelay	loss_onlyjit_modec                 C   s\   t || _| jt jkr|dkrtd| jt jk| _|| _|| _|| _|| _	|| _
|| _| 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`.)r   r   r  r  r  r   r   r   r   r   r   r  )r  ra  r   r^  rb  rc  rd  re  rE   rE   rF   set_evaluateG
  s   
1zTrainingArguments.set_evaluatec                 C   s   d| _ || _|| _|| _| 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  )r  r^  rd  re  rE   rE   rF   set_testing
  s
   "zTrainingArguments.set_testingtotal_limiton_each_nodec                 C   s<   t || _| jt jkr|dkrtd|| _|| _|| _| 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
        ```
        r   rf  )r   r   r  r  r   r   r   )r  ra  r   ri  rj  rE   rE   rF   set_save
  s   
)zTrainingArguments.set_saverp  level
first_stepnan_inf_filterreplica_levelc	           	      C   sT   t || _| jt jkr|dkrtd|| _|| _|| _|| _|| _|| _	|| _
| 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"`, `"swanlab"`, `"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
        ```
        r   rf  )r   r   r  r  r   r6  r   r   r   r   r   )	r  ra  r   r6  rl  rm  rn  rj  ro  rE   rE   rF   set_logging
  s   
?zTrainingArguments.set_loggingmodel_idr  private_repoalways_pushc                 C   s,   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@  r   rB  rC  rD  rE  )r  rq  ra  r  rr  rs  rE   rE   rF   set_push_to_hub(  s   >
z!TrainingArguments.set_push_to_hubr  beta1beta2epsilonargsc                 C   s2   t || _|| _|| _|| _|| _|| _|| _| 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_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'
        ```
        )rZ   r1  r   r   r   r   r   r2  )r  r  r   r   ru  rv  rw  rx  rE   rE   rF   set_optimizern  s   
*zTrainingArguments.set_optimizerc                 C   s&   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
        ```
        )r   r   r   r   r   r   )r  r  r_  r   r   r   rE   rE   rF   set_lr_scheduler  s   
&z"TrainingArguments.set_lr_schedulerr  r  	drop_lastnum_workers
pin_memorypersistent_workersprefetch_factorsampler_seedc                 C   s@   || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	| 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+  r  )r  r  r  r{  r|  r}  r~  r  rR  r+  r  rE   rE   rF   set_dataloader  s   8z TrainingArguments.set_dataloader)r9   rQ   )TrB  )r   r   r   r]  r0   r   r  F)r   r   r   NNFF)r   FF)r   r   NF)r   r   rp  r/   FFFr/   )rA  NNF)r[   r   r   r   r   r   N)r   r   r0   r   r   )
r   r   Fr   TFNFFN)r   r   r   r   r  r  r   r   r
   r   __annotations__r   r  r   r   r   r   r   r   r   r   rH   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   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  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,  r   r-  r   r.  r/  r   r   r0  default_optimr1  rZ   r2  r`   r3  r5  r6  r7  r8  r9  r:  r;  r<  r=  r>  r?  r@  rB  r   rC  rD  rE  rF  r   rG  rH  rI  rJ  rK  rL  rM  rP  rQ  rR  rS  rT  rV  rW  rX  rY  rZ  r[  r\  r]  r^  r_  r`  ra  rb  rc  r  r  __repr__propertyr  r  r   r  r   r$  rP   r  r  r  r3  r  r8  r:  r?  r@  rA  
contextlibcontextmanagerrJ  rN  r	   rR  rT  rX  r\  r`  rg  rh  rk  rp  rt  ry  rz  r  rE   rE   rE   rF   r      s
  
     X
	

												
												
	    2 2"		M
?*
3
	N
H
5
/	
r   c                   @   s$   e Zd ZdZdZdZdZdZdZdS )r  not_parallelnot_distributeddistributedsagemaker_model_parallelsagemaker_data_paralleltpuN)	r   r   r   r*  r)  r  r'  r(  r&  rE   rE   rE   rF   r    s    r  rE   )lr  r  rL  r@   r  dataclassesr   r   r   r   r:   r   enumr   pathlibr   typingr	   r
   r   huggingface_hubr   	packagingr   debug_utilsr   trainer_utilsr   r   r   r   r   r   utilsr   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   utils.genericr-   utils.import_utilsr.   
get_loggerr   r  get_log_levels_dictr  
log_levelsr   r;  r  torch.distributedr  r  accelerate.stater1   r2   r  r3   trainer_pt_utilsr4   torch_xla.core.xla_modelcore	xla_modelrV   rI   rJ   r  r   !torch_xla.distributed.xla_backendxla_backendxbnr   groupWORLDProcessGroupXlainit_process_groupAssertionError!smdistributed.modelparallel.torchmodelparallelr  rN  r   rG   rO   rY   rZ   r   r   r  rE   rE   rE   rF   <module>   s    `
	0                      V