U
    9%e                    @   s  d dl Z 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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/m0Z0m1Z1m2Z2m3Z3m4Z4 d	dl5m6Z6 d	dl7m8Z8 e39e:Z;e3< = Z>e?f e>ddiZ@e+ rpd dlAZAd dlBmCZD e' rd dlEmFZFmGZG d dlHmIZI e1ddrd dlJmK  mLZM e.ddr4ejNOdr4e8 re;Pd nTe;Qd d dlRmC  mSZT eUeDjVjWeTjXs4eDjYdd eUeDjVjWeTjXs4eZde* rVd dl[m\  mAZ] e]^  e_dddZ`dd Zad ee_ d!d"d#ZbG d$d% d%e%ZceG d&d' d'ZdG d(d) d)eZedS )*    N)asdict	dataclassfieldfields)	timedelta)Enum)Path)AnyDictListOptionalUnion)get_full_repo_name)version   DebugOption)EvaluationStrategy
FSDPOptionHubStrategyIntervalStrategySchedulerTypeShardedDDPOption)ExplicitEnumcached_propertyis_accelerate_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_neuroncore_availableis_torch_npu_availableis_torch_tf32_availableis_torch_tpu_availableis_torch_xpu_availableloggingrequires_backends)	strtobool)is_optimum_neuron_availablepassive)AcceleratorStatePartialState)DistributedTypeF)Zcheck_deviceZTORCHELASTIC_RUN_IDzwMake sure that you are performing the training with the TrainiumTrainer from optimum[neuron], this will fail otherwise.zPlease use the TrainiumTrainer 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_)socketr4   nowstrftimeospathjoingethostname)r7   r4   current_time r?   Y/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/training_args.pydefault_logdiri   s    rA   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.r,   r   )intr:   environget)Zenv_keysdefaultevalr?   r?   r@   get_int_from_envt   s
    
rH   torch.device)devicer3   c                 C   s$   t  r 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.
    r   :N)r%   xmZxla_real_devicessplit)rJ   r?   r?   r@   get_xla_device_type}   s    rN   c                   @   sX   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S )OptimizerNameszB
    Stores the acceptable string identifiers for optimizers.
    Zadamw_hfadamw_torchZadamw_torch_fusedZadamw_torch_xlaZadamw_apex_fused	adafactorZadamw_anyprecisionZsgdZadagradZadamw_bnb_8bitZ
adamw_8bitZ	lion_8bitZ
lion_32bitZpaged_adamw_32bitZpaged_adamw_8bitZpaged_lion_32bitZpaged_lion_8bitZrmspropN)__name__
__module____qualname____doc__ZADAMW_HFZADAMW_TORCHADAMW_TORCH_FUSEDZADAMW_TORCH_XLAZADAMW_APEX_FUSED	ADAFACTORZADAMW_ANYPRECISIONZSGDZADAGRADZ	ADAMW_BNBZ
ADAMW_8BITZ	LION_8BITZLIONZPAGED_ADAMWZPAGED_ADAMW_8BITZ
PAGED_LIONZPAGED_LION_8BITZRMSPROPr?   r?   r?   r@   rO      s&   rO   c                
   @   s  e Zd ZU dZdZe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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d*< ed+dd,id	Zeed-< ed.dd/id	Zeed0< ed1dd2id	Zeed3< ed4dd5id	Z eed6< ed7dd8id	Z!eed9< ed:dd;id	Z"eed<< ed=dd>id	Z#eed?< ed@ddAid	Z$ee%ef edB< ed+ddCid	Z&eedD< ed%ddEid	Z'eedF< edGdHe() dId	Z*ee edJ< edKdLe() dId	Z+ee edM< edNddOid	Z,e
edP< edddQid	Z-ee edR< edSddTid	Z.eeef edU< edddVid	Z/e
edW< edXddYid	Z0eedZ< edNdd[id	Z1e
ed\< edSdd]id	Z2eeef ed^< edXdd_id	Z3eed`< edddaid	Z4ee edb< edddcid	Z5ee
 edd< edddeid	Z6e
edf< edddgid	Z7e
edh< edddiid	Z8e
edj< edddkid	Z9e
edl< edmddnid	Z:eedo< edddpid	Z;ee edq< edddrid	Z<e
eds< edddtid	Z=e
edu< edddvid	Z>e
edw< edddxid	Z?e
edy< edzdd{id	Z@eed|< ed}d~d}dddgdId	ZAeed< edddid	ZBe
ed< edddid	ZCe
ed< edddid	ZDee
 ed< ed=ddid	ZEeed< edddddddgdId	ZFee ed< edddid	ZGee ed< edddid	ZHe
ed< edddid	ZIeeeJeK f ed< edddid	ZLe
ed< edddid	ZMee ed< ed%ddid	ZNeed< ed=ddid	ZOeed< edddid	ZPee ed< edddid	ZQee
 ed< edNddid	ZRee
 ed< edddid	ZSeeJe  ed< edddid	ZTee
 ed< edddid	ZUee ed< edddid	ZVee
 ed< edddid	ZWe
ed< edddid	ZXeeeJeY ef  ed< edddid	ZZeeeJe[ ef  ed< ed%ddid	Z\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 ed< ed+ddid	Z`eed< dZaeeaddid	Zbeecef ed< edddid	Zdee ed< edddid	Zee
ed< edddid	Zfe
ed< edddid	Zgee ed< edddid	ZheeJe  ed< edddid	Ziee
 ed< edddid	Zjee ed< edddid	Zkee
 ed< edNddid	Zle
ed< edNddid	Zme
ed< edddid	Zne
ed< edddid	Zoe
ed< edddid	Zpee ed< edddid	Zqee ed< edddid	Zreesef 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d< edddid	Zwe
ed< edddid	Zxe
ed< ed}dd}dddgdId	Zyeed< edddid	Zze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d=dZ}eed< edddid	Z~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d< edddi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< dd Zdd ZeZeedddZeedddZeedddZeddddZeddddZedd Zedd  Zed!d" Zed#d$ Zed%d& Zed'd( Zed)d* Zd+d, Zed-d. Zed/d0 ZejdZd2d3Zed4d5d6Zd7d8 Zd9d: Zeeef dd;d<Zd[eeeeeeee
d>d?d@Zd\eeef eeee ee e
e
dAdBdCZd]ee
e
dDdEdFZd^eeef eee e
dGdHdIZd_eeef eeeeJe f ee
e
e
edKdLdMZd`eeeesf ee e
e
dNdOdPZdaeeecf eeeeeee dQdRdSZdbeee%f eeeedTdUdVZdceee
ee
e
e
ee dWdXdYZdS (d  TrainingArgumentsuɉ  
    TrainingArguments is the subset of the arguments we use in our example scripts **which relate to the training loop
    itself**.

    Using [`HfArgumentParser`] we can turn this class into
    [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
    command line.

    Parameters:
        output_dir (`str`):
            The output directory where the model predictions and checkpoints will be written.
        overwrite_output_dir (`bool`, *optional*, defaults to `False`):
            If `True`, overwrite the content of the output directory. Use this to continue training if `output_dir`
            points to a checkpoint directory.
        do_train (`bool`, *optional*, defaults to `False`):
            Whether to run training or not. This argument is not directly used by [`Trainer`], it's intended to be used
            by your training/evaluation scripts instead. See the [example
            scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.
        do_eval (`bool`, *optional*):
            Whether to run evaluation on the validation set or not. Will be set to `True` if `evaluation_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.
        evaluation_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"no"`):
            The evaluation strategy to adopt during training. Possible values are:

                - `"no"`: No evaluation is done during training.
                - `"steps"`: Evaluation is done (and logged) every `eval_steps`.
                - `"epoch"`: Evaluation is done at the end of each epoch.

        prediction_loss_only (`bool`, *optional*, defaults to `False`):
            When performing evaluation and generating predictions, only returns the loss.
        per_device_train_batch_size (`int`, *optional*, defaults to 8):
            The batch size per GPU/XPU/TPU/MPS/NPU core/CPU for training.
        per_device_eval_batch_size (`int`, *optional*, defaults to 8):
            The batch size per GPU/XPU/TPU/MPS/NPU core/CPU for evaluation.
        gradient_accumulation_steps (`int`, *optional*, defaults to 1):
            Number of updates steps to accumulate the gradients for, before performing a backward/update pass.

            <Tip warning={true}>

            When using gradient accumulation, one step is counted as one step with backward pass. Therefore, logging,
            evaluation, save will be conducted every `gradient_accumulation_steps * xxx_step` training examples.

            </Tip>

        eval_accumulation_steps (`int`, *optional*):
            Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU. If
            left unset, the whole predictions are accumulated on GPU/NPU/TPU before being moved to the CPU (faster but
            requires more memory).
        eval_delay (`float`, *optional*):
            Number of epochs or steps to wait for before the first evaluation can be performed, depending on the
            evaluation_strategy.
        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`.
            In case of using a finite iterable dataset the training may stop before reaching the set number of steps
            when all data is exhausted
        lr_scheduler_type (`str` or [`SchedulerType`], *optional*, defaults to `"linear"`):
            The scheduler type to use. See the documentation of [`SchedulerType`] for all 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 and evaluate 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.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`.
        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 `False`):
            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.
        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", "cuda_amp", "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/performance#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 `evaluation_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*):
            A descriptor for the run. Typically used for [wandb](https://www.wandb.com/) and
            [mlflow](https://www.mlflow.org/) logging.
        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.

            (Note that this behavior is not implemented for [`TFTrainer`] yet.)
        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 `evaluation_strategy`, and in
            the case it is "steps", `save_steps` must be a round multiple of `eval_steps`.

            </Tip>

        metric_for_best_model (`str`, *optional*):
            Use in conjunction with `load_best_model_at_end` to specify the metric to use to compare two different
            models. Must be the name of a metric returned by the evaluation with or without the prefix `"eval_"`. Will
            default to `"loss"` if unspecified and `load_best_model_at_end=True` (to use the evaluation loss).

            If you set this value, `greater_is_better` will default to `True`. Don't forget to set it to `False` if
            your metric is better when lower.
        greater_is_better (`bool`, *optional*):
            Use in conjunction with `load_best_model_at_end` and `metric_for_best_model` to specify if better models
            should have a greater metric or not. Will default to:

            - `True` if `metric_for_best_model` is set to a value that isn't `"loss"` or `"eval_loss"`.
            - `False` if `metric_for_best_model` is not set, or set to `"loss"` or `"eval_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.
        sharded_ddp (`bool`, `str` or list of [`~trainer_utils.ShardedDDPOption`], *optional*, defaults to `''`):
            Use Sharded DDP training from [FairScale](https://github.com/facebookresearch/fairscale) (in distributed
            training only). This is an experimental feature.

            A list of options along the following:

            - `"simple"`: to use first instance of sharded DDP released by fairscale (`ShardedDDP`) similar to ZeRO-2.
            - `"zero_dp_2"`: to use the second instance of sharded DPP released by fairscale (`FullyShardedDDP`) in
              Zero-2 mode (with `reshard_after_forward=False`).
            - `"zero_dp_3"`: to use the second instance of sharded DPP released by fairscale (`FullyShardedDDP`) in
              Zero-3 mode (with `reshard_after_forward=True`).
            - `"offload"`: to add ZeRO-offload (only compatible with `"zero_dp_2"` and `"zero_dp_3"`).

            If a string is passed, it will be split on space. If a bool is passed, it will be converted to an empty
            list for `False` and `["simple"]` for `True`.
        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.
            - `"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
            deepspeed json config file (e.g., `ds_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 `False`)
                    If `"True"`, allows non-uniform `requires_grad` during init, which means support for interspersed
                    frozen and trainable paramteres. Useful in cases such as parameter-efficient fine-tuning. Please
                    refer this
                    [blog](https://dev-discuss.pytorch.org/t/rethinking-pytorch-fully-sharded-data-parallel-fsdp-from-first-principles/1019
                - sync_module_states (`bool`, *optional*, defaults to `True`)
                    If `"True"`, each individually wrapped FSDP unit will broadcast module parameters from rank 0 to
                    ensure they are the same across all ranks after initialization
                - 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.
                - 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.

        deepspeed (`str` or `dict`, *optional*):
            Use [Deepspeed](https://github.com/microsoft/deepspeed). This is an experimental feature and its API may
            evolve in the future. The value is either the location of DeepSpeed json config file (e.g.,
            `ds_config.json`) or an already loaded json file as a `dict`"
        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: adamw_hf, adamw_torch, adamw_torch_fused, adamw_apex_fused, adamw_anyprecision or
            adafactor.
        optim_args (`str`, *optional*):
            Optional arguments that are supplied to AnyPrecisionAdamW.
        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"`, `"flyte"`, `"mlflow"`, `"neptune"`,
            `"tensorboard"`, and `"wandb"`. Use `"all"` to report to all integrations installed, `"none"` for no
            integrations.
        ddp_find_unused_parameters (`bool`, *optional*):
            When using distributed training, the value of the flag `find_unused_parameters` passed to
            `DistributedDataParallel`. Will default to `False` if gradient checkpointing is used, `True` otherwise.
        ddp_bucket_cap_mb (`int`, *optional*):
            When using distributed training, the value of the flag `bucket_cap_mb` passed to `DistributedDataParallel`.
        ddp_broadcast_buffers (`bool`, *optional*):
            When using distributed training, the value of the flag `broadcast_buffers` passed to
            `DistributedDataParallel`. Will default to `False` if gradient checkpointing is used, `True` otherwise.
        dataloader_pin_memory (`bool`, *optional*, defaults to `True`):
            Whether you want to pin memory in data loaders or not. Will default to `True`.
        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 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 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*, defaults to `False`):
            If True, the Hub repo will be set to private.
        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.
        include_inputs_for_metrics (`bool`, *optional*, defaults to `False`):
            Whether or not the inputs will be passed to the `compute_metrics` function. This is intended for metrics
            that need inputs, predictions and references for scoring calculation in Metric class.
        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.
    pthelpzQThe output directory where the model predictions and checkpoints will be written.)metadata
output_dirFz|Overwrite the content of the output directory. Use this to continue training if output_dir points to a checkpoint directory.)rE   r[   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.evaluation_strategyzBWhen performing evaluation and predictions, only returns the loss.prediction_loss_only   z5Batch size per GPU/TPU/MPS/NPU core/CPU for training.per_device_train_batch_sizez7Batch size per GPU/TPU/MPS/NPU core/CPU for evaluation.per_device_eval_batch_sizeNzrDeprecated, the use of `--per_device_train_batch_size` is preferred. Batch size per GPU/TPU core/CPU for training.per_gpu_train_batch_sizezsDeprecated, the use of `--per_device_eval_batch_size` is preferred. Batch size per GPU/TPU core/CPU for evaluation.per_gpu_eval_batch_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   zyNumber of epochs or steps to wait for before the first evaluation can be performed, depending on the evaluation_strategy.
eval_delay-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_epochsr,   zQIf > 0: set total number of training steps to perform. Override num_train_epochs.	max_stepslinearzThe scheduler type to use.lr_scheduler_typez8Linear 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'.)rZ   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_nodeuT   This argument is deprecated. It will be removed in version 5.0 of 🤗 Transformers.no_cudaz^ Whether or not to use cpu. If set to False, we will use cuda/tpu/mps/npu device if available.use_cpuu   This argument is deprecated. `mps` device will be used if available similar to `cuda` device. It will be removed in version 5.0 of 🤗 Transformersuse_mps_device*   z:Random seed that will be set at the beginning of training.seedz*Random seed to be used with data samplers.	data_seedz5Whether or not to use PyTorch jit trace for inferencejit_mode_evalzzUse Intel extension for PyTorch when it is available, installation: 'https://github.com/intel/intel-extension-for-pytorch'use_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fp16Z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.Zcuda_ampapexZ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 trainingZncclZglooZmpiZcclZhccl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_debug 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_workerszRIf >=0, uses the corresponding part of the output as the past state for next step.
past_indexzCAn optional descriptor for the run. Notably used for wandb 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_skipar  Whether or not to use sharded DDP training (in distributed training only). The base option should be `simple`, `zero_dp_2` or `zero_dp_3` and you can add CPU-offload to `zero_dp_2` or `zero_dp_3` like this: zero_dp_2 offload` or `zero_dp_3 offload`. You can add auto-wrap to `zero_dp_2` or `zero_dp_3` with the same syntax: zero_dp_2 auto_wrap` or `zero_dp_3 auto_wrap`.sharded_ddpa  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 afsdp json config file (e.g., `fsdp_config.json`) or an already loaded json file as `dict`.fsdp_configzThis 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_wrapzEnable deepspeed and pass the path to deepspeed json config file (e.g. `ds_config.json`) or an already loaded json file as a dict	deepspeedzEThe label smoothing epsilon to apply (zero means no label smoothing).label_smoothing_factorrP   zThe optimizer to use.optimz*Optional arguments to supply to optimizer.
optim_argsz-Whether or not to replace AdamW by Adafactor.rQ   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_memoryzDWhether or not to skip adding of memory profiler reports to metrics.skip_memory_metricsz@Whether or not to use the legacy prediction_loop in the Trainer.use_legacy_prediction_loopzKWhether or not to upload the trained model to the model hub after training.push_to_hubz<The path to a folder with a valid checkpoint for your model.resume_from_checkpointzGThe name of the repository to keep in sync with the local `output_dir`.hub_model_id
every_savez:The hub strategy to use when `--push_to_hub` is activated.hub_strategyz*The token to use to push to the Model Hub.	hub_tokenz/Whether the model repository is private or not.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_checkpointingzKWhether or not the inputs will be passed to the `compute_metrics` function.include_inputs_for_metricsz.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reprrE   _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_modeaV  Whether to dispatch batches across devices in distributed training. If set to `True`, the dataloader prepared by the Accelerator is only iterated through on the main processand then the batches are split and broadcast to each process. Will default to `True` for `DataLoader` whoseunderlying dataset is an `IterableDataset`, `False` otherwise.dispatch_batcheszVIf set to `True`, the speed metrics will include `tgs` (tokens per second per device).include_tokens_per_secondc              	   C   s  | j d k	rtj| j | _ | jd krB| j d k	rBtj| j t | _| jd k	r\tj| j| _| jd krvt	 t
jk| _t| jtrtdt | jj| _| jrtdt | j| _t| j| _t| j| _t| j| _t| j| _t| j| _| jdkr| jtjkrd| _| jtjkrn| jd ks4| jdkrn| j dkr\t!d| j   | j | _nt"d| j d| jtjkr| j dkrt"d	| j d
| jtjkr| j dkr| j t#| j krt"d| j  t#| j | _ | jtjkr*| jdkr*| jt#| jkrt"d| j t#| j| _| jtjkrr| j$dkrr| j$t#| j$krft"d| j$ t#| j$| _$| j%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 rB| jdk r| j$dk s
t"d| j$ d| j dd}| j$| | j|  dkrBt"d| j$ d| j dt"d| j$ d| j dt& }| j'r|st"d| j' d| j's|rt!d| j' d | j%s| jtj(kr| j)d krd| _)| j*d kr| j)d k	r| j)dk| _*| j+d kr| j | _+| j,dkrt- r| j.r@| j.d kr@td!t | j.| _/| j0sP| j1r| jrrt2 srt3 srt"d"nl| jst4j56 rt7 st"d#nFt8 rdd$l9m:} |st"d%n"t; sdd&l9m<} |st"d'| j=r| j0rt"d(| j>r| j1rt"d)| j0rF| j/d*kr*t"d+| j?d,ksF| j?rFt"d-| jtj(krz| jtjkrjt"d.t- szt"d/t@| jA| _A| jBrtd0t t@jC| _A| jAt@jDkrt- rtEFtEFt4jGjHtEFd1k rt"d2tEFtEFt4jGjHtEFd1kr| j=rt"d3| j,dkrvt- rv| jIjJd4krv| jIjJd5krv| jIjJd6krvtK| jId7krv| j=sn| j>rvt"d8| j,dkrt- r| jIjJd4kr| jIjJd5kr| jIjJd6krtK| jId7krtK| jId9kr| jIjJd:kr| j0s| j1rt"d;| jLd k	rtd<t | jL| _M| jNd k	s2| jMd k	r@| jOs@d| _O| jOrZ| jMd krZd=| _M| jOrd>}| jMtjP|d? < | jNd k	r| jNtjP|d@ < | j,dkrt- r| jOrtQ r| jRd kr| j=r| j0rt!dA dt4jSj5jT_Udt4jSjV_Un
tWdB | j,dkrnt- rn| jRd k	rn| jRrPtQ rFdt4jSj5jT_Udt4jSjV_Unt"dCntQ rndt4jSj5jT_Udt4jSjV_U| j/d*krtX| j?dkrtjPYdDdE}| j=rdF}n| j0rdG}|tjPdD< | jZd krt!dH dI| _Z| jZdIks| jZdIgk	rddJl[m\} | | _Zn:| jZdKk	s"| jZdKgk	r*g | _Znt| jZt]	sB| jZg| _Z| j^dk 	sZ| j^dk	rdt"dLn"| j^dk	r| j_dk	rt!dM | j?d,k	s| j?	rtdNt t| j?t`	r| j?	rdOnd,| _?t| j?ta	rdPdQ | j?b D | _?| j?tcjdgk
rt"dRnLtX| j?dk
r,tcje| j?k
r,t"dSn$tcjf| j?k
rPtcjg| j?k
rPt"dTt| jht`
rp| jh
rjdUnd,| _ht| jhta
rdVdQ | jhb D | _h| jhtijdgk
rt"dWn$tijj| jhk
rtijk| jhk
rt"dX| jld k
ri | _lt| jltarvtX| jhdkrtdY tmjn| jldZd[d\R}top|| _lt]| jlq D ]0}	|	rd]r:| jls|	}
|
| jl|	d^d  < q:W 5 Q R X | jtdkrtd_t tu| jlYd`d| jt| jld`< t| jlYdad tar| jlda g| jlda< | jvd k	rtdbt | jlYdag | jvg | jlda< tX| jhdkr0| jld` dkr0tdc tX| jhdkr^| jlYdad d k	r^tdd tX| jhdkr| jld` dkr| jlYdad d k	rt"de| jlYdfd| jldf< | jlYdgd| jldg< | jldf r@tX| jhdkr4| jlYdhi | _wdi| jwkrtxt4| jwdi | jwdi< dj| jwkr>txt4| jwdj | jwdj< n
tdk n| jldg rVtdl tX| jhdkr| jldf sdmtjPdn< ddolymz}m{} dp}| jhD ]}|| |krta|}|| d tjP| dq< n|tijdkrdmtjP| dr< n|tij~kr|d tjP| ds< | jld` dkrJta| jld` tjP| dt< |d tjP| ds< n0| jlYdad d k	rdu| jlda tjP| dv< q| jlYdwdx}|| tjP| dy< | jlYdzd{tjP| d|< | jlYd}dmtjP| d~< | jlYdd{tjP| d< | jr*tdt | jd krd| _n|  jd7  _d| _t| jtarPddQ | jb D | _n| jd krbg | _d | _| jrt st"dddlm} || j| _| j|  ddlm} dmtjPd< || jd| _nLttjPYdd{rddlm} | | _tjPYdDdE}| j| | j  | jd k	r6tdt | j| _| jd k	rt| j| j| jd| _| jd k	r|td| j dt ntd| j dt n<| jd k	r| j dt| j j | _td| j dt d S )Nu   using `EvaluationStrategy` for `evaluation_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   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_stepsz 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!loss)r   Z	eval_lossrY   r   ux   `fp16_backend` is deprecated and will be removed in version 5 of 🤗 Transformers. Use `half_precision_backend` insteadzLYour setup doesn't support bf16/(cpu, tpu, neuroncore). You need torch>=1.10z[Your setup doesn't support bf16/gpu. You need torch>=1.10, using Ampere GPU with cuda>=11.0)#is_torch_greater_or_equal_than_1_11zfYour setup doesn't support bf16/npu. You need torch>=1.11, using Ascend NPU with `torch_npu` installed)#is_torch_greater_or_equal_than_1_12zbYour setup doesn't support bf16/xpu. You need torch>=1.12, using Intel XPU/GPU with IPEX installedz6At most one of fp16 and bf16 can be True, but not bothzDAt most one of fp16 and bf16 can be True for full eval, but not bothr   zt `--half_precision_backend apex`: GPU bf16 is not supported by apex. Use `--half_precision_backend cuda_amp` insteadr   z&sharded_ddp is not supported with bf16z@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.0cudanpuxpuZGPUzFP16 Mixed precision training with AMP or APEX (`--fp16`) and FP16 half precision evaluation (`--fp16_full_eval`) can only be used on CUDA or NPU devices or certain XPU devices (with IPEX).TPUcpuzBF16 Mixed precision training with AMP (`--bf16`) and BF16 half precision evaluation (`--bf16_full_eval`) can only be used on CUDA, XPU (with IPEX), NPU or CPU/TPU/NeuronCore devices.uv   `torchdynamo` is deprecated and will be removed in version 5 of 🤗 Transformers. Use `torch_compile_backend` insteadZinductorZACCELERATE_DYNAMO_ZBACKENDZMODEz`Setting TF32 in CUDA backends to speedup torch compile, you won't see any improvement otherwise.zaThe speedups for torchdynamo mostly come wih GPU Ampere or higher and which is not detected here.zC--tf32 requires Ampere or a newer GPU arch, cuda>=11 and torch>=1.7ZACCELERATE_MIXED_PRECISIONra   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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 trainingun   using `sharded_ddp` is deprecated and will be removed in version 4.33 of 🤗 Transformers. Use `fsdp` insteadsimplec                 S   s   g | ]}t |qS r?   )r   .0sr?   r?   r@   
<listcomp>  s     z3TrainingArguments.__post_init__.<locals>.<listcomp>z`--sharded_ddp offload` can't work on its own. It needs to be added to `--sharded_ddp zero_dp_2` or `--sharded_ddp zero_dp_3`. For example, `--sharded_ddp "zero_dp_2 offload"`.z?`--sharded_ddp simple` is not compatible with any other option.zK`--sharded_ddp zero_dp_2` is not compatible with `--sharded_ddp zero_dp_3`.Z
full_shardc                 S   s   g | ]}t |qS r?   )r   r   r?   r?   r@   r     s     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`.z:`--fsdp_config` is useful only when `--fsdp` is specified.rzutf-8)encodingZfsdp_   zEusing `--fsdp_min_num_params` is deprecated. Use fsdp_config instead Zmin_num_paramsZ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.r0   Zxla_fsdp_grad_ckptZxla_fsdp_settingsZcompute_dtypeZ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.trueZACCELERATE_USE_FSDP)FSDP_AUTO_WRAP_POLICYFSDP_SHARDING_STRATEGYZFSDP_ZSHARDING_STRATEGYZOFFLOAD_PARAMSZAUTO_WRAP_POLICYZMIN_NUM_PARAMS,ZTRANSFORMER_CLS_TO_WRAPZfsdp_backward_prefetchZNO_PREFETCHZBACKWARD_PREFETCHZforward_prefectfalseZFORWARD_PREFETCHZsync_module_statesZSYNC_MODULE_STATESZuse_orig_paramsZ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   s   g | ]}t |qS r?   r   r   r?   r?   r@   r     s     zJ--deepspeed requires Accelerate to be installed: `pip install accelerate`.)HfTrainerDeepSpeedConfig)DeepSpeedPluginACCELERATE_USE_DEEPSPEED)Zhf_ds_configuu   `--push_to_hub_token` is deprecated and will be removed in version 5 of 🤗 Transformers. Use `--hub_token` instead.)Z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 )r\   r:   r;   
expanduserr   r<   rA   r   loggergetEffectiveLevelr'   WARN
isinstancerb   r   warningswarnFutureWarningvaluer   r   r   r   r   r   r   r   rz   r_   NOSTEPSr   r   info
ValueErrorrB   r   r   r   r   ZREDUCE_ON_PLATEAUr   r   r   	frameworkr   r   r   r   r   r    r%   torchr   is_availabler!   r#   Zpytorch_utilsr   r&   r   r   r   r   rO   r   rQ   rW   rV   r   parse__version__base_versionrJ   typerN   r   r   r   r   rC   r$   r   backendsmatmulZ
allow_tf32Zcudnnr   lenrD   r   Zintegrationsr   listr{   r|   boolstrrM   r   ZOFFLOADSIMPLEZ	ZERO_DP_2Z	ZERO_DP_3r   r   Z
FULL_SHARDZSHARD_GRAD_OPr   ioopenjsonloadkeys
startswithpopr   maxr   Zxla_fsdp_configgetattrZaccelerate.utils.constantsr   r   upperindexZ	AUTO_WRAPr   r   Zdeepspeed_pluginr   r   Z#transformers.integrations.deepspeedr   Zhf_deepspeed_configZtrainer_config_processaccelerate.utilsr   r)   Zset_mixed_precisionZset_deepspeed_weakrefr   r   r   r   r   r   r   name)selfZLARGE_MULTIPLIERZsafetensors_availabler   r   prefixZmixed_precision_dtyper   fkvr   r   Zfsdp_optionZprefetch_policyr   r   Zmixed_precisionr?   r?   r@   __post_init__  s    



&
 

 (


	



		  







   
 
$





  zTrainingArguments.__post_init__c                 C   sV   t | }|d= |d= dd | D }dd t| D }| jj dd| d	S )
Nrg   rh   c                 S   s0   i | ](\}}|| d r(d|  dn|qS )_token<>)endswithr#  r   r*  r+  r?   r?   r@   
<dictcomp>  s      z-TrainingArguments.__str__.<locals>.<dictcomp>c                 S   s    g | ]\}}| d | dqS )=z,
r?   r1  r?   r?   r@   r     s     z-TrainingArguments.__str__.<locals>.<listcomp>z(
r   ))r   itemssorted	__class__rR   r<   )r'  Zself_as_dictZattrs_as_strr?   r?   r@   __str__  s    zTrainingArguments.__str__r2   c                 C   s0   | 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   )rg   r   r   re   r!  n_gpu)r'  per_device_batch_sizetrain_batch_sizer?   r?   r@   r;    s    z"TrainingArguments.train_batch_sizec                 C   s0   | j rtd | j p| j}|td| j }|S )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   )rh   r   r   rf   r!  r9  )r'  r:  eval_batch_sizer?   r?   r@   r<    s    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   r   r'  r?   r?   r@   ddp_timeout_delta  s    z#TrainingArguments.ddp_timeout_deltarI   c                 C   s  t | dg td t s:tdds.tdtjdd d | _| j	sZdt
jkrZd	t
jd< | jsrtt
jd
drtd| jd| _d| _nt rt }td|}d| _tj| nt rdt
jkrdt
jd< tt| jdd| _td}d| _npt rtdd| _d| _nT| jrJdt
jd< tt| jdd| _t
jd= d| _nt| jt| jdd| _d| _t s| jj}| jj| _t rt  r| j!t"j#krt$d t% r| jj}d| _nLt st rܐn8| jj&t'j(kr&dt
jkrdt
jd< tj)* | _td}tj)| n| jj&t'j+kr| j,r\t-.d |j/dkr\t0d|j/dkrpd| _n| jrtd}d| _nt rtd}tj)| d| _ndt1 rtd}tj2| d| _n>ttj rdnd}tj* | _|j/dkrtj| |S )Nr  zPyTorch: setting up devicesz0.20.1)min_versionzUsing the `Trainer` with `PyTorch` requires `accelerate>=0.20.1`: Please run `pip install transformers[torch]` or `pip install accelerate -U`T)Zreset_partial_stateZACCELERATE_USE_IPEXr   ZACCELERATE_USE_CPUFalse)r   r1   r   r   r   ZACCELERATE_USE_XPUr   r=  )timeoutzxpu:0)Z_use_sagemaker_dpr   )r1   rC  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. Z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.r   znpu:0zcuda:0)3r(   r   r
  r   r   ImportErrorr-   Z_reset_statedistributed_stater   r:   rC   r   r)   rD   r.   r   r   smpr   r  rJ   r   Z
set_devicer&   r   r   r   r   local_process_indexdistr  Zis_initializedparallel_modeParallelModeDISTRIBUTEDr   r%   distributed_typer/   Z	MULTI_XPUr   Zdevice_countr  r   r  r  r  r  r#   r   )r'  r   rJ   r?   r?   r@   _setup_devices  s    





 

"





z TrainingArguments._setup_devicesc                 C   s   t | dg | jS )z2
        The device used by this process.
        r  )r(   rM  r?  r?   r?   r@   rJ   g  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  r   )r(   hasattrrM  r   )r'  r6   r?   r?   r@   r9  o  s    	
zTrainingArguments.n_gpuc                 C   s|   t | dg t rtjS t r$tjS t r0tjS | jdk	rH| jj	t
jks\| jdkrb| jdkrbtjS | jdkrrtjS tjS d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  Nr,   r   )r(   r%   rJ  r   r   SAGEMAKER_MODEL_PARALLELr   SAGEMAKER_DATA_PARALLELrE  rL  r/   r  r   rK  r9  NOT_DISTRIBUTEDNOT_PARALLELr?  r?   r?   r@   rI  ~  s&    
zTrainingArguments.parallel_modec                 C   sB   t | dg | jdk	r| jjS t r>tjjjs6t S t	 S dS )z;
        The number of processes used in parallel.
        r  Nr   )
r(   rE  Znum_processesr   rF  statecfgprescaled_batchZdp_sizeZrdp_sizer?  r?   r?   r@   
world_size  s    
zTrainingArguments.world_sizec                 C   sB   t | dg | jdk	r| jjS t r>tjjjs6t S t	 S dS )z8
        The index of the current process used.
        r  Nr   )
r(   rE  process_indexr   rF  rS  rT  rU  Zdp_rankZrdp_rankr?  r?   r?   r@   rW    s    
zTrainingArguments.process_indexc                 C   s0   t | dg | jdk	r| jjS t r,t S dS )z6
        The index of the local process used.
        r  Nr   )r(   rE  rG  r   rF  r   r?  r?   r?   r@   rG    s    
z%TrainingArguments.local_process_indexc                 C   s0   | j r| jdkS t r"t dkS | jdkS dS )zH
        Whether or not the current process should produce log.
        r   N)r   rG  r   rF  rankrW  r?  r?   r?   r@   
should_log  s
    
zTrainingArguments.should_logc                 C   s0   | j r| jdkS t r"t dkS | jdkS dS )zp
        Whether or not the current process should write to disk, e.g., to save models and checkpoints.
        r   N)r   rG  r   rF  rX  rW  r?  r?   r?   r@   should_save  s
    
zTrainingArguments.should_savec                 C   sJ   t | j }t | j }|dkr$t n|}|dkr8t n|}| jrF|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`.
        r,   )trainer_log_levelsr~   r   r'   Zget_verbosityrY  )r'  r~   r   Zlog_level_main_nodeZlog_level_replica_noder?   r?   r@   get_process_log_level  s
    

z'TrainingArguments.get_process_log_levelc                 C   s   t   S )zR
        Can be subclassed and overridden for some specific integrations.
        )r   r?  r?   r?   r@   place_model_on_device  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?  r?   r?   r@   !_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k	r<|r2| jjn| jj}nt rNt dk}zD|st	| j
 d	| d
|  t rt| nt  dV  W 5 |rt	| j
 d| d| d t rt| nt  X n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: z completed z, releasing all replicasz: waiting for the z to perform )r   rV  rE  Zis_local_main_processis_main_processr   rF  rX  r   r   rW  r%   rL   Z
rendezvousrH  Zbarrier)r'  localdescZmain_process_descr`  r?   r?   r@   main_process_first  s(    

z$TrainingArguments.main_process_first)num_training_stepsc                 C   s$   | j dkr| j nt|| j }|S )z?
        Get number of steps used for a linear warmup.
        r   )r|   mathceilr{   )r'  rd  r|   r?   r?   r@   get_warmup_steps1  s    z"TrainingArguments.get_warmup_stepsc                    s    fddt  D }| D ]p\}}t|tr:|j||< t|trpt|dkrpt|d trpdd |D ||< |drd|  d||< 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 r?   )r   r&  r"  )r   r   r?  r?   r@   r2  @  s       z-TrainingArguments.to_dict.<locals>.<dictcomp>r   c                 S   s   g | ]
}|j qS r?   )r  )r   xr?   r?   r@   r   F  s     z-TrainingArguments.to_dict.<locals>.<listcomp>r-  r.  r/  )	r   r5  r  r   r  r  r  r0  r#  )r'  dr*  r+  r?   r?  r@   to_dict:  s    

$
zTrainingArguments.to_dictc                 C   s   t j|  ddS )z<
        Serializes this instance to a JSON string.
           )indent)r  dumpsrj  r?  r?   r?   r@   to_json_stringK  s    z TrainingArguments.to_json_stringc                    sN   |   }|| j| jd}ttttg t r8 t	j
  fdd| D S )uM   
        Sanitized serialization to use with TensorBoard’s hparams
        )r;  r<  c                    s*   i | ]"\}}|t | kr|nt|qS r?   )r  r  r1  Zvalid_typesr?   r@   r2  \  s      z7TrainingArguments.to_sanitized_dict.<locals>.<dictcomp>)rj  r;  r<  r  rB   floatr  r   appendr  ZTensorr5  )r'  ri  r?   ro  r@   to_sanitized_dictQ  s    z#TrainingArguments.to_sanitized_dict   )rm   
batch_sizern   
num_epochsrx   ri   r   r   c	           	      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`. In case of using a finite iterable dataset the training may stop before reaching
                the set number of steps when all data is exhausted.
            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^   rm   re   rn   rw   rx   ri   r   r   )	r'  rm   rt  rn   ru  rx   ri   r   r   r?   r?   r@   set_training_  s    @zTrainingArguments.set_training)strategyr   rt  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 )av  
        A method that regroups all arguments linked to the 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
                evaluation_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   rb   r	  r  r  r_   r   rf   rj   rk   rc   r   )r'  rw  r   rt  rx  ry  rz  r{  r?   r?   r@   set_evaluate  s    1
zTrainingArguments.set_evaluate)rt  rz  r{  c                 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`   rf   rc   r   )r'  rt  rz  r{  r?   r?   r@   set_testing  s
    "zTrainingArguments.set_testing)rw  r   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 the evaluation.

        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   r|  )r   r   r	  r  r   r   r   )r'  rw  r   r  r  r?   r?   r@   set_save	  s    )
zTrainingArguments.set_saver   )rw  r   r   level
first_stepnan_inf_filterr  replica_levelc	           	      C   sT   t || _| jt jkr&|dkr&td|| _|| _|| _|| _|| _|| _	|| _
| S )ab
  
        A method that regroups all arguments linked to the evaluation.

        Args:
            strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`):
                The logging 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 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 `"none"`):
                The list of integrations to report the results and logs to. Supported platforms are `"azure_ml"`,
                `"comet_ml"`, `"mlflow"`, `"neptune"`, `"tensorboard"`,`"clearml"` 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   r|  )r   r   r	  r  r   r   r~   r   r   r   r   )	r'  rw  r   r   r  r  r  r  r  r?   r?   r@   set_logging@	  s    >
zTrainingArguments.set_logging)model_idrw  r   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`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 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 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`):
                If True, the Hub repo will be set to private.
            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   r   r   r   r   )r'  r  rw  r   r  r  r?   r?   r@   set_push_to_hub	  s    >
z!TrainingArguments.set_push_to_hub)r&  rm   rn   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_hf"`, `"adamw_torch"`, `"adamw_torch_fused"`, `"adamw_apex_fused"`,
                `"adamw_anyprecision"` or `"adafactor"`.
            learning_rate (`float`, *optional*, defaults to 5e-5):
                The initial learning rate.
            weight_decay (`float`, *optional*, defaults to 0):
                The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights.
            beta1 (`float`, *optional*, defaults to 0.9):
                The beta1 hyperparameter for the adam optimizer or its variants.
            beta2 (`float`, *optional*, defaults to 0.999):
                The beta2 hyperparameter for the adam optimizer or its variants.
            epsilon (`float`, *optional*, defaults to 1e-8):
                The epsilon hyperparameter for the adam optimizer or its variants.
            args (`str`, *optional*):
                Optional arguments that are supplied to AnyPrecisionAdamW (only useful when
                `optim="adamw_anyprecision"`).

        Example:

        ```py
        >>> from transformers import TrainingArguments

        >>> args = TrainingArguments("working_dir")
        >>> args = args.set_optimizer(name="adamw_torch", beta1=0.8)
        >>> args.optim
        'adamw_torch'
        ```
        )rO   r   rm   rn   rp   rr   rt   r   )r'  r&  rm   rn   r  r  r  r  r?   r?   r@   set_optimizer	  s    *
zTrainingArguments.set_optimizer)r&  ru  rx   r{   r|   c                 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`. In case of using a finite iterable dataset the training may stop before reaching
                the set number of steps when all data is exhausted.
            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   rz   rw   rx   r{   r|   )r'  r&  ru  rx   r{   r|   r?   r?   r@   set_lr_scheduler
  s    &
z"TrainingArguments.set_lr_scheduler)r;  r<  	drop_lastnum_workers
pin_memoryr   r   sampler_seedc	           	      C   s4   || _ || _|| _|| _|| _|| _|| _|| _| S )a  
        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`.
            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
        ```
        )re   rf   r   r   r   r   r   r   )	r'  r;  r<  r  r  r  r   r   r  r?   r?   r@   set_dataloader0
  s    /z TrainingArguments.set_dataloader)Tr_  )rl   rd   r   rs  r,   r   r   F)ra   r   rd   NNFF)rd   FF)r   r   NF)r   r   r   r+   FFFr+   )r   NFF)rP   rl   r   ro   rq   rs   N)ry   rv   r,   r   r   )rd   rd   Fr   TFFN)rR   rS   rT   rU   r  r   r\   r  __annotations__r]   r  r^   r_   r`   rb   r   r   rc   re   rB   rf   rg   r   rh   ri   rj   rk   rp  rm   rn   rp   rr   rt   ru   rw   rx   rz   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   Zdefault_optimr   rO   r   rQ   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,  r8  __repr__propertyr;  r<  r   r@  r   rM  rJ   r9  rI  rV  rW  rG  rY  rZ  r\  r]  r^  
contextlibcontextmanagerrc  rg  rj  rn  r
   r	   rr  rv  r}  r~  r  r  r  r  r  r  r?   r?   r?   r@   rX      s  
   f
  	

 			 	   			
		  	
    	  	
	
	  			       
   		      	   uc2	       M      
?  *   
3       
M   
H      
5    
/       rX   c                   @   s$   e Zd ZdZdZdZdZdZdZdS )rJ  Znot_parallelZnot_distributeddistributedZsagemaker_model_parallelZsagemaker_data_parallelZtpuN)	rR   rS   rT   rR  rQ  rK  rO  rP  r   r?   r?   r?   r@   rJ  j
  s   rJ  )fr  r  r  re  r:   r  dataclassesr   r   r   r   r4   r   enumr   pathlibr   typingr	   r
   r   r   r   Zhuggingface_hubr   	packagingr   Zdebug_utilsr   Ztrainer_utilsr   r   r   r   r   r   utilsr   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   Zutils.genericr)   Zutils.import_utilsr*   Z
get_loggerrR   r   Zget_log_levels_dictcopyZ
log_levelsdictr[  r  Ztorch.distributedr  rH  Zaccelerate.stater-   r.   r%  r/   Ztorch_xla.core.xla_modelcoreZ	xla_modelrL   rC   rD   r
  r   Z!torch_xla.distributed.xla_backendZxla_backendZxbnr  groupZWORLDZProcessGroupXlaZinit_process_groupAssertionErrorZ!smdistributed.modelparallel.torchZmodelparallelrF  r   r  rA   rH   rN   rO   rX   rJ  r?   r?   r?   r@   <module>   s    H
		                   \