
    謜i                    P   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 ddlmZ dd	lmZmZmZmZmZ dd
lmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1m2Z2  e,jf                  e4      Z5 e,jl                         jo                         Z8 e9d'i e8ddiZ: e        r
d dl;Z;d dl<m=Z>  e       rd dl?m@Z@mAZA d dlBmCZC ddlDmEZE  ed      rd dlFmGZG neZG e*       r	d dlHmIc mJZK  e'd      rej                  j                  d      r e2       re5j                  d       ne5j                  d       d dlPm=c mQZR  eSe>j                  j                  eRj                        sB e>j                  d        eSe>j                  j                  eRj                        s eXd       e       rd dlYmZc m;Z[  e[j                           G d de      Z]de9fdZ^e G d  d!             Z_ G d" d#e      Z`d(d$ead%ebeaz  fd&Zcy))    N)asdict	dataclassfieldfields)	timedelta)Enum)cached_property)Any   )DebugOption)
FSDPOptionHubStrategyIntervalStrategySaveStrategySchedulerType)ACCELERATE_MIN_VERSIONExplicitEnumis_accelerate_availableis_sagemaker_dp_enabledis_sagemaker_mp_enabledis_torch_availableis_torch_bf16_gpu_availableis_torch_cuda_availableis_torch_hpu_availableis_torch_mlu_availableis_torch_mps_availableis_torch_musa_availableis_torch_neuroncore_availableis_torch_npu_availableis_torch_tf32_availableis_torch_xla_availableis_torch_xpu_availableloggingrequires_backends)	strtobool)enable_tf32is_optimum_neuron_availablepassive)AcceleratorStatePartialState)DistributedType)AcceleratorConfigz1.10.1)ParallelismConfigF)check_deviceTORCHELASTIC_RUN_IDzuMake sure that you are performing the training with the NeuronTrainer from optimum[neuron], this will fail otherwise.zPlease use the NeuronTrainer from optimum[neuron] instead of the Transformers library to perform training on AWS Trainium instances. More information here: https://github.com/huggingface/optimum-neuronxla)backendzGFailed to initialize torch.distributed process group using XLA backend.c                       e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!d Z"d!Z#d"Z$d#Z%d$Z&d%Z'd&Z(d'Z)d(Z*d)Z+d*Z,d+Z-y,)-OptimizerNameszB
    Stores the acceptable string identifiers for optimizers.
    adamw_torchadamw_torch_fusedadamw_torch_xlaadamw_torch_npu_fusedadamw_apex_fused	adafactoradamw_anyprecisionadamw_torch_4bitadamw_torch_8bitademamixsgdadagradadamw_bnb_8bit
adamw_8bitademamix_8bit	lion_8bit
lion_32bitpaged_adamw_32bitpaged_adamw_8bitpaged_ademamix_32bitpaged_ademamix_8bitpaged_lion_32bitpaged_lion_8bitrmsproprmsprop_bnbrmsprop_bnb_8bitrmsprop_bnb_32bitgalore_adamwgalore_adamw_8bitgalore_adafactorgalore_adamw_layerwisegalore_adamw_8bit_layerwisegalore_adafactor_layerwiselomoadalomo	grokadamwschedule_free_radamschedule_free_adamwschedule_free_sgdapollo_adamwapollo_adamw_layerwisestable_adamwN).__name__
__module____qualname____doc__ADAMW_TORCHADAMW_TORCH_FUSEDADAMW_TORCH_XLAADAMW_TORCH_NPU_FUSEDADAMW_APEX_FUSED	ADAFACTORADAMW_ANYPRECISIONADAMW_TORCH_4BITADAMW_TORCH_8BITADEMAMIXSGDADAGRAD	ADAMW_BNB
ADAMW_8BITADEMAMIX_8BIT	LION_8BITLIONPAGED_ADAMWPAGED_ADAMW_8BITPAGED_ADEMAMIXPAGED_ADEMAMIX_8BIT
PAGED_LIONPAGED_LION_8BITRMSPROPRMSPROP_BNBRMSPROP_8BITRMSPROP_32BITGALORE_ADAMWGALORE_ADAMW_8BITGALORE_ADAFACTORGALORE_ADAMW_LAYERWISEGALORE_ADAMW_8BIT_LAYERWISEGALORE_ADAFACTOR_LAYERWISELOMOADALOMO	GROKADAMWSCHEDULE_FREE_RADAMSCHEDULE_FREE_ADAMWSCHEDULE_FREE_SGDAPOLLO_ADAMWAPOLLO_ADAMW_LAYERWISESTABLE_ADAMW     V/mnt/e/genesis-system/.venv/lib/python3.12/site-packages/transformers/training_args.pyr4   r4   n   s      K+'O3)I-))H
CG IJ#MID%K)+N/#J'OGK%L'M!L+)5"?!=DGI//+!L5!Lr   r4   passed_valuec                    | j                         D ]  \  }}t        |t              rt        |      | |<   %t        |t              s6|j                         dv r|j                         dk(  | |<   _|j                         rt        |      | |<   ~|j                  ddd      j                         st        |      | |<    | S )zlSafely checks that a passed value is a dictionary and converts any string values to their appropriate types.)truefalser   . r   )
items
isinstancedict_convert_str_dictstrlowerisdigitintreplacefloat)r   keyvalues      r   r   r      s    "((* 1
UeT" 1% 8Ls#{{} 11$)KKMV$;S!$'JS!sB*224$)%LS!1 r   c                      e Zd ZU dZg dZ edddi      Zedz  ed<    eddd	i      Z	e
ed
<    edddi      Zeed<    edddi      Ze
ed<    edddi      Zeed<    edddi      Zeez  ed<    edddi      Zeez  dz  ed<    edddi      Zeed<   dZ e       r
ddlmZ erdZ eedd i      Zeez  ed!<    eddd"i      Zedz  ed#<    ed$dd%i      Zeed&<    ed'dd(i      Zeed)<    ed*dd+i      Zeed,<    ed-dd.i      Zeed/<    eddd0i      Zdez  e e   z  ed1<    eddd2i      Z!e
ed3<    ed4dd5i      Z"e#ed6<    ed7dd8i      Z$eed9<    ed$dd:i      Z%eed;<    ed<dd=i      Z&e#ed><    ed<dd?i      Z'e#ed@<    ed<ddAi      Z(e#edB<    ed<ddCi      Z)e#edD<    edddEi      Z*e#dz  edF<    ed<ddGi      Z+e#edH<    edddIi      Z,eee-f   ez  dz  edJ<    ed<ddKi      Z.e#edL<    edddMi      Z/edz  edN<    edddOi      Z0edz  edP<    ed<ddQi      Z1e#edR<    edddSi      Z2eee#f   dz  edT<    ed<ddUi      Z3e#edV<    edddWi      Z4edz  edX<    edddYi      Z5e
dz  edZ<    ed<dd[i      Z6e#ed\<    ed]dd^i      Z7e8ez  ed_<    ed`ddai      Z9eedb<    ed<ddci      Z:e#edd<    ed4ddei      Z;e#edf<    ed4ddgi      Z<e#edh<    ediddji      Z=ee#z  edk<    edldme>j                         dn      Z@eedo<    edpdqe>j                         dn      ZAeedr<    edddsi      ZBe#dz  edt<    eduddvi      ZCdez  e e   z  edw<    edddxi      ZDedz  edy<    edzdd{i      ZEeed|<    ed}dd~i      ZFedz  ed<    ediddi      ZGe8ez  ed<    edddi      ZHedz  ed<    edddi      ZIeed<    edddi      ZJe
ed<    ed<ddi      ZKe#ed<    ed<ddi      ZLe#ed<    ed4ddi      ZMe#ed<    ed<ddi      ZNe#ed<    edddi      ZOe
dz  ed<    ee ddi      ZPe e   ed<    ed<ddi      ZQe#ed<    ed<ddi      ZRe#ed<    ed]ddi      ZSeTez  ed<    ed`ddi      ZUeed<    ed<ddi      ZVe#ed<    edddi      ZWe
dz  ed<    ed<ddi      ZXe#ed<    ed<ddi      ZYe#ed<    edddi      ZZedz  ed<    edddi      Z[e#dz  ed<    edddi      Z\edz  ed<    edddi      Z]e^ez  ed<    ed<ddi      Z_e#ed<    edddi      Z`edz  ed<    ed<ddi      Zae#ed<    edddi      Zbedz  ed<    edddi      Zce#dz  ed<    ed<ddi      Zde#ed<    ed<ddi      Zee#ed<    ed<ddi      Zfe#ed<    edddi      Zge
ed<    edddi      Zhe
dz  ed<    ed<ddi      Zie#ed<    edddi      Zjeez  dz  ed<    edddi      Zkeldz  ed<    ed<ddi      Zme#ed<    edddi      Zne
ed<    ed4ddi      Zoe#ed<    ed<ddi      Zpe#ed<    edddi      Zqe
dz  ed<    ed4ddi      Zre#ed<    edddi      Zse e   dz  ed<    eddg d٢dn      Zteed<    edddi      Zueed<    edddi      Zve#dz  ed<    edddi      Zwe
dz  ed<    edddi      Zxe#dz  ed<    eddg ddn      Zyedz  ed<    edddi      Zze
ed<    edddi      Z{e e|   ez  dz  ed<    edddi      Z}eee-f   ez  dz  ed<    edddi      Z~eez  dz  ed<    edddi      Zee e   z  ed<    ed4ddi      Ze#ed<    ed<ddi      Ze#ed<    ed<ddi      Ze#ed<    ed<ddi      Ze#ed<    edddi      Zedz  ed<    edddi      Zedz  ed<    edddi      Zedz  ed <    edddi      Ze
ed<   d Zd Zd ZeZede
fd       Zede
fd       Zedefd	       ZedFd
       ZedFd       Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zd Zede#dz  fd       Zed        Zej@                  dGd       Zde
fdZdeee-f   ddfdZd Zd Zdeee-f   fdZ	 	 	 	 	 	 	 	 dHdede
d&edede
d3e
de
dHe#fd Z	 	 	 	 	 	 dId!ee8z  d]e
de
d"e
dz  d#edz  d$e#fd%Z	 	 dJde
d$e#fd&Z	 	 	 	 dKd!ee8z  d]e
d'e
dz  d(e#fd)Z	 	 	 	 	 	 	 	 dLd!ee8z  d]e
dwee e   z  d*ed+e#d,e#d(e#d-efd.Z	 	 	 	 	 dMd/ed!ee^z  d0edz  d1e#dz  d2e#d3edz  fd4Z	 	 	 	 	 	 	 dNd5eez  ded&ed6ed7ed8ed9edz  fd:Z	 	 	 	 	 dOd5eez  dede
dededz  f
d;Z	 	 	 	 	 	 	 	 	 	 dPd<e
d=e
d>e#d?e
d@e#dAe#dBe
dz  d\e#de#dCe
dz  fdDZdE Zy(Q  TrainingArgumentsu  
    Configuration class for controlling all aspects of model training with the Trainer.
    TrainingArguments centralizes all hyperparameters, optimization settings, logging preferences, and infrastructure choices needed for training.

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

    Parameters:
        output_dir (`str`, *optional*, defaults to `"trainer_output"`):
            The output directory where the model predictions and checkpoints will be written.

        > Training Duration and Batch Size

        per_device_train_batch_size (`int`, *optional*, defaults to 8):
            The batch size *per device*. The **global batch size** is computed as:
            `per_device_train_batch_size * number_of_devices` in multi-GPU or distributed setups.
        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):
            Overrides `num_train_epochs`. If set to a positive number, the total number of training steps to perform.
            For a finite dataset, training is reiterated through the dataset (if all data is exhausted) until
            `max_steps` is reached.

        > Learning Rate & Scheduler

        learning_rate (`float`, *optional*, defaults to 5e-5):
            The initial learning rate for the optimizer. This is typically the peak learning rate when using a scheduler with warmup.
        lr_scheduler_type (`str` or [`SchedulerType`], *optional*, defaults to `"linear"`):
            The learning rate scheduler type to use. See [`SchedulerType`] for all possible values. Common choices:
                - "linear" = [`get_linear_schedule_with_warmup`]
                - "cosine" = [`get_cosine_schedule_with_warmup`]
                - "constant" =  [`get_constant_schedule`]
                - "constant_with_warmup" = [`get_constant_schedule_with_warmup`]
        lr_scheduler_kwargs (`dict` or `str`, *optional*, defaults to `None`):
            The extra arguments for the lr_scheduler. See the documentation of each scheduler for possible values.
        warmup_steps (`int` or `float`, *optional*, defaults to 0):
            Number of steps for a linear warmup from 0 to `learning_rate`. Warmup helps stabilize training in the initial phase. Can be:
                - An integer: exact number of warmup steps
                - A float in range [0, 1): interpreted as ratio of total training steps

        > Optimizer

        optim (`str` or [`training_args.OptimizerNames`], *optional*, defaults to `"adamw_torch"` (for torch>=2.8 `"adamw_torch_fused"`)):
            The optimizer to use. Common options:
                - `"adamw_torch"`: PyTorch's AdamW (recommended default)
                - `"adamw_torch_fused"`: Fused AdamW kernel
                - `"adamw_hf"`: HuggingFace's AdamW implementation
                - `"sgd"`: Stochastic Gradient Descent with momentum
                - `"adafactor"`: Memory-efficient optimizer for large models
                - `"adamw_8bit"`: 8-bit AdamW (requires bitsandbytes)
                See [`OptimizerNames`] for the complete list.
        optim_args (`str`, *optional*):
            Optional arguments that are supplied to optimizers such as AnyPrecisionAdamW, AdEMAMix, and GaLore.
        weight_decay (`float`, *optional*, defaults to 0):
            Weight decay coefficient applied by the optimizer (not the loss function). Adds L2
            regularization to prevent overfitting by penalizing large weights. Automatically
            excluded from bias and LayerNorm parameters. Typical values: 0.01 (standard), 0.1
            (stronger regularization), 0.0 (no regularization).
        adam_beta1 (`float`, *optional*, defaults to 0.9):
            The exponential decay rate for the first moment estimates (momentum) in Adam-based
            optimizers. Controls how much history of gradients to retain.
        adam_beta2 (`float`, *optional*, defaults to 0.999):
            The exponential decay rate for the second moment estimates (variance) in Adam-based
            optimizers. Controls adaptive learning rate scaling.
        adam_epsilon (`float`, *optional*, defaults to 1e-8):
            Epsilon value for numerical stability in Adam-based optimizers. Prevents division by
            zero in the denominator of the update rule.
        optim_target_modules (`Union[str, list[str]]`, *optional*):
            The target modules to optimize, i.e. the module names that you would like to train.
            Currently used for the [GaLore algorithm](https://huggingface.co/papers/2403.03507) and [APOLLO algorithm](https://huggingface.co/papers/2412.05270).
            See [GaLore implementation](https://github.com/jiaweizzhao/GaLore) and [APOLLO implementation](https://github.com/zhuhanqing/APOLLO) for more details.
            You need to make sure to pass a valid GaLore or APOLLO optimizer, e.g., one of: "apollo_adamw", "galore_adamw", "galore_adamw_8bit", "galore_adafactor" and make sure that the target modules are `nn.Linear` modules only.

        > Regularization & Training Stability

        gradient_accumulation_steps (`int`, *optional*, defaults to 1):
            Number of update steps to accumulate gradients before performing a backward/update pass.
            Simulates larger batch sizes without additional memory. Effective batch size =
            `per_device_train_batch_size × num_devices × gradient_accumulation_steps`.
            > [!TIP]
            > When using gradient accumulation, one "step" is counted as one step with a backward pass. Therefore, logging, evaluation, and saving will occur every `gradient_accumulation_steps × xxx_step` training examples.
        average_tokens_across_devices (`bool`, *optional*, defaults to `True`):
            Whether or not to average tokens across devices. If enabled, will use all_reduce to synchronize
            num_tokens_in_batch for precise loss calculation. Reference:
            https://github.com/huggingface/transformers/issues/34242
        max_grad_norm (`float`, *optional*, defaults to 1.0):
            Maximum gradient norm for gradient clipping. Applied after backward pass, before
            optimizer step. Prevents gradient explosion by scaling down gradients when their global
            norm exceeds this threshold. Set to 0 to disable clipping. Typical values:
            1.0 (standard), 0.5 (more conservative), 5.0 (less aggressive).
        label_smoothing_factor (`float`, *optional*, defaults to 0.0):
            Label smoothing factor to prevent overconfidence. Replaces hard 0/1 targets with soft
            targets: 0 becomes `ε/num_labels` and 1 becomes `1 - ε + ε/num_labels`, where
            ε = `label_smoothing_factor`. Zero means no smoothing. Typical range: 0.0 to 0.1.

        > Mixed Precision Training

        bf16 (`bool`, *optional*, defaults to `False`):
            Enable bfloat16 (BF16) mixed precision training
            Generally preferred over FP16 due to better numerical stability and no loss scaling required.
        fp16 (`bool`, *optional*, defaults to `False`):
            Enable float16 (FP16) mixed precision training.
            Consider using BF16 instead if your hardware supports it.
        bf16_full_eval (`bool`, *optional*, defaults to `False`):
            Use full BF16 precision for evaluation (not just mixed precision). Faster and saves
            memory but may affect metric values slightly. Only applies during evaluation.
        fp16_full_eval (`bool`, *optional*, defaults to `False`):
            Use full FP16 precision for evaluation (not just mixed precision). Faster and saves
            memory but may affect metric values slightly. Only applies during evaluation.
        tf32 (`bool`, *optional*):
            Enable TensorFloat-32 (TF32) mode on Ampere and newer GPUs. TF32 uses 19-bit precision
            for matrix multiplications (instead of FP32's 23-bit), providing up to 8x speedup with
            negligible accuracy loss. Default depends on PyTorch version. See
            [TF32 docs](https://huggingface.co/docs/transformers/perf_train_gpu_one#tf32).

        > Gradient Checkpointing

        gradient_checkpointing (`bool`, *optional*, defaults to `False`):
            Enable gradient checkpointing to trade compute for memory. Reduces memory usage by
            clearing activations during forward pass and recomputing them during backward pass.
            Enables training larger models or batch sizes at the cost of ~20% slower training.
        gradient_checkpointing_kwargs (`dict`, *optional*, defaults to `None`):
            Keyword arguments passed to `gradient_checkpointing_enable()`.

        > Compilation

        torch_compile (`bool`, *optional*, defaults to `False`):
            Compile the model using PyTorch 2.0's `torch.compile()` for faster training. Can provide
            20-50% speedup with no code changes. Uses default compilation settings unless
            `torch_compile_backend` or `torch_compile_mode` are specified.
        torch_compile_backend (`str`, *optional*):
            Backend for `torch.compile()`. If set, automatically enables `torch_compile`. Options
            include `"inductor"` (default), `"aot_eager"`, `"cudagraphs"`. Backends vary by PyTorch
            version - see PyTorch docs for available options.
        torch_compile_mode (`str`, *optional*):
            Compilation mode for `torch.compile()`. If set, automatically enables `torch_compile`.
            Options: `"default"`, `"reduce-overhead"` (minimize Python overhead), `"max-autotune"`
            (aggressive optimization, slower compile time).

        > Kernels

        use_liger_kernel (`bool`, *optional*, defaults to `False`):
            Enable [Liger Kernel](https://github.com/linkedin/Liger-Kernel) optimizations. Increases
            multi-GPU throughput by ~20% and reduces memory usage by ~60%. Works with Flash Attention,
            FSDP, and DeepSpeed. Currently supports Llama, Mistral, Mixtral, and Gemma models.
        liger_kernel_config (`Optional[dict]`, *optional*):
            Configuration for Liger Kernel. Passed as kwargs to `_apply_liger_kernel_to_instance()`.
            Options typically include: `"rope"`, `"swiglu"`, `"cross_entropy"`,
            `"fused_linear_cross_entropy"`, `"rms_norm"`. If `None`, uses default configuration.

        > Additional Optimizations

        use_cache (`bool`, *optional*, defaults to `False`):
            Whether or not to enable cache for the model. For training, this is usually not needed apart from some PEFT methods that uses `past_key_values`.
        neftune_noise_alpha (`Optional[float]`):
            If not `None`, this will activate NEFTune noise embeddings. This can drastically improve model performance
            for instruction fine-tuning. Check out the [original paper](https://huggingface.co/papers/2310.05914) and the
            [original code](https://github.com/neelsjain/NEFTune). Support transformers `PreTrainedModel` and also
            `PeftModel` from peft. The original paper used values in the range [5.0, 15.0].
        torch_empty_cache_steps (`int`, *optional*):
            Number of steps to wait before calling `torch.<device>.empty_cache()`. If left unset or set to None, cache will not be emptied.
            This can help avoid CUDA out-of-memory errors by lowering peak VRAM usage at a cost of about [10% slower performance](https://github.com/huggingface/transformers/issues/31372).
        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.

        > Logging & Monitoring Training

        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_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_first_step (`bool`, *optional*, defaults to `False`):
            Whether to log the first `global_step` or not.
        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_nan_inf_filter (`bool`, *optional*, defaults to `True`):
             Filter out NaN and Inf losses when logging. If `True`, replaces NaN/Inf losses with the
            average of recent valid losses. Does not affect gradient computation, only logging.
        include_num_input_tokens_seen (`Optional[Union[str, bool]]`, *optional*, defaults to "no"):
            Whether to track the number of input tokens seen. Must be one of ["all", "non_padding", "no"] or a boolean value which map to "all" or "no".
            May be slower in distributed training as gather operations must be called.

        > Logging

        log_level (`str`, *optional*, defaults to `passive`):
            Logging level for the main process. Options: `"debug"`, `"info"`, `"warning"`, `"error"`,
            `"critical"`, or `"passive"` (doesn't change the current Transformers logging level,
            which defaults to `"warning"`)
        log_level_replica (`str`, *optional*, defaults to `"warning"`):
            Logging level for replica processes in distributed training. Same options as `log_level`.
        disable_tqdm (`bool`, *optional*):
            Disable tqdm progress bars. Defaults to `True` if `log_level` is warning or lower, `False` otherwise.

        > Experiment Tracking Integration

        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"`,
            `"clearml"`, `"codecarbon"`, `"comet_ml"`, `"dagshub"`, `"dvclive"`, `"flyte"`, `"mlflow"`, `"swanlab"`,
            `"tensorboard"`, `"trackio"` and `"wandb"`. Use `"all"` to report to all integrations installed, `"none"`
            for no integrations.
        run_name (`str`, *optional*):
            A descriptor for the run. Typically used for [trackio](https://github.com/gradio-app/trackio),
            [wandb](https://www.wandb.com/), [mlflow](https://www.mlflow.org/), [comet](https://www.comet.com/site) and
            [swanlab](https://swanlab.cn) logging.
        project (`str`, *optional*, defaults to `"huggingface"`):
            The name of the project to use for logging. Currently, only used by Trackio.
        trackio_space_id (`str` or `None`, *optional*, defaults to `"trackio"`):
            The Hugging Face Space ID to deploy to when using Trackio. Should be a complete Space name like
            `'username/reponame'` or `'orgname/reponame'`, or just `'reponame'` in which case the Space will be
            created in the currently-logged-in Hugging Face user's namespace. If `None`, will log to a local directory.
            Note that this Space will be public unless you set `hub_private_repo=True` or your organization's default
            is to create private Spaces."

        > Evaluation

        eval_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"no"`):
            When to run evaluation. Options:
            - `"no"`: No evaluation during training
            - `"steps"`: Evaluate every `eval_steps`
            - `"epoch"`: Evaluate at the end of each epoch
        eval_steps (`int` or `float`, *optional*):
            Number of update steps between two evaluations if `eval_strategy="steps"`. Will default to the same
            value as `logging_steps` if not set. Should be an integer or a float in range `[0,1)`. If smaller than 1,
            will be interpreted as ratio of total training steps.
        eval_delay (`float`, *optional*):
            Number of epochs or steps to wait for before the first evaluation can be performed, depending on the
            eval_strategy.
        per_device_eval_batch_size (`int`, *optional*, defaults to 8):
            The batch size per device accelerator core/CPU for evaluation.
        prediction_loss_only (`bool`, *optional*, defaults to `False`):
            When performing evaluation and generating predictions, only returns the loss.
        eval_on_start (`bool`, *optional*, defaults to `False`):
            Whether to perform a evaluation step (sanity check) before the training to ensure the validation steps works correctly.
        eval_do_concat_batches (`bool`, *optional*, defaults to `True`):
            Whether to recursively concat inputs/losses/labels/predictions across batches. If `False`,
            will instead store them as lists, with each batch kept separate.
        eval_use_gather_object (`bool`, *optional*, defaults to `False`):
            Whether to run recursively gather object in a nested list/tuple/dictionary of objects from all devices. This should only be enabled if users are not just returning tensors, and this is actively discouraged by PyTorch.
            This is useful when the labels structure is non standard, like in computer vision tasks.
        eval_accumulation_steps (`int`, *optional*):
            Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU. If
            left unset, the whole predictions are accumulated on the device accelerator before being moved to the CPU (faster but
            requires more memory).

        > Metrics Computation

        include_for_metrics (`list[str]`, *optional*, defaults to `[]`):
            Include additional data in the `compute_metrics` function if needed for metrics computation.
            Possible options to add to `include_for_metrics` list:
            - `"inputs"`: Input data passed to the model, intended for calculating input dependent metrics.
            - `"loss"`: Loss values computed during evaluation, intended for calculating loss dependent metrics.
        batch_eval_metrics (`bool`, *optional*, defaults to `False`):
            If set to `True`, evaluation will call compute_metrics at the end of each batch to accumulate statistics
            rather than saving all eval logits in memory. When set to `True`, you must pass a compute_metrics function
            that takes a boolean argument `compute_result`, which when passed `True`, will trigger the final global
            summary statistics from the batch-level summary statistics you've accumulated over the evaluation set.

        > Checkpointing & Saving

        save_only_model (`bool`, *optional*, defaults to `False`):
            Save only model weights, not optimizer/scheduler/RNG state. Significantly reduces
            checkpoint size but prevents resuming training from the checkpoint. Use when you only
            need the trained model for inference, not continued training.
            You can only load the model using `from_pretrained` with this option set to `True`.
        save_strategy (`str` or [`~trainer_utils.SaveStrategy`], *optional*, defaults to `"steps"`):
            The checkpoint save strategy to adopt during training. Possible values are:
                - `"no"`: No save is done during training.
                - `"epoch"`: Save is done at the end of each epoch.
                - `"steps"`: Save is done every `save_steps`.
                - `"best"`: Save is done whenever a new `best_metric` is achieved.
        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_on_each_node (`bool`, *optional*, defaults to `False`):
            When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on
            the main one.
            This should not be activated when the different nodes use the same storage as the files will be saved with
            the same names for each node.
        save_total_limit (`int`, *optional*):
            Maximum number of checkpoints to keep. Deletes older checkpoints in `output_dir`. When
            `load_best_model_at_end=True`, the best checkpoint is always retained plus the most
            recent ones. For example, `save_total_limit=5` keeps the 4 most recent plus the best
        enable_jit_checkpoint (`bool`, *optional*, defaults to `False`):
            Enable Just-In-Time checkpointing on SIGTERM signal for graceful termination on
            preemptible workloads. **Important**: Configure your orchestrator's graceful shutdown
            period to allow sufficient time. For Kubernetes, set `terminationGracePeriodSeconds`
            (default 30s is usually insufficient). For Slurm, use `--signal=USR1@<seconds>`.
            Required grace period ≥ longest iteration time + checkpoint save time.

        > Hugging Face Hub Integration

        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.
        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
            `hf auth login`.
        hub_private_repo (`bool`, *optional*):
            Whether to make the repo private. If `None` (default), the repo will be public unless the organization's
            default is private. This value is ignored if the repo already exists. If reporting to Trackio with
            deployment to Hugging Face Spaces enabled, the same logic determines whether the Space is private.
        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`.
        hub_strategy (`str` or [`~trainer_utils.HubStrategy`], *optional*, defaults to `"every_save"`):
            Defines what and when to push to Hub. Options:
                - `"end"`: Push only at the end of training
                - `"every_save"`: Push on each save (async to not block training)
                - `"checkpoint"`: Like `"every_save"` plus push latest checkpoint to `"last-checkpoint"` subfolder for easy resuming
                - `"all_checkpoints"`: Push all checkpoints as they appear
        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.
        hub_revision (`str`, *optional*):
            The revision to use when pushing to the Hub. Can be a branch name, a tag, or a commit hash.

        > Best Model Tracking

        load_best_model_at_end (`bool`, *optional*, defaults to `False`):
            Load the best checkpoint at the end of training. Requires `eval_strategy` to be set.
            When enabled, the best checkpoint is always saved (see `save_total_limit`).
            <Tip>
            When `True`, `save_strategy` must match `eval_strategy`, and if using `"steps"`,
            `save_steps` must be a multiple of `eval_steps`.
            </Tip>
        metric_for_best_model (`str`, *optional*):
            Metric to use for comparing models when `load_best_model_at_end=True`. Must be a metric
            name returned by evaluation, with or without the `"eval_"` prefix. Defaults to `"loss"`.
            If you set this, `greater_is_better` will default to `True` unless the name ends with
            `"loss"`. Examples: `"accuracy"`, `"f1"`, `"eval_bleu"`.
        greater_is_better (`bool`, *optional*):
            Whether higher metric values are better. Defaults based on `metric_for_best_model`:
            `True` if the metric name doesn't end in `"loss"`, `False` otherwise.

        > Resuming Training

        ignore_data_skip (`bool`, *optional*, defaults to `False`):
            When resuming training, skip fast-forwarding through the dataset to reach the previous
            state. If `True`, training starts from the beginning of the dataset (faster resume but
            results won't match interrupted training). If `False`, skips seen data (slower resume
            but exact continuation).
        restore_callback_states_from_checkpoint (`bool`, *optional*, defaults to `False`):
            Restore callback states from checkpoint when resuming. If `True`, will override callbacks
            passed to Trainer if they exist in the checkpoint.

        > Reproducibility

        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.
        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.

        > Hardware Configuration

        use_cpu (`bool`, *optional*, defaults to `False`):
            Whether or not to use cpu. If set to False, we will use the available torch device/backend.

        > Accelerate Configuration

        accelerator_config (`str`, `dict`, or `AcceleratorConfig`, *optional*):
            Configuration for the internal Accelerate integration. Can be:
                - Path to JSON config file: `"accelerator_config.json"`
                - Dictionary with config options
                - `AcceleratorConfig` instance
            Key options:
                - `split_batches` (`bool`, defaults to `False`): Whether to split batches across devices.
                    If `True`, actual batch size is the same on all devices (total must be divisible by
                    num_processes). If `False`, each device gets the specified batch size.
                - `dispatch_batches` (`bool`): If `True`, only main process iterates through dataloader
                    and dispatches batches to devices. Defaults to `True` for `IterableDataset`, `False`
                    otherwise.
                - `even_batches` (`bool`, defaults to `True`): Duplicate samples from dataset start to
                    ensure all workers get equal batch sizes.
                - `use_seedable_sampler` (`bool`, defaults to `True`): Use fully seedable random sampler
                    for reproducibility.
                - `use_configured_state` (`bool`, defaults to `False`): Use pre-initialized
                    `AcceleratorState`/`PartialState` instead of creating new one. May cause issues with
                    hyperparameter tuning.

        parallelism_config (`ParallelismConfig`, *optional*):
            Parallelism configuration for the training run. Requires Accelerate `1.10.1`

        > Dataloader

        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.
        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.
        dataloader_pin_memory (`bool`, *optional*, defaults to `True`):
            Whether you want to pin memory in data loaders or not. Will default to `True`.
        dataloader_persistent_workers (`bool`, *optional*, defaults to `False`):
            If True, the data loader will not shut down the worker processes after a dataset has been consumed once.
            This allows to maintain the workers Dataset instances alive. Can potentially speed up training, but will
            increase RAM usage. Will default to `False`.
        dataloader_prefetch_factor (`int`, *optional*):
            Number of batches loaded in advance by each worker.
            2 means there will be a total of 2 * num_workers batches prefetched across all workers.
        remove_unused_columns (`bool`, *optional*, defaults to `True`):
            Whether or not to automatically remove the columns unused by the model forward method.
        label_names (`list[str]`, *optional*):
            The list of keys in your dictionary of inputs that correspond to the labels.
            Will eventually default to the list of argument names accepted by the model that contain the word "label",
            except if the model used is one of the `XxxForQuestionAnswering` in which case it will also include the
            `["start_positions", "end_positions"]` keys.
            You should only specify `label_names` if you're using custom label names or if your model's `forward` consumes multiple label tensors (e.g., extractive QA).
        train_sampling_strategy (`str`, *optional*, defaults to `"random"`):
            The sampler to use for the training dataloader. Possible values are:

                - `"random"`: Uses `RandomSampler` (default).
                - `"sequential"`: Uses `SequentialSampler`.
                - `"group_by_length"`: Uses `LengthGroupedSampler` to group samples of roughly the same length
                  together (to minimize padding and be more efficient).

            Note: When using an `IterableDataset`, this argument is ignored.
        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 `train_sampling_strategy` is `"group_by_length"` and the dataset
            is an instance of `Dataset`.

        > DDP (DistributedDataParallel)

        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.
        ddp_backend (`str`, *optional*):
            The backend to use for distributed training. Must be one of `"nccl"`, `"mpi"`, `"xccl"`, `"gloo"`, `"hccl"`.
        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 to the [PyTorch documentation](https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group) for more
            information.

        > FSDP (Fully Sharded Data Parallel)

        fsdp (`bool`, `str` or list of [`~trainer_utils.FSDPOption`], *optional*, defaults to `None`):
            Enable PyTorch Fully Sharded Data Parallel (FSDP) for distributed training. Options:
                - `"full_shard"`: Shard parameters, gradients, and optimizer states (most memory efficient)
                - `"shard_grad_op"`: Shard only optimizer states and gradients (ZeRO-2)
                - `"hybrid_shard"`: Full shard within nodes, replicate across nodes
                - `"hybrid_shard_zero2"`: Shard gradients/optimizer within nodes, replicate across nodes
                - `"offload"`: Offload parameters and gradients to CPU (only with `"full_shard"` or
                    `"shard_grad_op"`)
                - `"auto_wrap"`: Automatically wrap layers using `default_auto_wrap_policy`
        fsdp_config (`str` or `dict`, *optional*):
            Config to be used with fsdp (Pytorch Distributed Parallel Training). The value is either a location of
            fsdp json config file (e.g., `fsdp_config.json`) or an already loaded json file as `dict`.

            A List of config and its options:
                - fsdp_version (`int`, *optional*, defaults to `1`):
                    The version of FSDP to use. Defaults to 1.
                - min_num_params (`int`, *optional*, defaults to `0`):
                    FSDP's minimum number of parameters for Default Auto Wrapping. (useful only when `fsdp` field is
                    passed).
                - transformer_layer_cls_to_wrap (`list[str]`, *optional*):
                    List of transformer layer class names (case-sensitive) to wrap, e.g, `BertLayer`, `GPTJBlock`,
                    `T5Block` .... (useful only when `fsdp` flag is passed).
                - backward_prefetch (`str`, *optional*)
                    FSDP's backward prefetch mode. Controls when to prefetch next set of parameters (useful only when
                    `fsdp` field is passed).

                    A list of options along the following:

                    - `"backward_pre"` : Prefetches the next set of parameters before the current set of parameter's
                      gradient computation.
                    - `"backward_post"` : This prefetches the next set of parameters after the current set of
                      parameter's gradient computation.
                - forward_prefetch (`bool`, *optional*, defaults to `False`)
                    FSDP's forward prefetch mode (useful only when `fsdp` field is passed).
                     If `"True"`, then FSDP explicitly prefetches the next upcoming all-gather while executing in the
                     forward pass.
                - limit_all_gathers (`bool`, *optional*, defaults to `False`)
                    FSDP's limit_all_gathers (useful only when `fsdp` field is passed).
                     If `"True"`, FSDP explicitly synchronizes the CPU thread to prevent too many in-flight
                     all-gathers.
                - use_orig_params (`bool`, *optional*, defaults to `True`)
                    If `"True"`, allows non-uniform `requires_grad` during init, which means support for interspersed
                    frozen and trainable parameters. Useful in cases such as parameter-efficient fine-tuning. Please
                    refer this
                    [blog](https://dev-discuss.pytorch.org/t/rethinking-pytorch-fully-sharded-data-parallel-fsdp-from-first-principles/1019
                - sync_module_states (`bool`, *optional*, defaults to `True`)
                    If `"True"`, each individually wrapped FSDP unit will broadcast module parameters from rank 0 to
                    ensure they are the same across all ranks after initialization
                - cpu_ram_efficient_loading (`bool`, *optional*, defaults to `False`)
                    If `"True"`, only the first process loads the pretrained model checkpoint while all other processes
                    have empty weights.  When this setting as `"True"`, `sync_module_states` also must to be `"True"`,
                    otherwise all the processes except the main process would have random weights leading to unexpected
                    behaviour during training.
                - activation_checkpointing (`bool`, *optional*, defaults to `False`):
                    If `"True"`, activation checkpointing is a technique to reduce memory usage by clearing activations of
                    certain layers and recomputing them during a backward pass. Effectively, this trades extra
                    computation time for reduced memory usage.
                - xla (`bool`, *optional*, defaults to `False`):
                    Whether to use PyTorch/XLA Fully Sharded Data Parallel Training. This is an experimental feature
                    and its API may evolve in the future.
                - xla_fsdp_settings (`dict`, *optional*)
                    The value is a dictionary which stores the XLA FSDP wrapping parameters.

                    For a complete list of options, please see [here](
                    https://github.com/pytorch/xla/blob/master/torch_xla/distributed/fsdp/xla_fully_sharded_data_parallel.py).
                - xla_fsdp_grad_ckpt (`bool`, *optional*, defaults to `False`):
                    Will use gradient checkpointing over each nested XLA FSDP wrapped layer. This setting can only be
                    used when the xla flag is set to true, and an auto wrapping policy is specified through
                    fsdp_min_num_params or fsdp_transformer_layer_cls_to_wrap.

        > DeepSpeed

        deepspeed (`str` or `dict`, *optional*):
             Enable [DeepSpeed](https://github.com/deepspeedai/DeepSpeed) integration. Value is either:
                - Path to DeepSpeed JSON config file: `"ds_config.json"`
                - Loaded config as dictionary
          > [!TIP]
          > If using ZeRO initialization, instantiate your model *after* initializing
          `TrainingArguments`, otherwise ZeRO won't be applied.

        > Debugging & Profiling (Experimental)

        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
        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.

        > External Script Flags (not used by Trainer)

        do_train (`bool`, *optional*, defaults to `False`):
            Whether to run training or not. This argument is not directly used by [`Trainer`], it's intended to be used
            by your training/evaluation scripts instead. See the [example
            scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.
        do_eval (`bool`, *optional*):
            Whether to run evaluation on the validation set or not. Will be set to `True` if `eval_strategy` is
            different from `"no"`. This argument is not directly used by [`Trainer`], it's intended to be used by your
            training/evaluation scripts instead. See the [example
            scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.
        do_predict (`bool`, *optional*, defaults to `False`):
            Whether to run predictions on the test set or not. This argument is not directly used by [`Trainer`], it's
            intended to be used by your training/evaluation scripts instead. See the [example
            scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details.
        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.
    )accelerator_configfsdp_config	deepspeedgradient_checkpointing_kwargslr_scheduler_kwargsNhelpzQThe output directory where the model predictions and checkpoints will be written.)defaultmetadata
output_dir   z'The batch size per device for training.per_device_train_batch_size      @z+Total number of training epochs to perform.num_train_epochsr)   ziOverrides `num_train_epochs`. If set to a positive number, the total number of training steps to perform.	max_steps-C6
?z,The initial learning rate for the optimizer.learning_ratelinearzUThe learning rate scheduler type to use. See `SchedulerType` for all possible values.lr_scheduler_typezfThe extra arguments for the lr_scheduler. See the documentation of each scheduler for possible values.r   r   zNumber of steps for a linear warmup from 0 to `learning_rate`. Can be an integer (exact steps) or a float in [0, 1) (ratio of total steps).warmup_stepsr5   r   )"is_torch_greater_or_equal_than_2_8r6   zAThe optimizer to use. See `OptimizerNames` for the complete list.optimzZOptional arguments supplied to optimizers such as AnyPrecisionAdamW, AdEMAMix, and GaLore.
optim_argsg        zmWeight decay coefficient applied by the optimizer. Automatically excluded from bias and LayerNorm parameters.weight_decay?z^The exponential decay rate for the first moment estimates (momentum) in Adam-based optimizers.
adam_beta1+?z_The exponential decay rate for the second moment estimates (variance) in Adam-based optimizers.
adam_beta2:0yE>z?Epsilon value for numerical stability in Adam-based optimizers.adam_epsilonzTThe target modules to optimize. Currently used for the GaLore and APOLLO algorithms.optim_target_moduleszNumber of update steps to accumulate gradients before performing a backward/update pass. Effective batch size = per_device_train_batch_size * num_devices * gradient_accumulation_steps.gradient_accumulation_stepsTzWhether or not to average tokens across devices. If enabled, will use all_reduce to synchronize num_tokens_in_batch for precise loss calculation. Reference: https://github.com/huggingface/transformers/issues/34242average_tokens_across_devicesg      ?zAMaximum gradient norm for gradient clipping. Set to 0 to disable.max_grad_normzJLabel smoothing factor to prevent overconfidence. Zero means no smoothing.label_smoothing_factorFzqEnable bfloat16 (BF16) mixed precision training. Generally preferred over FP16 due to better numerical stability.bf16ziEnable float16 (FP16) mixed precision training. Consider using BF16 instead if your hardware supports it.fp16z[Use full BF16 precision for evaluation (not just mixed precision). Faster and saves memory.bf16_full_evalz[Use full FP16 precision for evaluation (not just mixed precision). Faster and saves memory.fp16_full_evalzcEnable TF32 mode on Ampere and newer GPUs. Provides up to 8x speedup with negligible accuracy loss.tf32znEnable gradient checkpointing to trade compute for memory. Reduces memory at the cost of ~20% slower training.gradient_checkpointingz>Keyword arguments passed to `gradient_checkpointing_enable()`.r   z>Compile the model using `torch.compile()` for faster training.torch_compilezMBackend for `torch.compile()`. If set, automatically enables `torch_compile`.torch_compile_backendzVCompilation mode for `torch.compile()`. If set, automatically enables `torch_compile`.torch_compile_modez[Enable Liger Kernel optimizations. Increases throughput by ~20% and reduces memory by ~60%.use_liger_kernelz}Configuration for Liger Kernel. Passed as kwargs to `_apply_liger_kernel_to_instance()`. If None, uses default configuration.liger_kernel_configzWhether or not to use cache for the model For training, this is usually not needed apart from some PEFT methods that uses `past_key_values`.	use_cachezIf not None, activates NEFTune noise embeddings. Can drastically improve performance for instruction fine-tuning. Typical range: [5.0, 15.0].neftune_noise_alphazNumber of steps to wait before calling `torch.<device>.empty_cache()`. Helps avoid CUDA OOM at a cost of ~10% slower performance. If None, cache will not be emptied.torch_empty_cache_stepszWhether to find a batch size that will fit into memory automatically through exponential decay, avoiding CUDA Out-of-Memory errors.auto_find_batch_sizestepszOThe logging strategy to adopt during training. Options: 'no', 'epoch', 'steps'.logging_strategy  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.Whether to log the first `global_step` or not.logging_first_stepzhWhen doing a multinode distributed training, whether to log once per node or just once on the main node.log_on_each_nodez_Filter out NaN and Inf losses when logging. Does not affect gradient computation, only logging.logging_nan_inf_filternozWhether to track the number of input tokens seen. Must be one of [`all`, `non_padding`, `no`] or a boolean value which map to `all` or `no`include_num_input_tokens_seenr(   zhLogging level for the main process. Options: 'debug', 'info', 'warning', 'error', 'critical', 'passive'.)r   choices	log_levelwarningzYLogging level for replica processes in distributed training. Same options as `log_level`.log_level_replicazNDisable tqdm progress bars. Defaults to True if log_level is warning or lower.disable_tqdmnonezThe list of integrations to report the results and logs to. Use 'all' for all installed integrations, 'none' for no integrations.	report_tozfAn optional descriptor for the run. Notably used for trackio, wandb, mlflow comet and swanlab logging.run_namehuggingfacezLThe name of the project to use for logging. Currently, only used by Trackio.projecttrackioa  The Hugging Face Space ID to deploy to when using Trackio. Should be a complete Space name like 'username/reponame' or 'orgname/reponame', or just 'reponame' in which case the Space will be created in the currently-logged-in Hugging Face user's namespace. If `None`, will log to a local directory. Note that this Space will be public unless you set `hub_private_repo=True` or your organization's default is to create private Spaces.trackio_space_idz8When to run evaluation. Options: 'no', 'steps', 'epoch'.eval_strategyzNumber of update steps between evaluations if `eval_strategy='steps'`. Defaults to `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.
eval_stepszsNumber of epochs or steps to wait for before the first evaluation can be performed, depending on the eval_strategy.
eval_delayz<The batch size per device (GPU/TPU core/CPU) for evaluation.per_device_eval_batch_sizezMWhen performing evaluation and generating predictions, only returns the loss.prediction_loss_onlyzhWhether to run through the entire `evaluation` step at the very beginning of training as a sanity check.eval_on_startzWhether to recursively concat inputs/losses/labels/predictions across batches. If `False`, will instead store them as lists, with each batch kept separate.eval_do_concat_batcheszgWhether to run recursively gather object in a nested list/tuple/dictionary of objects from all devices.eval_use_gather_objectzNumber of predictions steps to accumulate the output tensors for, before moving the results to the CPU. If unset, predictions are accumulated on the accelerator before being moved to the CPU.eval_accumulation_stepszUInclude additional data in the `compute_metrics` function. Options: 'inputs', 'loss'.)default_factoryr   include_for_metricsz;Break eval metrics calculation into batches to save memory.batch_eval_metricszgSave only model weights, not optimizer/scheduler/RNG state. Prevents resuming training from checkpoint.save_only_modelz_The checkpoint save strategy to adopt during training. Options: 'no', 'epoch', 'steps', 'best'.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_stepszxWhen doing multi-node distributed training, whether to save models and checkpoints on each node, or only on the main onesave_on_each_nodezMaximum number of checkpoints to keep. Deletes older checkpoints in `output_dir`. The best checkpoint is always retained when `load_best_model_at_end=True`.save_total_limitzEnable JIT checkpointing on SIGTERM signal for graceful termination on preemptible workloads. Configure your orchestrator's graceful shutdown period accordingly.enable_jit_checkpointzJWhether or not to push the model to the Hub every time the model is saved.push_to_hubzZThe token to use to push the model to the Hub. Defaults to the token from `hf auth login`.	hub_tokena.  Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists. If reporting to Trackio with deployment to Hugging Face Spaces enabled, the same logic determines whether the Space is private.hub_private_repozGThe name of the repository to keep in sync with the local `output_dir`.hub_model_id
every_savezdDefines what and when to push to Hub. Options: 'end', 'every_save', 'checkpoint', 'all_checkpoints'.hub_strategyzTUnless `True`, the Trainer will skip pushes if the previous one wasn't finished yet.hub_always_pushz[The revision to use when pushing to the Hub. Can be a branch name, a tag, or a commit hash.hub_revisionzTLoad the best checkpoint at the end of training. Requires `eval_strategy` to be set.load_best_model_at_endzZMetric to use for comparing models when `load_best_model_at_end=True`. Defaults to 'loss'.metric_for_best_modelzSWhether higher metric values are better. Defaults based on `metric_for_best_model`.greater_is_betterzWhen resuming training, skip fast-forwarding through the dataset to reach the previous state. If True, training starts from the beginning of the dataset.ignore_data_skipzWhether to restore the callback states from the checkpoint. If `True`, will override callbacks passed to the `Trainer` if they exist in the checkpoint.'restore_callback_states_from_checkpointzWhether 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_determinism*   z:Random seed that will be set at the beginning of training.seedzTRandom seed to be used with data samplers. If not set, uses the same seed as `seed`.	data_seedz[Whether or not to use cpu. If set to False, we will use the available torch device/backend.use_cpuzeConfiguration for the internal Accelerate integration. Can be a path to a JSON config file or a dict.r   zMParallelism configuration for the training run. Requires Accelerate `1.10.1`.parallelism_configzHDrop the last incomplete batch if it is not divisible by the batch size.dataloader_drop_lastzxNumber of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in the main process.dataloader_num_workersz,Whether or not to pin memory for DataLoader.dataloader_pin_memoryzIf True, the data loader will not shut down the worker processes after a dataset has been consumed once. This allows to maintain the workers Dataset instances alive. Can potentially speed up training, but will increase RAM usage.dataloader_persistent_workerszNumber of batches loaded in advance by each worker. 2 means there will be a total of 2 * num_workers batches prefetched across all workers. dataloader_prefetch_factorzVWhether or not to automatically remove the columns unused by the model forward method.remove_unused_columnszLThe list of keys in your dictionary of inputs that correspond to the labels.label_namesrandomzMSampler for training: 'random' (default), 'sequential', or 'group_by_length'.)r  
sequentialgroup_by_lengthtrain_sampling_strategylengthzcColumn name for precomputed lengths. Ignored unless `train_sampling_strategy` is 'group_by_length'.length_column_nameztWhen 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_bufferszbThe backend to use for distributed training. Must be one of 'nccl', 'mpi', 'xccl', 'gloo', 'hccl'.)ncclgloompixcclhcclcnclmcclddp_backendi  zJThe timeout for `torch.distributed.init_process_group` calls (in seconds).ddp_timeoutzEnable PyTorch FSDP for distributed training. Options: 'full_shard', 'shard_grad_op', 'hybrid_shard', 'hybrid_shard_zero2', 'offload', 'auto_wrap'.fsdpzConfig to be used with FSDP (Pytorch Fully Sharded Data Parallel). The value is either a fsdp json config file (e.g., `fsdp_config.json`) or an already loaded json file as `dict`.r   zNEnable DeepSpeed integration. Value is a path to a JSON config file or a dict.r   r   zEnable one or more debug features. Options: 'underflow_overflow' (detect overflow in model I/O), 'tpu_metrics_debug' (print TPU metrics).debugzmWhether to skip adding memory profiler reports to metrics. Skipped by default because it slows down training.skip_memory_metricsz`Whether to run training. Not directly used by Trainer; intended for training/evaluation scripts.do_trainzbWhether to run evaluation. Not directly used by Trainer; intended for training/evaluation scripts.do_evalzsWhether to run predictions on the test set. Not directly used by Trainer; intended for training/evaluation scripts.
do_predictzPath to a folder with a valid checkpoint for your model. Not directly used by Trainer; intended for training/evaluation scripts.resume_from_checkpointzwThis argument is deprecated and will be removed in v5.2. Use `warmup_steps` instead as it also works with float values.warmup_ratiozqDeprecated and will be removed in v5.2. Set env var `TENSORBOARD_LOGGING_DIR` instead. TensorBoard log directory.logging_dirzWhen using torch.distributed.launch (Deprecated), it will pass `local_rank` in the script, so we need this for the parser. To get the local rank, prefer using the property `local_process_index`
local_rankc                 Z   | j                   d| _         t        j                  d       | j                  D ]^  }t	        | |      }t        |t              s |j                  d      s2t        j                  |      }t        |      }t        | ||       ` | j                   .t        j                  j                  | j                         | _         | j                  *t        j!                         t"        j$                  kD  | _        | j&                  &t        j)                  d       | j&                  | _        | j,                  t        j)                  d       t        | j.                  t0              r| j.                  rdnd| _        t3        | j4                        | _        t3        | j6                        | _        t9        | j:                        | _        t=        | j>                        | _        tA        | jB                        | _!        tE        | jF                        | _#        t        | jH                  t              r7| jH                  jK                         D cg c]  }tM        |       c}| _$        n| jH                  g | _$        | jN                  du r$| j4                  t2        jP                  k7  rd	| _'        | j4                  t2        jR                  k(  rw| jT                  | jT                  d
k(  r\| jV                  d
kD  r4t        j                  d| jV                          | jV                  | _*        ntY        d| j4                   d      | jZ                  s| jB                  t@        j\                  k(  r| j^                  d| _/        | j`                  -| j^                  !| j^                  jc                  d       | _0        | jd                  dk(  s| jd                  dgk(  rg | _2        n,t        | jd                  tf              s| jd                  g| _2        | ji                          t        jj                  jm                  dd      | _7        | jp                  rd| _7        n| jr                  rd| _7        | jt                  | jv                  | jx                  sd	| _<        | jx                  r1| jv                  %| jz                  st}               rd| _;        nd| _;        | jx                  rQt        d      sF| jv                  t        jj                  d<   | jt                  | jt                  t        jj                  d<   t               rt        | j                  t              s| j                  t               | _@        n~t        | j                  t              rt        d%i | j                  | _@        nIt        | j                  t              rt        d      t        j                  | j                        | _@        | j                  j                  rt        j                  d       t               r| j                   t               r| jx                  rvt               rW| j                  | jp                  r| jr                  rHt               rdnd}t        j                  d| d       t        d	       nt        j)                  d       t               rN| j                  B| j                  r!t               rt        d	       n tY        d      t               rt        d       | jz                  rd| _M        | j                         | _O        d | _P        | j                  rWd
d lRmS}  || j                        | _T        | j                  j                  |        d
d!lVmW}  || j                  "      | _P        y t        t        jj                  jm                  d#d$            rRd
d!lVmW}  |       | _P        | j                  j                  | jn                         | j                  j                          y y c c}w )&Ntrainer_outputzNo output directory specified, defaulting to 'trainer_output'. To change this behavior, specify --output_dir when creating TrainingArguments.{zSwarmup_ratio is deprecated and will be removed in v5.2. Use `warmup_steps` instead.zf`logging_dir` is deprecated and will be removed in v5.2. Please set `TENSORBOARD_LOGGING_DIR` instead.allr   FTr   z4using `logging_steps` to initialize `eval_steps` to zevaluation strategy z9 requires either non-zero --eval_steps or --logging_stepslossr   ACCELERATE_MIXED_PRECISIONr   r   hpu_backendinductorz1.2.0ACCELERATE_DYNAMO_BACKENDACCELERATE_DYNAMO_MODEzTried passing in a callable to `accelerator_config`, but this is not supported. Please pass in a fully constructed `AcceleratorConfig` object instead.zUsing `split_batches=True` in `accelerator_config` will override the `per_device_train_batch_size` Batches will be split across all processes equally when using `split_batches=True`.MUSACUDAzSetting TF32 in zL backends to speedup torch compile, you won't see any improvement otherwise.zbThe speedups for torchdynamo mostly come with GPU Ampere or higher and which is not detected here.zC--tf32 requires Ampere or a newer GPU arch, cuda>=11 and torch>=1.7)HfTrainerDeepSpeedConfig)DeepSpeedPlugin)hf_ds_configACCELERATE_USE_DEEPSPEEDr   r   )[r   loggerinfo_VALID_DICT_FIELDSgetattrr   r   
startswithjsonloadsr   setattrospath
expanduserr   getEffectiveLevelr#   WARNr/  r   r   r0  r   boolr   r   r   r   r   r   r  r   r   r4   r   r)  splitr   r,  NOSTEPSr   r   
ValueErrorr  REDUCE_ON_PLATEAUr  r  endswithr   list_validate_argsenvirongetmixed_precisionr   r   r   r   r   r  r   r   r   r-   r   typeNotImplementedErrorfrom_json_filesplit_batchesr   devicer    r   r   r&   r  _process_fsdp_argsfsdp_plugin_argsdeepspeed_pluginr   #transformers.integrations.deepspeedr>  hf_deepspeed_configtrainer_config_processaccelerate.utilsr?  r%   set_mixed_precisionset_deepspeed_weakref)selfvalid_fieldr   loaded_dicts
device_strr>  r?  s           r   __post_init__zTrainingArguments.__post_init__  sn   ??".DOKKa  22 	8K"45L,,1H1H1M"jj6/<k;7	8 ??& gg00ADO$ & 8 8 :W\\ ID(NNpq $ 1 1D'NNx d88$?:>:\:\bfD. .d.@.@A 01F1F G)$*<*<='(9(9:!.t/E/E!F#DJJ/
djj#&26**2B2B2DEQ+a.EDJZZDJ <<5 T%7%7;K;N;N%NDL !1!7!77T__=TX\XgXgklXl!!A%RSWSeSeRfgh"&"4"4 *4+=+=*> ?' '  ''4+A+A]EdEd+d((0)/D&!!)d.H.H.T)-)C)C)L)LV)T%TD">>V#t~~&'ADNDNND1"nn-DN 	  "zz~~.JDQ99#)D YY#)D  ##/43M3M3Ycgcucu!%D$"<"<"D<<$:$<-:*-7**73:>:T:T

67**6;?;R;RBJJ78 #$d557HI**2.?.AD+ 7 7>.?.Z$BYBY.ZD+ 7 7>-a 
 /@.N.NtOfOf.gD+&&44j KK D$6$6&(99$TYY$))+B+D&JKK*:, 7& &  %x DII$9yy*,%$%jkk*,& <<).D& !% 7 7 9 !%>>T (@'OD$$$;;DA8$3AYAY$ZD!rzz~~&@'JK8$3$5D!!!55d6J6JK!!779 LA Fs   `(c                 	   | j                   Bt        | j                   t              r| j                   dkD  st        d| j                    d      | j                  t
        j                  k(  r(| j                  dk(  rt        d| j                   d      | j                  t
        j                  k(  rc| j                  dkD  rT| j                  t        | j                        k7  rt        d| j                         t        | j                        | _        | j                  t
        j                  k(  rc| j                  dkD  rT| j                  t        | j                        k7  rt        d	| j                         t        | j                        | _	        | j                  t        j                  k(  rc| j                  dkD  rT| j                  t        | j                        k7  rt        d
| j                         t        | j                        | _        | j                  rg| j                  t        j                  k7  rI| j                  | j                  k7  r%t        d| j                   d| j                         | j                  t
        j                  k(  r| j                  | j                  z  dk7  r| j                  dk  s| j                  dk  r| j                  dk  r| j                  dk  s&t        d| j                   d| j                   d      d}| j                  |z  | j                  |z  z  dk7  rLt        d| j                   d| j                   d      t        d| j                   d| j                   d      t               rT| j                   s| j"                  r<| j$                  s0t'               s&t)               sd}t+               r|dz  }t        |      | j,                  r| j                   rt        d      | j.                  r| j"                  rt        d      | j0                  t2        j4                  k(  r=| j                  t
        j6                  k(  rt        d      t               st        d      | j8                  dk  rt        d      | j:                  dk(  r| j<                  t        d      yy)z5Validate argument combinations and value constraints.Nr   z@`torch_empty_cache_steps` must be an integer bigger than 0, got r   zlogging strategy z" requires non-zero --logging_stepsr   z5--logging_steps must be an integer if bigger than 1: z2--eval_steps must be an integer if bigger than 1: z2--save_steps must be an integer if bigger than 1: zh--load_best_model_at_end requires the save and eval strategy to match, but found
- Evaluation strategy: z
- Save strategy: z--load_best_model_at_end requires the saving steps to be a multiple of the evaluation steps, which cannot get guaranteed when mixing ratio and absolute steps for save_steps z and eval_steps i@B zg--load_best_model_at_end requires the saving steps to be a multiple of the evaluation steps, but found z, which is not a multiple of zm--load_best_model_at_end requires the saving steps to be a round multiple of the evaluation steps, but found z#, which is not a round multiple of zfYour setup doesn't support bf16/gpu. You need to assign use_cpu if you want to train the model on CPU.z& You need Ampere+ GPU with cuda>=11.0.z6At 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 bothz@lr_scheduler_type reduce_lr_on_plateau requires an eval strategyz<lr_scheduler_type reduce_lr_on_plateau requires torch>=0.2.0z*warmup_steps must be an integer or a floatz--dataloader_prefetch_factor can only be set when data is loaded in a different process, i.e. when --dataloader_num_workers > 0.)r   r   r   rS  r   r   rR  r   r   r   r   r   r   r  BESTr   r   r   r  r   r!   r   r   r   r   r   rT  rQ  r   r  r  )ri  LARGE_MULTIPLIERerror_messages      r   rW  z TrainingArguments._validate_args[  sY   ''3t;;SAdFbFbefFf VW[WsWsVttuv 
   $4$:$::t?Q?QUV?V01F1F0GGijkk  $4$:$::t?Q?QTU?U!!S););%<< #XY]YkYkXl!mnn!$T%7%7!8D!1!7!77DOOa<O#doo"66 #UVZVeVeUf!ghh!$//2DO!3!33!8K#doo"66 #UVZVeVeUf!ghh!$//2DO &&4+=+=ARAR+R!!T%7%77 !!%!3!3 44GHZHZG[]  !!%5%;%;;RVRaRa@aef@f??Q&$//A*= OOa/DOOa4G(v#//??PPQS  (1$*::tQa?abfgg(004/@@]^b^m^m]nnoq 
 %,,0OO+<<_`d`o`o_ppqs 
 yyD//||,G,IRhRj %MM.0%)QQ$]3399UVV4#6#6cdd!!]%D%DD!!%5%8%88 !cdd%' !_``q IJJ&&!+0O0O0[6  1\+r   c                 x   t        |       }|j                         D ci c]-  \  }}||j                  d      rd|j                          dn|/ }}}t	        |j                               D cg c]  \  }}| d| d }}}| j
                  j                   ddj                  |       dS c c}}w c c}}w )	N_token<>=z,
z(
r   ))r   r   rU  uppersorted	__class__r_   join)ri  self_as_dictkvattrs_as_strs        r   __str__zTrainingArguments.__str__  s    d|WcWiWiWkltqRSqzz(/CQqwwyk+Jll289K9K9M2NO$!Q1#QqcOO..))*#bggl.C-DAFF mOs   2B00B6returnc                 L    | j                   t        d| j                        z  }|S )z5
        The actual batch size for training.
        r   )r   maxn_gpu)ri  train_batch_sizes     r   r  z"TrainingArguments.train_batch_size  s&    
  ;;c!TZZ>PPr   c                 L    | j                   t        d| j                        z  }|S )z7
        The actual batch size for evaluation.
        r   )r   r  r  )ri  eval_batch_sizes     r   r  z!TrainingArguments.eval_batch_size  s%    
 99C4::<NNr   c                 .    t        | j                        S )zt
        The actual timeout for torch.distributed.init_process_group since it expects a timedelta variable.
        seconds)r   r'  ri  s    r   ddp_timeout_deltaz#TrainingArguments.ddp_timeout_delta  s    
 !1!122r   c                 h   t        | dg       t        j                  d       t               s$t	               st        dt         dt         d      ddd}t        | j                  t              r| j                  j                  d	d      |d	<   |d	   rwt        j                  i k(  rt        d
      t        | j                        | _        | j                   rO| j                  j"                  t$        j&                  k7  r(t)        d      t+        j,                  d       d | _        d| _        | j                  s)t1        t2        j4                  j7                  dd            rd|d<   | j8                  |d<   d| _        nt               rMd|d<   t;        j<                  dt?        j@                               }t:        jB                  jE                  |       nctG               rd|d<   nS| j                   rd|d<   tI        | jJ                        |d<   n(| j8                  |d<   tI        | jJ                        |d<   |j                  dd      r\|j                  d	d      sJ|j                  dd      }|rdt2        j4                  d<   t        d%i || _        |rt2        j4                  d= t               s| j                  j<                  }tM        jN                         rFtM        jP                         r2| jR                  tT        jV                  k7  rt        jY                  d       t[               r| j                  j<                  }d| _        |S tG               s
t               r	 S | j                  j"                  t$        j\                  k(  r(| j                  rt;        j<                  d      }|S t_               rt;        j<                  d      }|S ta               r6t;        j<                  d      }t:        jb                  jE                  |       |S te               r6t;        j<                  d      }t:        jf                  jE                  |       |S ti               r6t;        j<                  d       }t:        jj                  jE                  |       |S tm               r6t;        j<                  d!      }t:        jn                  jE                  |       |S tq               r6t;        j<                  d"      }t:        jr                  jE                  |       |S t;        j<                  t:        jB                  jO                         rd#nt2        j4                  j7                  d$d            }t:        jB                  ju                         | _        |jv                  dk(  rt:        jB                  jE                  |       S )&NtorchzPyTorch: setting up devicesz9Using the `Trainer` with `PyTorch` requires `accelerate>=zM`: Please run `pip install transformers[torch]` or `pip install 'accelerate>=z'`TF)enableduse_configured_stater  zPassing `'use_configured_state':True` to the AcceleratorConfig requires a pre-configured `AcceleratorState` or `PartialState` to be defined before calling `TrainingArguments`. )cpua  Tried to use an already configured `Accelerator` or `PartialState` that was not initialized for DeepSpeed, but also passed in a `deepspeed` configuration to the `TrainingArguments`. Please set `use_configured_state:False` instead or setup your `Accelerator` or `PartialState` properly.)reset_partial_stater   ACCELERATE_USE_CPUFalser  r2   r   r  cuda_use_sagemaker_dpuse_deepspeedr  timeoutr   rA  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.launchmpszxpu:0zmlu:0zmusa:0znpu:0zhpu:0zcuda:0ACCELERATE_TORCH_DEVICEr   )<r$   rB  rC  r   r   ImportErrorr   r   r   r-   popr+   _shared_staterS  r  distributed_stater   distributed_typer,   	DEEPSPEEDRuntimeErrorr*   _reset_state_n_gpur%   rJ  rX  rY  r&  r  r_  smpr1  r  
set_devicer   r   r'  distis_availableis_initializedparallel_modeParallelModeDISTRIBUTEDr   r!   rQ  r   r"   xpur   mlur   musar   npur   hpudevice_countr[  )ri  accelerator_state_kwargsr_  r  s       r   _setup_devicesz TrainingArguments._setup_devices  s   $	*12&(*,!OPfOg haaw`xxz| 
 @D]b3c d--/@A?C?V?V?Z?Z&@$%;< $$:;))R/ n  &2dll%CD"~~$"8"8"I"I_MfMf"f"s  ))dC%)D"<<9RZZ^^4H'%RS.2$U+262B2B$Y/DK$&27$Y/\\&#..*:;FJJ!!&)$&<@$%89^^8<$_52;DDTDT2U$Y/262B2B$Y/2;DDTDT2U$Y/ $''	59BZB^B^"EC
 588%PM9?

56%1%M4L%MD"JJ9:&(++22F4#6#6#8T=O=OS_SkSk=kNNi "#++22FDK@ ? %&*A*C< ; ##448J8JJ||e,6 5 ()e,2 1 ()g.		$$V,, + ()g.		$$V,& % )*h/

%%f-   ()g.		$$V,  ()g.		$$V,   %

 7 7 9Hrzz~~Ngin?o $jj557;;&(JJ))&1r   c                 4    t        | dg       | j                  S )z2
        The device used by this process.
        r  )r$   r  r  s    r   r_  zTrainingArguments.device7  s    
 	$	*"""r   c                 d    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$   hasattrr  r  )ri  _s     r   r  zTrainingArguments.n_gpu?  s/     	$	*tX&##A{{r   c                    t        | dg       t               rt        j                  S t	               rt        j
                  S t               rt        j                  S | j                  7| j                  j                  t        j                  k7  rt        j                  S | j                  dkD  rt        j                  S t        j                  S )a  
        The current mode used for parallelism if multiple GPUs/TPU cores are available. One of:

        - `ParallelMode.NOT_PARALLEL`: no parallelism (CPU or one GPU).
        - `ParallelMode.NOT_DISTRIBUTED`: several GPUs in one single process (uses `torch.nn.DataParallel`).
        - `ParallelMode.DISTRIBUTED`: several GPUs, each having its own process (uses
          `torch.nn.DistributedDataParallel`).
        - `ParallelMode.TPU`: several TPU cores.
        r  r   )r$   r!   r  TPUr   SAGEMAKER_MODEL_PARALLELr   SAGEMAKER_DATA_PARALLELr  r  r,   rQ  r  r  NOT_DISTRIBUTEDNOT_PARALLELr  s    r   r  zTrainingArguments.parallel_modeN  s     	$	*!####$&888$&777##/D4J4J4[4[_n_q_q4q+++ZZ!^///,,,r   c                    t        | dg       | j                  | j                  j                  S t               rLt        j
                  j                  j                  st	        j                         S t	        j                         S y)z;
        The number of processes used in parallel.
        r  r   )
r$   r  num_processesr   r  statecfgprescaled_batchdp_sizerdp_sizer  s    r   
world_sizezTrainingArguments.world_sizeg  ^    
 	$	*!!-))777$&(+		(E(E3;;=Y3<<>Yr   c                    t        | dg       | j                  | j                  j                  S t               rLt        j
                  j                  j                  st	        j                         S t	        j                         S y)z8
        The index of the current process used.
        r  r   )
r$   r  process_indexr   r  r  r  r  dp_rankrdp_rankr  s    r   r  zTrainingArguments.process_indexs  r  r   c                     t        | dg       | j                  | j                  j                  S t               rt	        j
                         S y)z6
        The index of the local process used.
        r  r   )r$   r  local_process_indexr   r  r1  r  s    r   r  z%TrainingArguments.local_process_index  sD    
 	$	*!!-))===$&>>##r   c                     | j                   r| j                  dk(  S t               rt        j                         dk(  S | j
                  dk(  S )zH
        Whether or not the current process should produce log.
        r   )r   r  r   r  rankr  r  s    r   
should_logzTrainingArguments.should_log  sE    
   ++q00&(xxzQ&))Q..r   c                     | j                   r| j                  dk(  S t               rt        j                         dk(  S | j
                  dk(  S )zp
        Whether or not the current process should write to disk, e.g., to save models and checkpoints.
        r   )r   r  r   r  r  r  r  s    r   should_savezTrainingArguments.should_save  sE    
 !!++q00&(xxzQ&))Q..r   c                     t         | j                     }t         | j                     }|dk(  rt        j                         n|}|dk(  rt        j                         n|}| j
                  r|S |S )a`  
        Returns the log level to be used depending on whether this process is the main process of node 0, main process
        of node non-0, or a non-main process.

        For the main process the log level defaults to the logging level set (`logging.WARNING` if you didn't do
        anything) unless overridden by `log_level` argument.

        For the replica processes the log level defaults to `logging.WARNING` unless overridden by `log_level_replica`
        argument.

        The choice between the main and replica process settings is made according to the return value of `should_log`.
        r)   )trainer_log_levelsr   r   r#   get_verbosityr  )ri  r   r   log_level_main_nodelog_level_replica_nodes        r   get_process_log_levelz'TrainingArguments.get_process_log_level  sg     't~~6	.t/E/EF9Bbg335i<MQS<S!6!6!8Yj&*oo"Q;QQr   c                      y)zR
        Can be subclassed and overridden for some specific integrations.
        Nr   r  s    r   place_model_on_devicez'TrainingArguments.place_model_on_device  s    
 r   c                 d    | j                   xs" t               xs t               xs
 t                S )zc
        Whether or not to use no_sync for the gradients when doing gradient accumulation.
        )r   r   r   r   r  s    r   !_no_sync_in_gradient_accumulationz3TrainingArguments._no_sync_in_gradient_accumulation  s0     NNw57w;R;TwXuXw
 	
r   c           
   #   Z  K   t               r4| j                  dkD  r$|rdnd}| j                  /|r| j                  j                  n| j                  j                  }n!t               rt        j                         dk(  }	 s[t        j                  | j                   d| d|        t               rt        j                  |       nt        j                          d |r]t        j                  | j                   d| d	| d
       t               rt        j                  |       yt        j                          yyd y# r]t        j                  | j                   d| d	| d
       t               rt        j                  |       w t        j                          w w xY ww)ax  
        A context manager for torch distributed environment where on needs to do something on the main process, while
        blocking replicas, and when it's finished releasing the replicas.

        One such use is for `datasets`'s `map` feature which to be efficient should be run once on the main process,
        which upon completion saves a cached version of results and which then automatically gets loaded by the
        replicas.

        Args:
            local (`bool`, *optional*, defaults to `True`):
                if `True` first means process of rank 0 of each node if `False` first means process of rank 0 of node
                rank 0 In multi-node environment with a shared filesystem you most likely will want to use
                `local=False` so that only the main process of the first node will do the processing. If however, the
                filesystem is not shared, then the main process of each node will need to do the processing, which is
                the default behavior.
            desc (`str`, *optional*, defaults to `"work"`):
                a work description to be used in debug logs

        r   zmain local processzmain processNr   z: waiting for the z to perform z: z completed z, releasing all replicas)r   r  r  is_local_main_processis_main_processr   r  r  rB  r)  r  r!   xm
rendezvousr  barrier)ri  localdescmain_process_descr  s        r   main_process_firstz$TrainingArguments.main_process_first  s_    * DOOa$78= 4>%%1DID**@@tOeOeOuOu   )*"%((*/'&LLD$6$6#77IJ[I\\himhn!op-/d+"LLD$6$6#7r:K9LKX\W]]u!vw-/d+ #  #LLD$6$6#7r:K9LKX\W]]u!vw-/d+ #s!   A>F+A!E "A%F+A!F((F+num_training_stepsc                     | j                   dk\  rt        | j                         }|S t        j                  || j                   z        }|S )z?
        Get number of steps used for a linear warmup.
        r   )r   r   mathceil)ri  r  r   s      r   get_warmup_stepsz"TrainingArguments.get_warmup_steps  sV    
 '+&7&71&<C!!" 	  CG))L^aeararLrBs 	 r   dc                     |j                  d      6t        |d   t              s#t        |d         j                  d      d   |d<   |j	                         D ]$  }t        |t
              s| j                  |       & y)a(  
        Checks whether the passed dictionary and its nested dicts have a *dtype* key and if it's not None,
        converts torch.dtype to a string of just the type. For example, `torch.float32` get converted into *"float32"*
        string, which can then be stored in the json format.
        dtypeNr   r   )rY  r   r   rP  valuesr   _dict_dtype_to_str)ri  r  r   s      r   r  z$TrainingArguments._dict_dtype_to_str  sm     55>%j7S.IQwZ..s3A6AgJXXZ 	/E%&''.	/r   c                 \   t        |       D ci c]0  }|j                  s|j                  t        | |j                        2 }}|j	                         D ]8  \  }}t        |t              r|j                  ||<   t        |t              r>t        |      dkD  r0t        |d   t              r|D cg c]  }|j                   c}||<   |j                  d      rd|j                          d||<   t               r#t        |t              r|j                         ||<   |dk(  rMt        |t              r=d|v r9|j!                  d      }|r&t        |t              s|j                         ||   d<   |dk(  s"|&|j#                         ||<   ; | j%                  |       |S c c}w c c}w )z
        Serializes this instance while replace `Enum` by their values (for JSON serialization support). It obfuscates
        the token values by removing their value.
        r   rt  ru  rv  model_init_kwargsquantization_configr  )r   initnamerE  r   r   r   r   rV  lenrU  ry  r   r-   to_dictr   rY  to_jsonr  )ri  r   r  r~  r  xr  s          r   r  zTrainingArguments.to_dict  sr    AGt[uPUPZPZUZZuzz22[[GGI 	#DAq!T"ww!!T"s1vzj1t6L)*+A+!zz(#1779+Q'!&(Z;L-Myy{!''Jq$,?DY]^D^&'ee,A&B#&z:Mt/T2E2M2M2OAaD./((Q]yy{!!	#$ 	"- \ ,s   F$#F$0F)c                 L    t        j                  | j                         d      S )z<
        Serializes this instance to a JSON string.
           )indent)rG  dumpsr  r  s    r   to_json_stringz TrainingArguments.to_json_string2  s     zz$,,.33r   c                 ^   | j                         }i || j                  | j                  d}t        t        t
        t        g}t               r|j                  t        j                         |j                         D ci c]   \  }}|t        |      |v r|n
t        |      " c}}S c c}}w )zK
        Sanitized serialization to use with TensorBoard's hparams
        )r  r  )r  r  r  rO  r   r   r   r   appendr  Tensorr   r[  )ri  r  valid_typesr~  r  s        r   to_sanitized_dictz#TrainingArguments.to_sanitized_dict8  s     LLNeqed&;&;PTPdPdeS%-u||,GHwwyQtq!Q;.1CF:QQQs    %B)
batch_size
num_epochsc	                     d| _         || _        || _        || _        || _        || _        || _        || _        || _        | S )a	  
        A method that regroups all basic arguments linked to the training.

        <Tip>

        Calling this method will automatically set `self.do_train` to `True`.

        </Tip>

        Args:
            learning_rate (`float`, *optional*, defaults to 5e-5):
                The initial learning rate for the optimizer.
            batch_size (`int` *optional*, defaults to 8):
                The batch size per device (GPU/TPU core/CPU...) used for training.
            weight_decay (`float`, *optional*, defaults to 0):
                The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in the
                optimizer.
            num_train_epochs(`float`, *optional*, defaults to 3.0):
                Total number of training epochs to perform (if not an integer, will perform the decimal part percents
                of the last epoch before stopping training).
            max_steps (`int`, *optional*, defaults to -1):
                If set to a positive number, the total number of training steps to perform. Overrides `num_train_epochs`.
                For a finite dataset, training is reiterated through the dataset (if all data is exhausted) until
                `max_steps` is reached.
            gradient_accumulation_steps (`int`, *optional*, defaults to 1):
                Number of updates steps to accumulate the gradients for, before performing a backward/update pass.

                <Tip warning={true}>

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

                </Tip>

            seed (`int`, *optional*, defaults to 42):
                Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use
                the [`~Trainer.model_init`] function to instantiate the model if it has some randomly initialized
                parameters.
            gradient_checkpointing (`bool`, *optional*, defaults to `False`):
                If True, use gradient checkpointing to save memory at the expense of slower backward pass.

        Example:

        ```py
        >>> from transformers import TrainingArguments

        >>> args = TrainingArguments("working_dir")
        >>> args = args.set_training(learning_rate=1e-4, batch_size=32)
        >>> args.learning_rate
        1e-4
        ```
        T)	r+  r   r   r   r   r   r   r  r   )	ri  r   r  r   r  r   r   r  r   s	            r   set_trainingzTrainingArguments.set_trainingF  sO    @ *+5(( *"+F(	&<#r   strategyaccumulation_stepsdelay	loss_onlyc                 
   t        |      | _        | j                  t         j                  k(  r|dk(  rt        d      | j                  t         j                  k7  | _        || _        || _        || _        || _	        || _
        | S )a  
        A method that regroups all arguments linked to evaluation.

        Args:
            strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"no"`):
                The evaluation strategy to adopt during training. Possible values are:

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

                Setting a `strategy` different from `"no"` will set `self.do_eval` to `True`.
            steps (`int`, *optional*, defaults to 500):
                Number of update steps between two evaluations if `strategy="steps"`.
            batch_size (`int` *optional*, defaults to 8):
                The batch size per device (GPU/TPU core/CPU...) used for evaluation.
            accumulation_steps (`int`, *optional*):
                Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU.
                If left unset, the whole predictions are accumulated on GPU/TPU before being moved to the CPU (faster
                but requires more memory).
            delay (`float`, *optional*):
                Number of epochs or steps to wait for before the first evaluation can be performed, depending on the
                eval_strategy.
            loss_only (`bool`, *optional*, defaults to `False`):
                Ignores all outputs except the loss.

        Example:

        ```py
        >>> from transformers import TrainingArguments

        >>> args = TrainingArguments("working_dir")
        >>> args = args.set_evaluate(strategy="steps", steps=100)
        >>> args.eval_steps
        100
        ```
        r   DSetting `strategy` as 'steps' requires a positive value for `steps`.)r   r   rR  rS  rQ  r,  r   r   r   r   r   )ri  r  r   r  r	  r
  r  s          r   set_evaluatezTrainingArguments.set_evaluate  s}    \ .h7!1!7!77EQJcdd))-=-@-@@*4''9$$-!r   c                 0    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.

        Example:

        ```py
        >>> from transformers import TrainingArguments

        >>> args = TrainingArguments("working_dir")
        >>> args = args.set_testing(batch_size=32)
        >>> args.per_device_eval_batch_size
        32
        ```
        T)r-  r   r   )ri  r  r  s      r   set_testingzTrainingArguments.set_testing  s     > *4'$-!r   total_limiton_each_nodec                     t        |      | _        | j                  t         j                  k(  r|dk(  rt        d      || _        || _        || _        | S )a  
        A method that regroups all arguments linked to checkpoint saving.

        Args:
            strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`):
                The checkpoint save strategy to adopt during training. Possible values are:

                    - `"no"`: No save is done during training.
                    - `"epoch"`: Save is done at the end of each epoch.
                    - `"steps"`: Save is done every `save_steps`.

            steps (`int`, *optional*, defaults to 500):
                Number of updates steps before two checkpoint saves if `strategy="steps"`.
            total_limit (`int`, *optional*):
                If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in
                `output_dir`.
            on_each_node (`bool`, *optional*, defaults to `False`):
                When doing multi-node distributed training, whether to save models and checkpoints on each node, or
                only on the main one.

                This should not be activated when the different nodes use the same storage as the files will be saved
                with the same names for each node.

        Example:

        ```py
        >>> from transformers import TrainingArguments

        >>> args = TrainingArguments("working_dir")
        >>> args = args.set_save(strategy="steps", steps=100)
        >>> args.save_steps
        100
        ```
        r   r  )r   r   rR  rS  r   r   r   )ri  r  r   r  r  s        r   set_savezTrainingArguments.set_save  sT    R *(3!3!33
cdd +!-r   level
first_stepnan_inf_filterreplica_levelc	                     t        |      | _        | j                  t         j                  k(  r|dk(  rt        d      || _        || _        || _        || _        || _        || _	        || _
        | S )a
  
        A method that regroups all arguments linked to logging.

        Args:
            strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`):
                The logging strategy to adopt during training. Possible values are:

                    - `"no"`: No logging is done during training.
                    - `"epoch"`: Logging is done at the end of each epoch.
                    - `"steps"`: Logging is done every `logging_steps`.

            steps (`int`, *optional*, defaults to 500):
                Number of update steps between two logs if `strategy="steps"`.
            level (`str`, *optional*, defaults to `"passive"`):
                Logger log level to use on the main process. Possible choices are the log levels as strings: `"debug"`,
                `"info"`, `"warning"`, `"error"` and `"critical"`, plus a `"passive"` level which doesn't set anything
                and lets the application set the level.
            report_to (`str` or `list[str]`, *optional*, defaults to `"none"`):
                The list of integrations to report the results and logs to. Supported platforms are `"azure_ml"`,
                `"clearml"`, `"codecarbon"`, `"comet_ml"`, `"dagshub"`, `"dvclive"`, `"flyte"`, `"mlflow"`,
                `"swanlab"`, `"tensorboard"`, `"trackio"` 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   rR  rS  r   r   r   r   r   r   r   )	ri  r  r   r   r  r  r  r  r  s	            r   set_loggingzTrainingArguments.set_logging	  st    ~ !1 :  $4$:$::uzcdd""",&4# ,!.r   model_idtokenprivate_repoalways_pushrevisionc                 z    d| _         || _        t        |      | _        || _        || _        || _        || _        | S )am  
        A method that regroups all arguments linked to synchronizing checkpoints with the Hub.

        <Tip>

        Calling this method will set `self.push_to_hub` to `True`, which means the `output_dir` will begin a git
        directory synced with the repo (determined by `model_id`) and the content will be pushed each time a save is
        triggered (depending on your `self.save_strategy`). Calling [`~Trainer.save_model`] will also trigger a push.

        </Tip>

        Args:
            model_id (`str`):
                The name of the repository to keep in sync with the local *output_dir*. It can be a simple model ID in
                which case the model will be pushed in your namespace. Otherwise it should be the whole repository
                name, for instance `"user_name/model"`, which allows you to push to an organization you are a member of
                with `"organization_name/model"`.
            strategy (`str` or [`~trainer_utils.HubStrategy`], *optional*, defaults to `"every_save"`):
                Defines the scope of what is pushed to the Hub and when. Possible values are:

                - `"end"`: push the model, its configuration, the processing_class e.g. tokenizer (if passed along to the [`Trainer`]) and a
                draft of a model card when the [`~Trainer.save_model`] method is called.
                - `"every_save"`: push the model, its configuration, the processing_class e.g. tokenizer (if passed along to the [`Trainer`])
                  and
                a draft of a model card each time there is a model save. The pushes are asynchronous to not block
                training, and in case the save are very frequent, a new push is only attempted if the previous one is
                finished. A last push is made with the final model at the end of training.
                - `"checkpoint"`: like `"every_save"` but the latest checkpoint is also pushed in a subfolder named
                last-checkpoint, allowing you to resume training easily with
                `trainer.train(resume_from_checkpoint="last-checkpoint")`.
                - `"all_checkpoints"`: like `"checkpoint"` but all checkpoints are pushed like they appear in the
                  output
                folder (so you will get one checkpoint folder per folder in your final repository)

            token (`str`, *optional*):
                The token to use to push the model to the Hub. Will default to the token in the cache folder obtained
                with `hf auth login`.
            private_repo (`bool`, *optional*, defaults to `False`):
                Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
            always_push (`bool`, *optional*, defaults to `False`):
                Unless this is `True`, the `Trainer` will skip pushing a checkpoint when the previous push is not
                finished.
            revision (`str`, *optional*):
                The revision to use when pushing to the Hub. Can be a branch name, a tag, or a commit hash.

        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  )ri  r  r  r  r  r  r  s          r   set_push_to_hubz!TrainingArguments.set_push_to_hubj	  sF    B  $'1 ,*$r   r  beta1beta2epsilonargsc                 z    t        |      | _        || _        || _        || _        || _        || _        || _        | S )a  
        A method that regroups all arguments linked to the optimizer and its hyperparameters.

        Args:
            name (`str` or [`training_args.OptimizerNames`], *optional*, defaults to `"adamw_torch"`):
                The optimizer to use: `"adamw_torch"`, `"adamw_torch_fused"`, `"adamw_apex_fused"`,
                `"adamw_anyprecision"` or `"adafactor"`.
            learning_rate (`float`, *optional*, defaults to 5e-5):
                The initial learning rate.
            weight_decay (`float`, *optional*, defaults to 0):
                The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights.
            beta1 (`float`, *optional*, defaults to 0.9):
                The beta1 hyperparameter for the adam optimizer or its variants.
            beta2 (`float`, *optional*, defaults to 0.999):
                The beta2 hyperparameter for the adam optimizer or its variants.
            epsilon (`float`, *optional*, defaults to 1e-8):
                The epsilon hyperparameter for the adam optimizer or its variants.
            args (`str`, *optional*):
                Optional arguments that are supplied to AnyPrecisionAdamW (only useful when
                `optim="adamw_anyprecision"`).

        Example:

        ```py
        >>> from transformers import TrainingArguments

        >>> args = TrainingArguments("working_dir")
        >>> args = args.set_optimizer(name="adamw_torch", beta1=0.8)
        >>> args.optim
        'adamw_torch'
        ```
        )r4   r   r   r   r   r   r   r   )ri  r  r   r   r"  r#  r$  r%  s           r   set_optimizerzTrainingArguments.set_optimizer	  sC    T $D)
*(#r   c                     |t         j                  d       |}t        |      | _        || _        || _        || _        | S )a  
        A method that regroups all arguments linked to the learning rate scheduler and its hyperparameters.

        Args:
            name (`str` or [`SchedulerType`], *optional*, defaults to `"linear"`):
                The scheduler type to use. See the documentation of [`SchedulerType`] for all possible values.
            num_epochs(`float`, *optional*, defaults to 3.0):
                Total number of training epochs to perform (if not an integer, will perform the decimal part percents
                of the last epoch before stopping training).
            max_steps (`int`, *optional*, defaults to -1):
                If set to a positive number, the total number of training steps to perform. Overrides `num_train_epochs`.
                For a finite dataset, training is reiterated through the dataset (if all data is exhausted) until
                `max_steps` is reached.
            warmup_steps (`float`, *optional*, defaults to 0):
                Number of steps used for a linear warmup from 0 to `learning_rate`.  Should be an integer or a float in range `[0,1)`.
                If smaller than 1, will be interpreted as ratio of steps used for a linear warmup from 0 to `learning_rate`.

        Example:

        ```py
        >>> from transformers import TrainingArguments

        >>> args = TrainingArguments("working_dir")
        >>> args = args.set_lr_scheduler(name="cosine", warmup_steps=0.05)
        >>> args.warmup_steps
        0.05
        ```
        zTwarmup_ratio is deprecated and will be removed in v5.2 . Use `warmup_steps` instead.)rB  r   r   r   r   r   r   )ri  r  r  r   r   r/  s         r   set_lr_schedulerz"TrainingArguments.set_lr_scheduler	  sF    H #NNqr'L!.t!4 *"(r   r  r  	drop_lastnum_workers
pin_memorypersistent_workersprefetch_factorsampler_seedc                     || _         || _        || _        || _        || _        || _        || _        || _        |	| _        |
| _	        | S )aS
  
        A method that regroups all arguments linked to the dataloaders creation.

        Args:
            drop_last (`bool`, *optional*, defaults to `False`):
                Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch
                size) or not.
            num_workers (`int`, *optional*, defaults to 0):
                Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in
                the main process.
            pin_memory (`bool`, *optional*, defaults to `True`):
                Whether you want to pin memory in data loaders or not. Will default to `True`.
            persistent_workers (`bool`, *optional*, defaults to `False`):
                If True, the data loader will not shut down the worker processes after a dataset has been consumed
                once. This allows to maintain the workers Dataset instances alive. Can potentially speed up training,
                but will increase RAM usage. Will default to `False`.
            prefetch_factor (`int`, *optional*):
                Number of batches loaded in advance by each worker.
                2 means there will be a total of 2 * num_workers batches prefetched across all workers.
            auto_find_batch_size (`bool`, *optional*, defaults to `False`)
                Whether to find a batch size that will fit into memory automatically through exponential decay,
                avoiding CUDA Out-of-Memory errors. Requires accelerate to be installed (`pip install accelerate`)
            ignore_data_skip (`bool`, *optional*, defaults to `False`):
                When resuming training, whether or not to skip the epochs and batches to get the data loading at the
                same stage as in the previous training. If set to `True`, the training will begin faster (as that
                skipping step can take a long time) but will not yield the same results as the interrupted training
                would have.
            sampler_seed (`int`, *optional*):
                Random seed to be used with data samplers. If not set, random generators for data sampling will use the
                same seed as `self.seed`. This can be used to ensure reproducibility of data sampling, independent of
                the model seed.

        Example:

        ```py
        >>> from transformers import TrainingArguments

        >>> args = TrainingArguments("working_dir")
        >>> args = args.set_dataloader(train_batch_size=16, eval_batch_size=64)
        >>> args.per_device_train_batch_size
        16
        ```
        )
r   r   r  r  r  r  r  r   r  r  )ri  r  r  r*  r+  r,  r-  r.  r   r  r/  s              r   set_dataloaderz TrainingArguments.set_dataloader
  sY    p ,<(*9'$-!&1#%/"-?**9'$8! 0%r   c                    | j                   sg | _         nu| j                   du rt        j                  g| _         nPt        | j                   t              r6| j                   j                         D cg c]  }t        |       c}| _         | j                   t        j                  gk(  rt        d      t        j                  | j                   v r't        j                  | j                   v rt        d      | j                  rMt        j                  | j                   v st        j                  | j                   v rt        j                  d       | j                  i | _        t        | j                  t              rgt        | j                         dk(  rt        j                   d       t#        | j                  d      5 }t%        j&                  |      | _        d d d        | j                  t        | j                  t(              rgt+        | j                  j-                               D ]A  }|j/                  d	      s| j                  j1                  |      }|| j                  |d
d  <   C | j                  j3                  dd      | j                  d<   t        | j                  j3                  dd       t              r| j                  d   g| j                  d<   t        | j                         dk(  r'| j                  d   dkD  rt        j                   d       t        | j                         dk(  r1| j                  j3                  dd       t        j                   d       t        | j                         dkD  r9| j                  d   dkD  r'| j                  j3                  dd       t        d      | j                  j3                  dd      | j                  d<   | j                  j3                  dd      | j                  d<   | j                  j3                  dd      | j                  d<   | j                  d   rt        | j                         dkD  r| j                  j3                  di       j5                         | _        d| j6                  v r*t9        t:        | j6                  d         | j6                  d<   d| j6                  v ret9        t:        | j6                  d         | j6                  d<   n:t        j                   d       n$| j                  d   rt        j                   d       d }t        | j                         dkD  r| j                  d   sddlm}m } i }| j                   D ]  }|jC                         |v r||d<   |t        j                  k(  rd|d<   4|t        jD                  k(  sH|d   |d<   | j                  d   dkD  r| j                  d   |d<   |d   |d<   }| j                  j3                  dd       djG                  | j                  d         |d<    tI        | j                  j3                  d d            }	|	|d!<   | j                  j3                  d"d#      }
|	d$k(  r@tK        t	        | j                  j3                  d%d&            jM                               |d%<   ntK        t	        | j                  j3                  d'd&            jM                               |d'<   |
jC                         |d"<   t	        | j                  j3                  d%d(            jM                         |d%<   tK        t	        | j                  j3                  d)d*            jM                               |d)<   t	        | j                  j3                  d+d*            jM                         }t	        | j                  j3                  d,d&            jM                         }|d&k(  r|d*k(  rt        d-      tK        |      |d,<   |tN        jP                  d.<   tK        |      |d+<   |S c c}w # 1 sw Y   ]xY w)/NTz`--fsdp offload` can't work on its own. It needs to be added to `--fsdp full_shard` or `--fsdp shard_grad_op`. For example, `--fsdp "full_shard offload"`.zB`--fsdp full_shard` is not compatible with `--fsdp shard_grad_op`.a  When using FSDP full shard, instead of using `gradient_checkpointing` in TrainingArguments, please use `activation_checkpointing` in `fsdp_config`. The former introduces a redundant AllGather operation in backward pass. Reference: https://github.com/huggingface/transformers/issues/30404r   z:`--fsdp_config` is useful only when `--fsdp` is specified.zutf-8)encodingfsdp_   min_num_paramstransformer_layer_cls_to_wrapz;`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.r1   Fxla_fsdp_v2xla_fsdp_grad_ckptxla_fsdp_settingscompute_dtypebuffer_dtypez5XLA FSDP can be used only when `--fsdp` is specified.zB`--xla_fsdp_grad_ckpt` is useful only when `--xla` is set to true.)FSDP_AUTO_WRAP_POLICYFSDP_SHARDING_STRATEGYsharding_strategycpu_offloadauto_wrap_policyr   ,transformer_cls_names_to_wrapversionfsdp_versionbackward_prefetchNO_PREFETCHr  reshard_after_forwardr   forward_prefetch
FULL_SHARDuse_orig_paramsr   sync_module_statescpu_ram_efficient_loadingzP`sync_module_states` must be `"True"` if `cpu_ram_efficient_loading` is `"True"`FSDP_CPU_RAM_EFFICIENT_LOADING))r(  r   rJ  r   r   rP  OFFLOADrS  SHARD_GRAD_OPr   HYBRID_SHARDrB  r   r   r  warningswarnopenrG  loadr   rV  keysrF  r  rY  copyxla_fsdp_configrE  r  accelerate.utils.constantsr=  r>  ry  	AUTO_WRAPr|  r   str_to_boolr   rJ  rX  )ri  rl  fr~  r  ra  r=  r>  fsdp_optionrE  prefetch_policyrL  rM  s                r   r`  z$TrainingArguments._process_fsdp_argsY
  sF   yyDIYY$#../DI		3'04		0AB1ABDI99++,,V  ""dii/J4L4LPTPYPY4Yabb&&!!TYY.*2I2ITYY2VNNs #!Dd&&,499~"Z[d&&9 0Q#'99Q< 0 'Jt7G7G,N$**//12 0<<(((,,Q/A./D$$QqrU+0
 .2-=-=-A-ABRTU-V)* d&&**+JDQSVWAEAQAQRqAr@sD<=tyy>Q4#3#34D#E#IMMWXtyy>Q4#3#3#7#78WY]#^#jMMfg 		NQ  !12Q6  $$%DdKWkll"&"2"2"6"6ue"D*.*:*:*>*>}e*T'151A1A1E1EFZ\a1b-.E"499~!'+'7'7';';<OQS'T'Y'Y'[$"d&:&::<CE4K_K_`oKp<qD((9!T%9%99;B5$J^J^_mJn;oD((8UV 45bc  tyy>Ad&6&6u&=
  "#yy $$&*@@<G$%89 J$6$666:$]3 J$8$88;PQR;S$%78''(89A==A=M=MN^=_()9:?TUV?W();<))--.MtT`LOHH ,,-LMM()HI t//33IqABL/;^,"..223FVOq <G((,,-DgNOUUW= !89 8C((,,-?IJPPR8 !34 9H8M8M8O !45<?$$(()@,O=%' !!89 7B((,,->GHNNP7 !23 "%T%5%5%9%9:NPV%W!X!^!^!`(+D,<,<,@,@A\^e,f(g(m(m(o%!W,1Jf1T !stt =HHa<b89;TBJJ785@AS5T12y C20 0s   0`1 `66a )r  ztorch.device)Twork)r   r   r      r)   r   r
  F)r   r   r   NNF)r   F)r   r   NF)r   r   r   r(   FFFr(   )r   NNFN)r5   r   r   r   r   r   N)r   r   r)   r   N)
r   r   Fr   TFNFFN)r_   r`   ra   rb   rD  r   r   r   __annotations__r   r   r   r   r   r   r   r   r   r   r   default_optimr   pytorch_utilsr   r   r4   r   r   r   r   r   r   rV  r   r   rO  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  rV  r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r  r  r  r  r  r  r  r	  r  r  r  r   r  r.   r  r  r  r  r  r  r  r  r  r  r  r  r&  r'  r(  r   r   r   r)  r   r*  r+  r,  r-  r.  r/  r0  r1  rn  rW  r  __repr__propertyr  r  r   r  r	   r  r_  r  r  r  r  r  r  r  r  r  r  
contextlibcontextmanagerr  r  r  r  r  r  r  r  r  r  r  r!  r'  r)  r1  r`  r   r   r   r   r      s   yz #mnJd
  (-Q&JsAt'uu#C6Cp:qrer
Is  !Ao8pqM5q-2qr.}s*  .3|
.d*     b
L%  "ME-/M"']^#E>C  #p
Jd
     D
L%  t
J  u
J   (ijL%  49pq4$*tCy0  (-s
(  +0 G
+!4  !v'jkM5  %*v'st%E 
   H
D$  
D$  !q
ND  !q
ND  y
D$+  $)  E
$D  BGZ[B!4S>C#7$#>   )i jM4  ).c
)3:  &+l
&d
  #q
d  38  T
3c4i4/    c
It  ).  d
)  +0  |
+S4Z  "'  Z
"$  05kl0&,  ![
M5   %)Y Z   #
d  $)u
$D  16l
1!3:  ~)..0
Is  #o)..0
s  !&jk!L$+  ).  X
)ItczDI%  !
HcDj  hiGS  $) 3
	$cDj 	 -2TU-M#c)   %N
 J  "
J  ',V%cd'  "'ij"$   ~
M4  $)  r
$D  $)}
$D  +0  V
+S4Z  &+qr&c   %WX   "}
OT  ).u
)M<#%  [
J  $(
t  $)  s
$cDj  #(  x
#4  )u vK  "p
IsTz  %* 
%dTk   %(qr L#*  ',z
'L+#  "pqOT   %q
 L#*  $)pq$D  ).p
)3:  &+op&td{  #  p
d  5:  n
5+T  #s
d  bF4p+qrD#r!pqIsTz  q
GT  -2{
-s
T)  49ij4)D0  "')s t"$  #((
#C  #((VW#4  +0  |
+!4  .3k
.d
  #(rs#4  %*(vw%KcT!  $)cB
$S  $y
  /4-
/t  %*-
%sTz  */-
*4$;  $xN
Kt  fgK  +0  j
+D$z
S
 4
'  05m
0Kc3h#%,  $)jk$ItczD   &+  `
&E3k""  !&  D
!  v
Hd  x
GT    J
J  */  W
*C$J  "'  N
"L%$,  $  H
Kt    X
J s:jPdG H #        39 3 3 f fP # #   - -0 	 	 	 	 
 
 
/ 
/ 
/ 
/R, td{   
 
 0 0d3 
/DcN 
/t 
/<4R4S> R   $+,',II I 	I
 I I &)I I !%IZ ,0)-"7((7 7 	7
  $J7 t|7 7v "" "L ,3"&"/((/ / 4Z	/
 /f ,3%+ $"&I((I I c?	I
 I I I I I\ '3 $(!#HH #H Tz	H
 TkH H *HX &3#1N"1 1 	1
 1 1 1 Dj1j %-%),M!, , 	,
 , dl,` !" #(&*%*!&#'BB B 	B
 B B !B tB #B B DjBHB r   r   c                   $    e Zd ZdZdZdZdZdZdZy)r  not_parallelnot_distributeddistributedsagemaker_model_parallelsagemaker_data_paralleltpuN)	r_   r`   ra   r  r  r  r  r  r  r   r   r   r  r  
  s"    !L'OK97
Cr   r  to_boolr  c                 f    | j                         } | dv r|sdS dS | dv r|sdS dS t        d|        )z
    Converts a string representation of truth to `True` (1) or `False` (0).

    True values are `y`, `yes`, `t`, `true`, `on`, and `1`; False value are `n`, `no`, `f`, `false`, `off`, and `0`;
    )yyestr   on1r   T)nr   r\  r   off0r   Fzinvalid truth value )r   rS  )r   ro  s     r   r[  r[  
  sN     KKME44q)T)	7	7q*U*/w788r   r   )T)drf  rG  r  rJ  rR  dataclassesr   r   r   r   datetimer   enumr   	functoolsr	   typingr
   debug_utilsr   trainer_utilsr   r   r   r   r   utilsr   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   utils.genericr%   utils.import_utilsr&   r'   
get_loggerr_   rB  get_log_levels_dictrW  
log_levelsr   r  r  torch.distributedrk  r  accelerate.stater*   r+   rf  r,   trainer_pt_utilsr-   accelerate.parallelism_configr.   torch_xla.core.xla_modelcore	xla_modelr  rX  rY  rC  r   !torch_xla.distributed.xla_backendxla_backendxbnr   groupWORLDProcessGroupXlainit_process_groupAssertionError!smdistributed.modelparallel.torchmodelparallelr  r  r4   r   r   r  rO  r   r[  r   r   r   <module>r     s      	  8 8   %  $      * % H 
		H	%(W((*//1
3J33 $?038$?)) e4 
zz~~+,&(KK'
 NN@
 <;djj..0C0CD'''6!$**"2"2C4G4GH()rss 33CHHJ."\ ."bD $ i(  i(  i( XQ4 9 9d
 9r   