
    eThr                       S r SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSK	r	SSK
r
SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKJr  SSKJr  SSKJr  SSKJrJrJrJrJr  SSKJr  SSKJ r!  SSK"r#SSK$r$SSK%J&r'  SS	K(J)r)J*r*J+r+  SS
K,J-r-  SSK$J.r.  SSK/J0r0J1r1J2r2J3r3J4r4  SSK5J6r6  SSK7J8r8  SSK9J:r:J;r;J<r<  SSK=J>r>J?r?  SSK@JArA  SSKBJCrC  SSKDJErEJFrF  SSKGJHrH  SSKIJJrJJKrKJLrL  SSKMJNrN  SSKOJPrP  SSKQJRrRJSrSJTrT  SSKUJVrVJWrW  SSKXJYrYJZrZ  SSK[J\r\  SSK]J^r^J_r_  SSK`Jara  SSKbJcrcJdrdJereJfrfJgrgJhrhJiriJjrj  SSKkJlrlJmrmJnrnJoroJprpJqrqJrrrJsrsJtrtJuruJvrvJwrwJxrxJyryJzrzJ{r{J|r|J}r}J~r~Jr  SS KJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJr  SS!KJrJrJr  SS"K JrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJr  SS#KJr  SS$KJr  SS%KJr  \d/r\gr\" 5       (       a  SS&KJr  \r\" 5       (       a  SS'KJr  \" 5       (       a  SSKr\" 5       (       aV  SSKJs  Jr  SSKJs  Jr  SSKJr  SSKJ6r  \-GR                  " \5      \-GR                  " \5      :  r\(       a	  SSKJ&s  Jr  OS(r\" 5       (       aC  SSKJs  J$r  SSKJ6r  \-GR                  " \5      \-GR                  " S)5      :  rSS*KkJrJrJrJr  OS(r\" 5       (       a  SSKr\" 5       (       a  SS+KJr  \" 5       (       a  SS,KJrJr  SSKJ6r  SS-KJr  SS.KJrJrJrJrJrJrJr  \3/Gr \-GR                  " \5      \-GR                  " S/5      :  a  SS0KGJGr  \-GR                  " \5      \-GR                  " S15      :  a  SS2GKGJGr  G\ G\/-  Gr \L" 5       (       a  SS3KGJGr  \" S45      (       a  SS5KGJGr  S6 GrS7 GrS8 Gr\(       a  SSGK	Gr	\" 5       (       a  SSKr\GR                  " G\5      GrS9GrS:GrS;GrS<GrS=GrS>GrS?Gr\" S@SA9 " SB SC5      5       Grg)Duc   
The Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task.
    N)Mappingpartial)Path)TYPE_CHECKINGAnyCallableOptionalUnion   )#get_reporting_integration_callbacks)	ModelCardcreate_repoupload_folder)version)nn)
DataLoaderDatasetIterableDatasetRandomSamplerSequentialSampler)__version__)PretrainedConfig)DataCollatorDataCollatorWithPaddingdefault_data_collator)DebugOptionDebugUnderflowOverflow)SequenceFeatureExtractor)FeatureExtractionMixin)"ALL_HYPERPARAMETER_SEARCH_BACKENDSdefault_hp_search_backend)BaseImageProcessor)deepspeed_initdeepspeed_load_checkpointis_deepspeed_available)tpu_spmd_dataloader)TrainingSummary)PreTrainedModelload_sharded_checkpointunwrap_model)!MODEL_FOR_CAUSAL_LM_MAPPING_NAMESMODEL_MAPPING_NAMES)	Adafactorget_scheduler)ProcessorMixin)ALL_LAYERNORM_LAYERS"is_torch_greater_or_equal_than_2_3)PreTrainedTokenizerBase)CallbackHandlerDefaultFlowCallbackExportableStatePrinterCallbackProgressCallbackTrainerCallbackTrainerControlTrainerState)DistributedTensorGathererEvalLoopContainerIterableDatasetShardLabelSmootherLayerWiseDummyOptimizerLengthGroupedSamplerSequentialDistributedSamplerdistributed_broadcast_scalarsdistributed_concatfind_batch_sizeget_model_param_countget_module_class_from_nameget_parameter_namesnested_concatnested_detachnested_numpifynested_xla_mesh_reducereissue_pt_warningsremove_dummy_checkpointset_rng_state_for_device)PREFIX_CHECKPOINT_DIRBestRunEvalLoopOutputEvalPredictionHPSearchBackendHubStrategyPredictionOutputRemoveColumnsCollatorSaveStrategyTrainerMemoryTrackerTrainOutputcheck_target_module_existsdefault_compute_objectivedenumpify_detensorizeenable_full_determinismfind_executable_batch_sizeget_last_checkpoint
has_lengthneftune_post_forward_hooknumber_of_argumentsseed_workerset_seedspeed_metrics)OptimizerNamesParallelModeTrainingArguments))ADAPTER_CONFIG_NAMEADAPTER_SAFE_WEIGHTS_NAMEADAPTER_WEIGHTS_NAMECONFIG_NAMESAFE_WEIGHTS_INDEX_NAMESAFE_WEIGHTS_NAMEWEIGHTS_INDEX_NAMEWEIGHTS_NAMEXLA_FSDPV2_MIN_VERSIONPushInProgressPushToHubMixincan_return_losscheck_torch_load_is_safefind_labelsis_accelerate_availableis_apex_availableis_apollo_torch_availableis_bitsandbytes_availableis_datasets_availableis_galore_torch_availableis_grokadamw_availableis_in_notebookis_ipex_availableis_liger_kernel_availableis_lomo_availableis_peft_availableis_safetensors_availableis_sagemaker_dp_enabledis_sagemaker_mp_enabledis_schedulefree_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_xla_availableis_torch_xpu_availableis_torchao_availablelogging	strtobool)deprecate_kwarg)requires)QuantizationMethod)NotebookProgressCallback)ampFz1.10)smp_forward_backwardsmp_forward_only
smp_gathersmp_nested_concat)	PeftModel)Acceleratorskip_first_batches)AcceleratorState)AutocastKwargsDistributedDataParallelKwargsDistributedTypeload_fsdp_modelload_fsdp_optimizersave_fsdp_modelsave_fsdp_optimizer1.3.0)TorchTensorParallelPluginz0.23.0)SeedableRandomSampler)DeepSpeedSchedulerWrapper0.28.0)DataLoaderConfigurationc                     [        5       (       aj  [        4n[        R                  " [        R
                  R                  S5      5      [        R                  " S5      :  a  SSKJn  / UQUP7n[        X5      $ g)Npeftz0.7.0r   )PeftMixedModelF)	r   r   r   parse	importlibmetadatar   r   
isinstance)modelclasses_to_checkr   s      L/var/www/auris/envauris/lib/python3.13/site-packages/transformers/trainer.py_is_peft_modelr     s`    %<==++33F;<g@VV+B!1B>B%22    c                      [        5       (       a5  S[        [        R                  " [        5      R
                  5      ;   a  SS0$ 0 $ )Nadapter_onlyT)rx   listinspect	signaturer   
parameters r   r   _get_fsdp_ckpt_kwargsr     s8      ^tG<M<Mo<^<i<i7j%j%%	r   c                     [         R                  " [        R                  5      R                  [         R                  " S5      R                  :  a  [
        R                  " 5       $ [         R                  " [        R                  5      [         R                  " S5      :  a  [        R                  O[        R                  n U R                  R                  [        R                  [        R                  /nU[        [        R                  " [        R                  5      5      /-  n[        R                   R#                  U5      $ )Nz2.6z2.0.0)r   r   torchr   release
contextlibnullcontextnp_corecore
multiarray_reconstructndarraydtypetypeuint32serializationsafe_globals)np_core	allowlists     r   r   r     s     }}U&&'//'--2F2N2NN%%''!--77==;QQbhhWYW^W^G##00"**bhhGI $rxx		*+,,I++I66r   ztraining_args.binztrainer_state.jsonzoptimizer.ptz	scaler.ptzoptimizer.binzscheduler.ptpytorch_model_fsdp)r   
accelerate)backendsc                   D   \ rS rSrSrSSKJrJrJrJ	r	J
r
  \" SSSSS	9             SS\\\R                  S
4   S\S\\   S\\\\S4      S\\\\\\4   S4      S\\\\\\4      S\\/ \4      S\\   S\\\/\4      S\\\      S\\\ RB                  RD                     \\ RB                  RF                  RH                     4   S\\\%\ RB                  RD                     \\\&4   4      S\\\ RN                  \ RN                  /\ RN                  4      4S jj5       r(\)S\\   4S j5       r*\*RV                  SS j5       r*S r,S r-S r.S  r/S! r0S" r1S# r2SS$SS%\\   4S& jjr3 SS\S%\\   S\4S' jjr4SS\\   S\\ Rj                  Rl                  Rn                     4S( jjr8   SS$\S%\S*\9S+\\\/\ Rj                  Rl                  Rn                  4      S,\:S-\\   S\;4S. jjr<S\;4S/ jr=S\S\\ Rj                  Rl                  Rn                     4S0 jr>SS\\\\4      S\;4S1 jjr?S2\S\;4S3 jr@S4\94S5 jrAS\\   4S6 jrBS7 rCS8 rDS9 rESS:\\\\ R                  R                  R                  4      4S; jjrH\I SS\S\\   S\\&\&4   4S< jj5       rJSS4\9S=\ RB                  RD                  4S> jjrKS?\;S\94S@ jrL\ISSA\;SB\\9   S\94SC jj5       rMSD\SE\\\&4   4   4SF jrNSD\SE\\\&4   4   SG\9SH\\\O4   4SI jrPSJ\4SK jrQSSL jrRSSM jrSS)\ R                  4SN jrUSO rVSSP jrW   SSQ\\\\:4      SD\SE\\\&4   S
4   SR\\\      4SS jjrX SST jrYSU rZSSV jr[SW r\SX r]SSY jr^ SSZ jr_S[ r`S\ raS] rbS^ rcS_ rdS` reSa rfSb rgSc rh      SSd\\SE/\\\O4   4      Se\\\\\O4   /\O4      Sf\9Sg\\\\   4   Sh\\Si\i4      Sj\\SE/\4      S\\j\\j   4   4Sk jjrkSSl\\\O4   Sm\\O   SS
4Sn jjrlSo\\ RN                  \&4   S\\ RN                  \&4   4Sp jrmSq\\\\ RN                  \&4   4   S\\\\ RN                  \&4   4   4Sr jrnSs roSSt\\:   4Su jjrp SS\R                  Sq\\\\ RN                  \&4   4   S\ RN                  4Sv jjrqSSw jrrS\:4Sx jrsS\:4Sy jrtSSz\\   S{\:4S| jjruSSz\\   4S} jjrvSSz\\   4S~ jjrwS rxS
\yS)4S\\   4S jjrzSSS jjr{   SS\\\\\\4   4      S\\\      S\S\\\O4   4S jjr| SS2\S\\\      S\S\}4S jjr~   SS?\;S%\S\\:   S\\\      S\S\4S jjrSS jr SS\R                  Sq\\\\ RN                  \&4   4   S\:S\\\      S\\\ RN                     \\ RN                     \\ RN                     4   4
S jjrSq\\\\ RN                  \&4   4   4S jrSS\\   4S jjr         SS\\   S\\   S\\\\   S
4   S\\   S\\   S\\\\   S
4   S\\\\   S
4   S$\\\\   S
4   S\\\\   S
4   4S jjrS rS r    SS\\   S\:S\\   S\\   S\4
S jjr   SS?\;S%\S\\:   S\\\      S\S\4S jjrS rSS jrS rSS jrS rS rS\S?\;S\94S jrSrg
)Traineri>  u  
Trainer is a simple but feature-complete training and eval loop for PyTorch, optimized for 🤗 Transformers.

Args:
    model ([`PreTrainedModel`] or `torch.nn.Module`, *optional*):
        The model to train, evaluate or use for predictions. If not provided, a `model_init` must be passed.

        <Tip>

        [`Trainer`] is optimized to work with the [`PreTrainedModel`] provided by the library. You can still use
        your own models defined as `torch.nn.Module` as long as they work the same way as the 🤗 Transformers
        models.

        </Tip>

    args ([`TrainingArguments`], *optional*):
        The arguments to tweak for training. Will default to a basic instance of [`TrainingArguments`] with the
        `output_dir` set to a directory named *tmp_trainer* in the current directory if not provided.
    data_collator (`DataCollator`, *optional*):
        The function to use to form a batch from a list of elements of `train_dataset` or `eval_dataset`. Will
        default to [`default_data_collator`] if no `processing_class` is provided, an instance of
        [`DataCollatorWithPadding`] otherwise if the processing_class is a feature extractor or tokenizer.
    train_dataset (Union[`torch.utils.data.Dataset`, `torch.utils.data.IterableDataset`, `datasets.Dataset`], *optional*):
        The dataset to use for training. If it is a [`~datasets.Dataset`], columns not accepted by the
        `model.forward()` method are automatically removed.

        Note that if it's a `torch.utils.data.IterableDataset` with some randomization and you are training in a
        distributed fashion, your iterable dataset should either use a internal attribute `generator` that is a
        `torch.Generator` for the randomization that must be identical on all processes (and the Trainer will
        manually set the seed of this `generator` at each epoch) or have a `set_epoch()` method that internally
        sets the seed of the RNGs used.
    eval_dataset (Union[`torch.utils.data.Dataset`, Dict[str, `torch.utils.data.Dataset`, `datasets.Dataset`]), *optional*):
         The dataset to use for evaluation. If it is a [`~datasets.Dataset`], columns not accepted by the
         `model.forward()` method are automatically removed. If it is a dictionary, it will evaluate on each
         dataset prepending the dictionary key to the metric name.
    processing_class (`PreTrainedTokenizerBase` or `BaseImageProcessor` or `FeatureExtractionMixin` or `ProcessorMixin`, *optional*):
        Processing class used to process the data. If provided, will be used to automatically process the inputs
        for the model, and it will be saved along the model to make it easier to rerun an interrupted training or
        reuse the fine-tuned model.
        This supersedes the `tokenizer` argument, which is now deprecated.
    model_init (`Callable[[], PreTrainedModel]`, *optional*):
        A function that instantiates the model to be used. If provided, each call to [`~Trainer.train`] will start
        from a new instance of the model as given by this function.

        The function may have zero argument, or a single one containing the optuna/Ray Tune/SigOpt trial object, to
        be able to choose different architectures according to hyper parameters (such as layer count, sizes of
        inner layers, dropout probabilities etc).
    compute_loss_func (`Callable`, *optional*):
        A function that accepts the raw model outputs, labels, and the number of items in the entire accumulated
        batch (batch_size * gradient_accumulation_steps) and returns the loss. For example, see the default [loss function](https://github.com/huggingface/transformers/blob/052e652d6d53c2b26ffde87e039b723949a53493/src/transformers/trainer.py#L3618) used by [`Trainer`].
    compute_metrics (`Callable[[EvalPrediction], Dict]`, *optional*):
        The function that will be used to compute metrics at evaluation. Must take a [`EvalPrediction`] and return
        a dictionary string to metric values. *Note* When passing TrainingArgs with `batch_eval_metrics` set to
        `True`, your compute_metrics function must take a boolean `compute_result` argument. This will be triggered
        after the last eval batch to signal that the function needs to calculate and return the global summary
        statistics rather than accumulating the batch-level statistics
    callbacks (List of [`TrainerCallback`], *optional*):
        A list of callbacks to customize the training loop. Will add those to the list of default callbacks
        detailed in [here](callback).

        If you want to remove one of the default callbacks used, use the [`Trainer.remove_callback`] method.
    optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`, *optional*, defaults to `(None, None)`):
        A tuple containing the optimizer and the scheduler to use. Will default to an instance of [`AdamW`] on your
        model and a scheduler given by [`get_linear_schedule_with_warmup`] controlled by `args`.
    optimizer_cls_and_kwargs (`Tuple[Type[torch.optim.Optimizer], Dict[str, Any]]`, *optional*):
        A tuple containing the optimizer class and keyword arguments to use.
        Overrides `optim` and `optim_args` in `args`. Incompatible with the `optimizers` argument.

        Unlike `optimizers`, this argument avoids the need to place model parameters on the correct devices before initializing the Trainer.
    preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`, *optional*):
        A function that preprocess the logits right before caching them at each evaluation step. Must take two
        tensors, the logits and the labels, and return the logits once processed as desired. The modifications made
        by this function will be reflected in the predictions received by `compute_metrics`.

        Note that the labels (second parameter) will be `None` if the dataset does not have them.

Important attributes:

    - **model** -- Always points to the core model. If using a transformers model, it will be a [`PreTrainedModel`]
      subclass.
    - **model_wrapped** -- Always points to the most external model in case one or more other modules wrap the
      original model. This is the model that should be used for the forward pass. For example, under `DeepSpeed`,
      the inner model is wrapped in `DeepSpeed` and then again in `torch.nn.DistributedDataParallel`. If the inner
      model hasn't been wrapped, then `self.model_wrapped` is the same as `self.model`.
    - **is_model_parallel** -- Whether or not a model has been switched to a model parallel mode (different from
      data parallelism, this means some of the model layers are split on different GPUs).
    - **place_model_on_device** -- Whether or not to automatically place the model on the device - it will be set
      to `False` if model parallel or deepspeed is used, or if the default
      `TrainingArguments.place_model_on_device` is overridden to return `False` .
    - **is_in_train** -- Whether or not a model is currently running `train` (e.g. when `evaluate` is called while
      in `train`)

r   )_get_learning_ratelog_metricsmetrics_formatsave_metrics
save_state	tokenizerprocessing_classz5.0.0T)new_namer   raise_if_both_namesNNNr   argsdata_collatortrain_datasetzdatasets.Dataseteval_dataset
model_initcompute_loss_funccompute_metrics	callbacks
optimizersoptimizer_cls_and_kwargspreprocess_logits_for_metricsc                 #   Uc$  Sn[         R                  SU S35        [        US9nUR                  (       a@  U	b=  S[        R
                  " U	5      R                  R                  5       ;  a  [        S5      eUR                  b,  UR                  S:w  a  Uc  [        SUR                   S	35      eUR                  [        R                  :X  d  UR                  (       a  UR                  c  [        S
5      eX l        Xl        U R                  R"                  (       a  [%        U R                  R&                  5      O[)        U R                  R&                  5        S U l        S U l        SU l        Xl        U R3                  5         [5        U R                  R6                  5      U l        U R8                  R;                  5         UR=                  5       n[>        R@                  " U5        URB                    Uc%  Ub  Xpl"        U RG                  5       nO/[I        S5      eUb  [J        RL                  " S[N        5        Xpl"        URP                  RR                  [T        ;   a#  [        SURP                  RR                   S35      e[W        USS5      (       a  [W        USS5      (       a  SU l,        OSU l,        [W        USS 5      b  [[        UR\                  R_                  5       5       Vs/ s H  nUS;  d  M  UPM     nn[a        U5      S:  a  SU l,        OL[a        U5      S:X  a6  U R                  Rb                  [d        Rb                  " US   5      :g  U l,        OSU l,        U RX                  (       a  [         R                  S5        U R                  Rf                  (       a  [i        5       (       a  SSK5J6n  [o        U[p        5      (       a  U" US9  Oj[s        US5      (       a8  [o        URu                  5       [p        5      (       a  U" URu                  5       S9  O![         Rw                  S5        O[y        S5      e[W        USS5      =(       a    [W        USS5      (       + n[W        USS 5      S L=(       a    URz                  R|                  n[W        USS 5      S L=(       a    [W        URz                  S S5      nU(       a  [s        US!5      (       a  [        S"5      eU(       a"  [        U5      (       d  U(       d  [        S#5      eU(       aT  U(       dM  [        S$URz                  R                  R                   S%URz                  R                  R                   35      eUR                  S&   U lC        [a        UR                  5      S:  aY  U R                  (       a  [        S'5      eUR                  S&   (       d)  UR                  [        R                  :w  a  [        S(5      eUR                  U lI        U RX                  (       df  U R                  (       dU  UR                  (       d  UR                  (       a  UR                  (       a"  U R                  (       d  U R                  (       a  SU lI        Ub&  [o        U[        [        45      (       a  [        U5      O[        nUb  UOUU lR        X@lS        XPlT        X`lU        U R                  (       a:  [W        US)S 5      [        R                  :X  d  U R                  XRb                  5        U RX                  (       a  SU R                  lY        XlZ        Xl        U R                  R                  U5      n[        U5      (       d  UR                  OURu                  5       R                  n[        R
                  " U5      R                  n[s        US*5      (       a  UR                  U l_        O%[        S+ UR_                  5        5       5      U l_        UR                  U la        Xlb        Xlc        Uu  U ld        U le        Xlf        U R                  b  U R                  b  [I        S,5      eUb%  U R                  c  U R                  b  [I        S-5      e[        5       (       a  U R                  b  U R0                  R                  5        H  nURb                  n  O   U R                  R                   H)  n[a        US.   5      S:  d  M  US.   S   Rb                  n  O   WW:w  a  [        S/5      eU R                  (       d  U R                  (       a%  U R                  c  U R                  b  [I        S05      e[        [        U R                  R                  5      -   nU
c  UOUU
-   n
[        XR0                  U R                  U R                  U R                  5      U lm        U R                  U R                  R                  (       a  [        O[        5        SU lr        S U ls        U R                  R                  (       a  U R                  5         U R                  R                  (       a)  [        R                  " U R                  R                  SS19  [        U R                  5      (       d0  [        [W        U R                  S2S 5      5      (       a  [        S35      eUR                  S:  a%  UR                  S:  a  [         R                  S45        Ub+  [        U5      (       d  UR                  S::  a  [        S55      eUbQ  [o        U[d        R                  R                  GR                   5      (       a  UGR                  (       a  [        S65      eS U l        SU l        SU l        G[        5       (       Gan  UGR                  (       a  [        S75      eG[        (       a  UGR                  G[        GR                  GR                  GR                  :w  a  [         Rw                  S8G[        GR                  GR                  GR                   S9UGR                   S:G[        GR                  GR                  GR                   35        G[        GR                  GR                  GR                  Ul        Ok[s        G[        GR                  GR                  S;5      (       a?  [         Rw                  S8G[        GR                  GR                  GR                   S<35        UGR                  (       d  UGR                  (       a  UGR                  S=:X  ay  URb                  [d        Rb                  " S>5      :X  a1  UGR                  (       a  G[        (       d  [        S?5      eOS@Ul        [         R                  SAUGR                   SB35        UGR                  (       d  UGR                  (       a  U R                  (       dr  G[        5       (       db  UGR                  S@:X  a  SU l        [d        GR                  U l        O3UGR                  SC:X  a"  G[!        5       (       d  [y        SD5      eSU l        U R                  GR"                  S:w  a%  G[%        U R                  GR"                  SE9U l        OS U l        G[)        5       U l        G[-        U GR/                  5       U GR1                  5       U R                  GR2                  U GR*                  /-    Vs/ s H  n[o        UG[4        5      (       d  M  UPM     snSF9U l        SU l        S U l        [        U R0                  5      (       aO  U R                  GR:                  c7  [         Rw                  SGU R0                  RP                  RR                   SH35        G[=        U R0                  RP                  5      n U R                  GR:                  c  U OU R                  GR:                  U l        G[?        U R0                  RP                  5      U l        U R                  GRA                  U R                  U GR                  U GR*                  5      U l        UGRB                  U l        SU l        U R8                  GRI                  5         UR                  GRK                  SIS5      U l        U GRL                  (       a~  G[N        (       d  [        SJ5      eG[P        GRR                  " 5       n!G[T        GRV                  " G[T        GRX                  " G[Z        GR\                  " G[_        U!5      5      U!S4SKSL95        U R                  =(       a    U GRL                  (       + U l        g s  snf s  snf )MNtmp_trainerz1No `TrainingArguments` passed, using `output_dir=z`.)
output_dircompute_resultzWhen using `batch_eval_metrics`, your `compute_metrics` function must take a `compute_result` boolean argument which will be triggered after the last batch of the eval set to signal that the summary statistics should be returned by the function.noz%You have set `args.eval_strategy` to zx but you didn't pass an `eval_dataset` to `Trainer`. Either set `args.eval_strategy` to `no` or pass an `eval_dataset`. z`args.metric_for_best_model` must be provided when using 'best' save_strategy or if `args.load_best_model_at_end` is set to `True`.Fz<`Trainer` requires either a `model` or `model_init` argumentz`Trainer` requires either a `model` or `model_init` argument, but not both. `model_init` will overwrite your model when calling the `train` method. This will become a fatal error in the next release.zThe model you have picked (a  ) cannot be used as is for training: it only computes hidden states and does not accept any labels. You should choose a model with a head suitable for your task like any of the `AutoModelForXxx` listed at https://huggingface.co/docs/transformers/model_doc/autois_parallelizablemodel_parallelThf_device_map)cpudiskr   r   zYou have loaded a model on multiple GPUs. `is_model_parallel` attribute will be force-set to `True` to avoid any unexpected behavior such as device placement mismatching.)_apply_liger_kernel_to_instancer   get_base_modelzRThe model is not an instance of PreTrainedModel. No liger kernels will be applied.zYou have set `use_liger_kernel` to `True` but liger-kernel >= 0.3.0 is not available. Please install it with `pip install liger-kernel`is_quantized_hf_peft_config_loadedhf_quantizeris_qat_trainable	_orig_modzYou cannot fine-tune quantized model with `torch.compile()` make sure to pass a non-compiled model when fine-tuning a quantized model with PEFTzYou cannot perform fine-tuning on purely quantized models. Please attach trainable adapters on top of the quantized model to correctly perform fine-tuning. Please see: https://huggingface.co/docs/transformers/peft for more detailsz8The model you are trying to fine-tune is quantized with z but that quantization method do not support training. Please open an issue on GitHub: https://github.com/huggingface/transformers to request the support for training support for xlazZUsing --fsdp xxx together with --deepspeed is not possible, deactivate one of those flags.z.Using fsdp only works in distributed training.quantization_methodaccepts_loss_kwargsc              3   n   #    U  H+  oR                   [        R                  R                  :H  v   M-     g 7fN)kindr   	ParameterVAR_KEYWORD).0ks     r   	<genexpr>#Trainer.__init__.<locals>.<genexpr>  s'      1AXA'++777AXs   35zSPassing both `optimizers` and `optimizer_cls_and_kwargs` arguments is incompatible.zPassing a `model_init` is incompatible with providing the `optimizers` argument. You should subclass `Trainer` and override the `create_optimizer_and_scheduler` method.paramsa[  The model and the optimizer parameters are not on the same device, which probably means you created an optimizer around your model **before** putting on the device and passing it to the `Trainer`. Make sure the lines `import torch_xla.core.xla_model as xm` and `model.to(xm.xla_device())` is performed before the optimizer creation in your script.zPassing `optimizers` is not allowed if PyTorch FSDP is enabled. You should subclass `Trainer` and override the `create_optimizer_and_scheduler` method.exist_okcollate_batchzRThe `data_collator` should be a simple callable (function, class with `__call__`).zHmax_steps is given, it will override any value given in num_train_epochszThe train_dataset does not implement __len__, max_steps has to be specified. The number of steps needs to be known in advance for the learning rate scheduler.zTthe `--group_by_length` option is only available for `Dataset`, not `IterableDatasetzOSageMaker Model Parallelism does not support BF16 yet. Please use FP16 instead z(FP16 provided in SM_HP_MP_PARAMETERS is z+, but FP16 provided in trainer argument is z, setting to fp16zJ, but SageMaker Model Parallelism < 1.10 does not support FP16 in trainer.autor   z2Tried to use `fp16` but it is not supported on cpucpu_ampzUsing z half precision backendapexzcUsing FP16 with APEX but APEX is not installed, please refer to https://www.github.com/nvidia/apex.)epsilon)is_local_process_zerois_world_process_zerostateful_callbacksz)No label_names provided for model class `z`. Since `PeftModel` hides base models input arguments, if label_names is not given, label_names can't be set automatically within `Trainer`. Note that empty label_names list will be used instead.xla_fsdp_v2z*FSDPv2 requires `torch_xla` 2.2 or higher.)fsdptensor)
axis_names)loggerinfori   batch_eval_metricsr   r   r   keys
ValueErroreval_strategysave_strategyrX   BESTload_best_model_at_endmetric_for_best_modelr   r   full_determinismr^   seedre   hp_name	deepspeedis_in_trainr   "create_accelerator_and_postprocessrY   skip_memory_metrics_memory_trackerstartget_process_log_levelr   set_verbosity_setup_devicesr   call_model_initRuntimeErrorwarningswarnFutureWarning	__class____name__r-   getattris_model_parallelsetr   valueslendevicer   use_liger_kernelr   liger_kernel.transformersr   r   r)   hasattrr   warningImportErrorr   is_trainabler   quantization_configquant_methodfsdp_configis_fsdp_xla_enabledr  is_deepspeed_enabledparallel_moderh   DISTRIBUTEDplace_model_on_devicefp16_full_evalbf16_full_evaldo_trainis_fsdp_enabledr3   r   r   r   r   r   r   r   r   BITS_AND_BYTES_move_model_to_device_n_gpumodel_wrappedacceleratorr+   forwardr  model_accepts_loss_kwargsanyneftune_noise_alphar   r   	optimizerlr_schedulerr   r   param_groupsDEFAULT_CALLBACKSr   	report_tor4   callback_handleradd_callbackdisable_tqdmr7   DEFAULT_PROGRESS_CALLBACK_loggers_initializedhub_model_idpush_to_hubinit_hf_reposhould_saveosmakedirsr   callable	max_stepsnum_train_epochsra   utilsdatar   group_by_length_signature_columnsuse_apexuse_cpu_ampr   bf16IS_SAGEMAKER_MP_POST_1_10r  smpstatecfghalf_precision_backendr2   bfloat16	amp_dtypery   label_smoothing_factorr?   label_smootherr:   controlr;   r  r  r   r6   current_floshp_search_backendlabel_namesrw   ru   on_init_endtrain_batch_size_train_batch_size_created_lr_schedulerstop_and_update_metricsgetis_fsdp_xla_v2_enabledIS_XLA_FSDPV2_POST_2_2xrglobal_runtime_device_countxsset_global_meshMeshr   arrayrangeis_fsdp_xla_v1_enabled)"selfr   r   r   r   r   r   r   r   r   r   r   r   r   r   	log_levelr=  devicesr   _is_quantized_and_base_model&_quantization_method_supports_training%_is_model_quantized_and_qat_trainabledefault_collatorunwrapped_modelmodel_forwardforward_paramsparammodel_deviceparam_groupoptimizer_devicedefault_callbackscbdefault_label_namesnum_devicess"                                     r   __init__Trainer.__init__  s   & <&JKKKJ<WYZ[$
;D""'Bw'8'8'I'T'T'Y'Y'[[ N 
 )d.@.@D.H\Ma78J8J7K  LD  E  !2!22d6Q6Q))1  Z  	!237993M3M		/S[\`\e\e\j\jSk 
//1  4DII4Q4QR""$ ..0	i( 	=%",,,."#abb%  "	 )O??##'::-eoo.F.F-G HJ J  5-u55'%IY[`:a:a%)D"%*D"5/40<,/0C0C0J0J0L,Mo,M&QW_nQnv,MGo7|a)-&W")-)9)9U\\'RS*=U)U&).& %%h
 99%%(**Ue_553%@U$455*UEYEYE[]l:m:m3%:N:N:PQNNl "H 
 (/une'L (
U\+UV
 R
$ E>40<`ASASA`A` 	/ 18~t0T\`0` 1
el 2Ef
-
 (GE;,G,G b 
 (u0E0ENs$ 
 *2XJ5K]K]KqKqK~K~JDDIDVDVDjDjDwDwCxz  $(#3#3E#: tyy>A(( p  ##E*t/A/A\E]E]/] !QRR &*%?%?"""(($$(;(;T]]''##).D&  ++.EG_-`aa $$45 '	 	 /<.G]M]*( 0 &&E#8$?CUCdCdd&&ukk: !! DII #
 **77> "/22 ## //199 	
 !**=9DD 5/00-2-F-FD*-0 1AOAVAVAX1 .D* $(#;#; .-J*,6))(@%((49Stuu!t~~'ATEVEVEbj  "##(B..0$|| 1  $~~::{8,-1'28'<Q'?'F'F$  ; // n  $$(<(<NN&$*;*;*Gj  .0STXT]T]TgTg0hh)2):%@QT]@]	 /zz4#8#8$..$J[J[!
 	TYY-C-C/Ibc %*! !99  99  KK		,,t<**++ASASUdfj9k0l0lqrr>>A$"7"7!";KKbc$Z-F-F4>>]^K^d  %=%++*:*:*J*JKK$$$stt"&   #$$yyy !rss((99		 2 22NNB399==CUCUBV WDDHII; O&&)iimm&8&8%9;
 !$		 2 2DI 399==&11NNB399==CUCUBV Wc c III(C(Cv(M{{ell511999==()]^^ > 3<D/KK&!<!< ==TUVIIIT-F-FJaJcJc**i7#' !&,,6(**%?  !% 99++q0"/		8X8X"YD"&D%'!"&"<"<">"&"<"<">!22<<~M MrQ[\^`oQpM 

 !%$**%%$))*?*?*GNN;DJJ<P<P<Y<Y;Z [J J
 *$***>*>?26))2G2G2O.UYU^U^UjUj.tzz/C/CD,,88DJJPTP\P\] "&!6!6%*" 	446&*&6&6&:&:=%&P#&&&)) !MNN 88:Krwwrxxk0B'CkSTEUbtuv&*&>&>&btGbGbCb#]	 pX s   ,
AE?:AE?AF)AFreturnc                 D    [         R                  S5        U R                  $ )NzUTrainer.tokenizer is now deprecated. You should use Trainer.processing_class instead.r  rA  r   r  s    r   r   Trainer.tokenizer2  s    no$$$r   c                 :    [         R                  S5        Xl        g )NzjTrainer.tokenizer is now deprecated. You should use `Trainer.processing_class = processing_class` instead.r  )r  r   s     r   r   r  7  s    x	
 !1r   c                     U R                   R                  U5      n[        U5      (       a%  UR                  R                  R                  5       nOUR                  5       nAU R                  Ul        UR                  [        5      nX@l	        U$ )z
Activates the neftune as presented in this code: https://github.com/neelsjain/NEFTune and paper:
https://arxiv.org/abs/2310.05914
)
rT  r+   r   
base_modelr   get_input_embeddingsrX  register_forward_hookrb   neftune_hook_handle)r  r   r  
embeddingshook_handles        r   _activate_neftuneTrainer._activate_neftune>  sz    
 **77>/**(3399NNPJ(==?J)-)A)A
& 667PQ#. r   c                 6   [        U S5      (       d  [        S5      eU R                  R                  U5      n[	        U5      (       a%  UR
                  R                  R                  5       nOUR                  5       nU R                  R                  5         U?
Ag)zN
Deactivates the neftune method. Make sure to call `_activate_neftune` first.
r  zNNeftune is not activated make sure to call `trainer._activate_neftune()` firstN)r@  r  rT  r+   r   r  r   r  r  removerX  )r  r   r  r  s       r   _deactivate_neftuneTrainer._deactivate_neftuneQ  s     t233mnn**77>/**(3399NNPJ(==?J  '')*Or   c                 :    U R                   R                  U5        g)a7  
Add a callback to the current list of [`~transformers.TrainerCallback`].

Args:
   callback (`type` or [`~transformers.TrainerCallback]`):
       A [`~transformers.TrainerCallback`] class or an instance of a [`~transformers.TrainerCallback`]. In the
       first case, will instantiate a member of that class.
N)r^  r_  r  callbacks     r   r_  Trainer.add_callbackb  s     	**84r   c                 8    U R                   R                  U5      $ )a  
Remove a callback from the current list of [`~transformers.TrainerCallback`] and returns it.

If the callback is not found, returns `None` (and no error is raised).

Args:
   callback (`type` or [`~transformers.TrainerCallback]`):
       A [`~transformers.TrainerCallback`] class or an instance of a [`~transformers.TrainerCallback`]. In the
       first case, will pop the first member of that class found in the list of callbacks.

Returns:
    [`~transformers.TrainerCallback`]: The callback removed, if found.
)r^  pop_callbackr  s     r   r  Trainer.pop_callbackm  s     $$11(;;r   c                 :    U R                   R                  U5        g)a^  
Remove a callback from the current list of [`~transformers.TrainerCallback`].

Args:
   callback (`type` or [`~transformers.TrainerCallback]`):
       A [`~transformers.TrainerCallback`] class or an instance of a [`~transformers.TrainerCallback`]. In the
       first case, will remove the first member of that class found in the list of callbacks.
N)r^  remove_callbackr  s     r   r  Trainer.remove_callback}  s     	--h7r   c                     UR                  U5      nU R                  R                  [        R                  :X  a#  [        US5      (       a  UR                  5         g g g )Ntie_weights)tor   rI  rh   TPUr@  r  )r  r   r=  s      r   rQ  Trainer._move_model_to_device  sI     99""l&6&6675-;X;X <Y6r   c                    U R                   c  U R                  n[        U R                  5      (       aV  [        U R                  S5      (       a  U R                  R	                  5       nO U R                  R
                  R                  n[        R                  " UR                  5      n[        UR                  R                  5       5      U l         U =R                   [        [        SS/U R                  -   5      5      -  sl         g g )Nr   label	label_ids)ro  r   r   r@  r   r  r   r   rU  r   r   r  r:  r  )r  model_to_inspectr   s      r    _set_signature_columns_if_needed(Trainer._set_signature_columns_if_needed  s    ""*#zzdjj))4::'788'+zz'@'@'B$ (,zz'<'<'B'B$))*:*B*BCI&*9+?+?+D+D+F&GD###tC+0FIYIY0Y,Z'[[# +r   datasetdescriptionc                    U R                   R                  (       d  U$ U R                  5         U R                  n[	        [        UR                  5      [        U5      -
  5      n[        U5      S:  a  Uc  SOSU S3n[        R                  SU SU R                  R                  R                   SSR                  U5       S	SR                  U5       S
U R                  R                  R                   S35        U Vs/ s H  ofUR                  ;   d  M  UPM     nn[        U5      S:X  a  [        SSR                  U5       S35      e[        R                   " ["        R$                  5      [        R                   " S5      :  a,  UR'                  UR(                  S   XqR(                  S   S9  U$ UR+                  U5      $ s  snf )Nr    zin the z setzThe following columns z) don't have a corresponding argument in `z!.forward` and have been ignored: , z. If z are not expected by `z/.forward`,  you can safely ignore this message.zNo columns in the dataset match the model's forward method signature: ({', '.join(signature_columns)}). The following columns have been ignored: [zp]. Please check the dataset and model. You may need to set `remove_unused_columns=False` in `TrainingArguments`.1.4.0r   format_kwargs)r   columnsr  )r   remove_unused_columnsr  ro  r   r:  column_namesr<  r  r  r   r6  r7  joinr  r   r   datasetsr   
set_formatformatremove_columns)r  r  r  signature_columnsignored_columnsdset_descriptionr  r  s           r   _remove_unused_columnsTrainer._remove_unused_columns  s   yy..N--/ 33s7#7#783?P;QQR!#%0%8r}TX>YKK()9(: ;JJ((1122STXT]T]^mTnSo pyy122HI]I]IfIfHg h77 0M/8L8L3L1/Mw<1==AYY=W<X Y@@  ==--.w1GG^^F+WNN[jLk   N))/:: Ns   GGc                     U R                   R                  (       d  U$ U R                  5         U R                  n[	        UU[
        UU R                  R                  R                  S9nU$ )z=Wrap the data collator in a callable removing unused columns.)r   r  r  r  
model_name)	r   r  r  ro  rW   r  r   r6  r7  )r  r   r  r  remove_columns_collators        r   "_get_collator_with_removed_columns*Trainer._get_collator_with_removed_columns  sa     yy..  --/ 33"7'/#zz++44#
 '&r   c                 0   Uc  U R                   nUb  [        U5      (       d  g U R                  R                  (       a  [	        5       (       a^  [        U[        R                  5      (       a?  U R                  R                  UR                  ;   a  XR                  R                     OS nOS nU R                  b  U R                  R                  S   OS n[        U R                  R                  U R                  R                  -  UUUS9$ [        U5      $ )Nr   r  lengthsmodel_input_name)r   ra   r   rn  r|   r   r  r   length_column_namer  r   model_input_namesrA   r  gradient_accumulation_stepsr   )r  r   r  r  s       r   _get_train_samplerTrainer._get_train_sampler  s      ..M 
=(A(A 99$$$&&:mXEUEU+V+V yy33}7Q7QQ "))">">?  >B>S>S>_%%77:ei  (		**TYY-R-RR%!1	  !//r   F
batch_size
sampler_fnis_trainingdataloader_keyc                    U R                   n[        5       (       a/  [        U[        R                  5      (       a  U R                  XS9nOU R                  U R                   US9nUUU R                  R                  U R                  R                  U R                  R                  S.n[        U[        R                  R                  R                  5      (       d  Ub  U" U5      US'   U R                  R                  US'   U R                  R                   US'   U(       a:  [#        [$        U R                  R                  U R                  R&                  S9US'   [)        U40 UD6n	UbC  U R                  R                  (       a(  [+        U S5      (       a  XR,                  U'   OXi0U l        U R.                  R1                  U	5      $ )	zACreate a [`~torch.utils.data.DataLoader`] from the given dataset.)r  )r  
collate_fnnum_workers
pin_memorypersistent_workerssampler	drop_lastprefetch_factor)r  rankworker_init_fn_eval_dataloaders)r   r|   r   r  r   r  r  r   dataloader_num_workersdataloader_pin_memorydataloader_persistent_workersr   rl  rm  r   dataloader_drop_lastdataloader_prefetch_factorr   rd   process_indexr   r@  r  rT  prepare)
r  r  r  r  r  r  r  r   dataloader_params
dataloaders
             r   _get_dataloaderTrainer._get_dataloader  s    ** ""z'8;K;K'L'L11'1SG CCDDVDVdoCpM %'99;;))99"&))"I"I
 '5;;#3#3#C#CDD%/9'/B!),-1YY-K-Kk*37993W3W/06=TYY-M-MTXT]T]TkTk7!"23  =+<=
 %$))*Q*Qt0119C&&~6*8)E&''
33r   c                     U R                   c  [        S5      eU R                  U R                   SU R                  U R                  SS9$ )a  
Returns the training [`~torch.utils.data.DataLoader`].

Will use no sampler if `train_dataset` does not implement `__len__`, a random sampler (adapted to distributed
training if necessary) otherwise.

Subclass and override this method if you want to inject some custom behavior.
z+Trainer: training requires a train_dataset.TrainingT)r  r  r  r  r  )r   r  r  r  r  r  s    r   get_train_dataloaderTrainer.get_train_dataloader  sU     %JKK##&&"--.. $ 
 	
r   c                    Ub  [        U5      (       d  g U R                  R                  (       a  [        5       (       a1  [	        U[
        R                  " 5       [
        R                  " 5       S9$ [        5       (       aF  [	        U[        R                  " 5       [        R                  " 5       U R                  R                  S9$ [        U5      $ U R                  R                  (       a  [        5       (       a^  [!        U["        R$                  5      (       a?  U R                  R&                  UR(                  ;   a  XR                  R&                     OS nOS nU R*                  b  U R*                  R,                  S   OS n[/        U R                  R0                  UUUS9$ U R                  R                  S::  a  [        U5      $ g )N)num_replicasr  )r  r  r  r   r  r   )ra   r   use_legacy_prediction_loopr   rB   r  
world_sizeglobal_ordinalr   rt  dp_sizedp_rankper_device_eval_batch_sizer   rn  r|   r   r  r   r  r  r   r  rA   eval_batch_size)r  r   r  r  s       r   _get_eval_samplerTrainer._get_eval_sampler/  sh   z,'?'? 99//%''3 r}}REVEVEX  )**3 !$#yyCC	  )6699$$$&&:lHDTDT+U+U yy33|7P7PP !!=!=>  >B>S>S>_%%77:ei  (		))$!1	  991$$\22r   c                    Uc  U R                   c  [        S5      e[        U[        5      (       a  UOSn[	        U S5      (       aR  X R
                  ;   aC  U R                  R                  (       a(  U R                  R                  U R
                  U   5      $ [        U[        5      (       a  U R                   U   OUb  UOU R                   nU R                  USU R                  R                  U R                  US9$ )a  
Returns the evaluation [`~torch.utils.data.DataLoader`].

Subclass and override this method if you want to inject some custom behavior.

Args:
    eval_dataset (`str` or `torch.utils.data.Dataset`, *optional*):
        If a `str`, will use `self.eval_dataset[eval_dataset]` as the evaluation dataset. If a `Dataset`, will override `self.eval_dataset` and must implement `__len__`. If it is a [`~datasets.Dataset`], columns not accepted by the `model.forward()` method are automatically removed.
z-Trainer: evaluation requires an eval_dataset.evalr  
Evaluation)r  r  r  r  r  )r   r  r   strr@  r  r   r  rT  r  r  r  r  )r  r   r  s      r   get_eval_dataloaderTrainer.get_eval_dataloader\  s     D$5$5$=LMM *4L#)F)FFD-.."8"88		77##++D,B,B>,RSS ,,, l+ ' "" 	 ## $yy00--) $ 
 	
r   test_datasetc                 b    U R                  USU R                  R                  U R                  S9$ )a}  
Returns the test [`~torch.utils.data.DataLoader`].

Subclass and override this method if you want to inject some custom behavior.

Args:
    test_dataset (`torch.utils.data.Dataset`, *optional*):
        The test dataset to use. If it is a [`~datasets.Dataset`], columns not accepted by the
        `model.forward()` method are automatically removed. It must implement `__len__`.
test)r  r  r  r  )r  r   r  r  )r  r  s     r   get_test_dataloaderTrainer.get_test_dataloader  s8     ## yy00--	 $ 
 	
r   num_training_stepsc                     U R                  5         [        (       a@  [        R                  R                  R
                  (       a  U R                  R                  nOU R                  nU R                  XS9  g)a2  
Setup the optimizer and the learning rate scheduler.

We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
Trainer's init through `optimizers`, or subclass and override this method (or `create_optimizer` and/or
`create_scheduler`) in a subclass.
)r"  rY  N)create_optimizerrs  rt  ru  rv  r  rY  create_schedulerr  r"  rY  s      r   create_optimizer_and_scheduler&Trainer.create_optimizer_and_scheduler  sP     	$$););00II1CYr   c                 ,    [        U[        / SQ5      nU$ )a  
Get all parameter names that weight decay will be applied to.

This function filters out parameters in two ways:
1. By layer type (instances of layers specified in ALL_LAYERNORM_LAYERS)
2. By parameter name patterns (containing 'bias', 'layernorm', or 'rmsnorm')
)bias	layernormrmsnorm)rH   r1   )r  r   decay_parameterss      r   get_decay_parameter_names!Trainer.get_decay_parameter_names  s     /u6JLlmr   c           
         [        5       (       a  U R                  OU R                  nU R                  Gc  U R	                  U5      nUR                  5        VVs/ s H!  u  p4X2;   d  M  UR                  (       d  M  UPM#     snnU R                  R                  S.UR                  5        VVs/ s H!  u  p4X2;  d  M  UR                  (       d  M  UPM#     snnSS./nU R                  b  U R                  u  pgOU R                  U R                  U5      u  pgSU;   a  UR                  S5      nSU;   a  UR                  S5      nSU;   a  UR                  S5      nU" U40 UD6U l        S[        U5      ;   Ga9  UR                  SS5      S	:X  Ga"  S
SKnUR                  R                   R#                  5       n	S
n
UR%                  5        H  n['        U[(        R*                  5      (       d  M$  U
[-        UR/                  5        Vs0 s H!  oDR1                  5       UR3                  5       _M#     snR5                  5       5      -  n
[6        R9                  SU SU
S-   S35        U	R;                  USSS05        [6        R=                  SU S35        M     [6        R9                  SU
S-   S35        [        5       (       a%  [>        R@                  " U R                  5      U l        U R                  $ s  snnf s  snnf s  snf )z
Setup the optimizer.

We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
Trainer's init through `optimizers`, or subclass and override this method in a subclass.
N)r  weight_decay        r  r   optimizer_dictbitsandbytes
optim_bits   r   zskipped : i   zM paramsweight    zbitsandbytes: will optimize z in fp32z	skipped: )!r   rS  r   rY  r.  named_parametersrequires_gradr   r1  r   get_optimizer_cls_and_kwargspopr  r  r4  optimGlobalOptimManagerget_instancemodulesr   r   	Embeddingsumr   data_ptrnumelr;  r  r  register_module_overridedebugrt  DistributedOptimizer)r  	opt_modelr-  npoptimizer_grouped_parametersoptimizer_clsoptimizer_kwargsr4  managerskippedmodules               r   r$  Trainer.create_optimizer  s    +B*C*CD&&	>>!#==iH '0&@&@&B&BdaqG\abapap&B %)II$:$:	 '0&@&@&B&BdaqG`efetet&B %(	,( ,,8262O2O//262S2STXT]T]_h2i/ ++/?/C/CH/M, **/?/C/CG/L,  #33/?/C/CDT/U,*+G\K[\DN]!338H8L8L\[_8`de8e#&,,??LLN'//1F!&",,773IZIZI\']I\A

aggi(?I\']'d'd'f#gghvhb58I$RS88LZ\K]^'CF88%TU 2 i%'8AB"$$ 55dnnEDN~~iJ (^s*   K5)K5<K5/K;>K;K;	(Lc                 V    [        S U R                  R                  5        5       5      $ )z)
Get the number of trainable parameters.
c              3   f   #    U  H'  oR                   (       d  M  UR                  5       v   M)     g 7fr  )r;  rE  )r  rK  s     r   r	  7Trainer.get_num_trainable_parameters.<locals>.<genexpr>  s      Q&=917799&=s   11)rC  r   r   r  s    r   get_num_trainable_parameters$Trainer.get_num_trainable_parameters  s"     Qdjj&;&;&=QQQr   c                     U R                   c  [        S5      eU R                   R                   Vs/ s H  oS   PM	     sn$ s  snf )zB
Returns the learning rate of each parameter from self.optimizer.
PTrainer optimizer is None, please make sure you have setup the optimizer before.lrrY  r  r[  )r  groups     r   get_learning_ratesTrainer.get_learning_rates  s@     >>!opp)-)D)DE)Dd)DEEEs   Ar  c                     U R                   c  [        S5      eUb)  U R                   R                   H  nXS   ;   d  M  Us  $    U R                   R                   Vs/ s H  o"S   PM	     sn$ s  snf )z
Returns optimizer group for a parameter if given, else returns all optimizer groups for params.

Args:
    param (`str` or `torch.nn.parameter.Parameter`, *optional*):
        The parameter for which optimizer group needs to be returned.
rY  r  r[  )r  r  r\  s      r   get_optimizer_groupTrainer.get_optimizer_group  sk     >>!opp44(O+ L 5 .2^^-H-HI-HEh-HIIIs   A.c                   ^ ^^#^$ 0 m#T R                   (       aJ  T R                   R                  SS5      R                  S5       H  nUR                  S5      u  p4UT#U'   M     ST R                  0m$T R                  T R
                  4T R                  S.n S|S[        S	[        [        [        4   S
[        [        [        4   S[        S[        [        [        4   4
U UU#U$4S jjjnT R                  [        R                  :X  a  [        nT$R!                  SSS.5        UT$4$ T R                  [        R"                  [        R$                  4;   aN  SSKJn  UnT$R!                  U5        T R                  [        R$                  :X  a  T$R!                  SS05        UT$4$ T R                  [        R*                  :X  a   SSKJn  UnT$R!                  U5        UT$4$ T R                  [        R2                  :X  a   SSKJn	  U	nT$R!                  U5        UT$4$ T R                  [        R8                  :X  a   SSKJn
  U
nT$R!                  U5        UT$4$ T R                  [        R>                  [        R@                  [        RB                  [        RD                  [        RF                  [        RH                  [        RJ                  [        RL                  [        RN                  [        RP                  [        RR                  [        RT                  [        RV                  [        RX                  [        RZ                  4;   Ga   SSK.JnJ/nJ0n  SnSnSnUnST R                  ;   a  SnST R                  ;   a  SnST R                  ;   a  UnGOST R                  ;   a  UnS T R                  T R
                  40nGOfS!T R                  ;   a  UnT#nGOPS"T R                  ;   Ga?  [c        5       (       aV  [d        Rf                  " [h        Rj                  Re                  S#5      5      [d        Rf                  " S$5      :  a  [1        S%5      eSS&K.J6n  Un[o        T#Rq                  S'T R                  5      5      [o        T#Rq                  S(T R
                  5      5      [o        T#Rq                  S)S*5      5      4[o        T#Rq                  S+S,5      5      [o        T#Rq                  S-T R                  5      5      S..nS/T#;   a  [s        T#S/   5      US/'   S0T#;   a  [s        T#S0   5      US0'   S1U0nS!T R                  ;  a  UUS2'   T$R!                  U5        T$R!                  U5        [c        5       (       a`  [d        Rf                  " [h        Rj                  Re                  S#5      5      [d        Rf                  " S45      :  a  [t        Rw                  S55        UT$4$ T R                  [        Rx                  :X  a   SS6K=J>n  UnT$R!                  U5        T$R!                  [        T#Rq                  S7S85      5      [        [        T#Rq                  S9S:5      5      [        [        T#Rq                  S;S:5      5      [        [        T#Rq                  S<S=5      5      S>.5        UT$4$ T R                  [        R                  :X  a  [        R                  R                  nUT$4$ T R                  [        R                  :X  a  [        R                  R                  nUT$4$ T R                  [        R                  :X  a  [        R                  R`                  nUT$4$ T R                  [        R                  [        R                  [        R                  [        R                  [        R                  [        R                  4;   Ga5  [        5       (       d  [/        S@5      eSSAKMJNnJOnJPn  [        R                  U[        R                  U[        R                  U[        R                  U[        R                  U[        R                  U0n[s        T#R                  SBSC5      5      [s        T#R                  SDSE5      5      [o        T#R                  SFSG5      5      T#R                  SHSI5      SJ.nU" T R                  UU5      u  nm$T R                  [        R                  :X  a  T$R!                  SSS.5        UT$4$ T R                  [        R                  [        R                  4;   a  [        5       (       d  [/        SK5      eSSLKUJVn  [        R                  U[        R                  U0n[s        T#R                  SBSC5      5      T#R                  SMSN5      T#R                  SOSP5      [s        T#R                  SDSE5      5      [o        T#R                  SFSQ5      5      T#R                  SHSI5      SR.nUR!                  U5        U" T R                  UU5      u  nm$UT$4$ T R                  [        R                  [        R                  4;   aw  [        5       (       d  [/        SS5      e[        ST5      (       d  [/        SU5      eTc  [1        SV5      eSSWK[J\nJ]n  SXT R                  ;   a  UnOUnT$R!                  SYT05        UT$4$ T R                  [        R                  :X  a  [        5       (       d  [1        SZ5      eSS[K`Jan  UnT$R!                  [o        T#Rq                  S\S]5      5      [o        T#Rq                  S^S_5      5      [o        T#Rq                  S`Sa5      5      [o        T#Rq                  SbSa5      5      [o        T#Rq                  ScSQ5      5      Sd.5        UT$4$ T R                  [        R                  [        R                  4;   Gay  [        5       (       aK  [d        Rf                  " [h        Rj                  Re                  Se5      5      [d        Rf                  " Sf5      :  a  [/        Sg5      e[d        Rf                  " [h        Rj                  Re                  Sh5      5      [d        Rf                  " Si5      ::  a  [/        Sj5      e[d        Rf                  " [h        Rj                  Re                  Se5      5      [d        Rf                  " Sk5      :  a	  SSlKeJfnJgn  OSSlKhJfnJgn  T R                  [        R                  :X  a  UnO,T R                  [        R                  :X  a  UnO[1        Sm5      eT$R!                  U5        UT$4$ T R                  [        R                  [        R                  [        R                  4;   GaV  [        5       (       d  [/        Sn5      e[        ST5      (       d  [/        So5      eSSpKmJnnJon   0 nSn!T R                  [        R                  :X  a(  [        Sq5      (       d  [/        Sr5      eSSsKmJpn"  U"nUnSn!OOT R                  [        R                  :X  a  UnUnO,T R                  [        R                  :X  a  U nO[1        St5      eT R                  USu'   U!(       a  T R                  USv'   UR!                  [o        T#Rq                  SwS_5      5      [o        T#Rq                  SxSy5      5      Sz.5        T$R!                  U5        UT$4$ [1        S{T R                   35      e! [.         a    [1        S5      ef = f! [.         a    [1        S5      ef = f! [.         a    [1        S5      ef = f! [.         a    [1        S35      ef = f! [.         a    [1        S?5      ef = f)}z
Returns the optimizer class and optimizer parameters based on the training arguments.

Args:
    args (`transformers.training_args.TrainingArguments`):
        The training arguments for the training session.

 r  ,=rZ  )betasepsToptimizer_nameoptimizer_mappingoptim_kwargsis_layerwise_supportedr  c                 B  >^ U R                  5       R                  S5      nU(       a4  TR                  [        R                  :X  a  U(       a  [        SU  S35      eX   nTR                  c  [        SU  S35      e[        TR                  [        [        45      (       d  [        STR                   35      eTc  [        SU  S35      e[        TR                  [        5      =(       a    TR                  R                  S	S
5      S:H  n/ nTR                  5        H  u  p[        TR                  USS9u  p[        U	[        R                  5      (       d+  U
(       a"  U(       d  [         R#                  U SU  S35        Mf  U
(       d	  U(       d  Mv  UR%                  US-   5        M     ['        U5      S:X  a  [        SU  STR                   S35      eTR)                  5        VVs/ s H  u  pX;   d  M  UPM     nnnTR)                  5        VVs/ s H  u  pX;  d  M  UPM     nnnUR+                  T5        SU0SU0UE/nU(       a  TR,                  S:w  a  [        SU  S35      e0 mU H  nU" SU/0/40 TD6TU'   M     U H  nU" SU/0UE/40 TD6TU'   M     U4S jnTR/                  5        H'  nUR0                  (       d  M  UR3                  U5        M)     [4        nTR+                  ST05        TR+                  SU05        UT4$ s  snnf s  snnf )a  
Helper function to set up low-rank optimizers like GaLore and Apollo.

Args:
    optimizer_name (str): Name of the optimizer.
    optimizer_mapping (dict): Mapping of optimizer names to their classes.
    optim_kwargs (dict): Keyword arguments for the optimizer.
    is_layerwise_supported (bool): Whether layerwise optimization is supported.

Returns:
    Tuple[Any, Any]: Optimizer class and updated optimizer kwargs.
	layerwisezLayer-wise z" does not support DDP at this timez1You need to define `optim_target_modules` to use z optimizerszX`optim_target_modules` must be a list of strings, a regex string, or 'all-linear'. Got: z'You need to pass a model to initialize z optimizer._-z
all-linearT)return_is_regexz matched but ignored. z only supports linear layers.z.weightr   zNo target modules found for z ().r  r   z
Layerwise z( does not support gradient accumulation!c                 n   > U R                   b'  TU    R                  5         TU    R                  5         g g r  )gradstep	zero_grad)r  r3  s    r   optimizer_hook^Trainer.get_optimizer_cls_and_kwargs.<locals>.setup_low_rank_optimizer.<locals>.optimizer_hook|  s4    zz-&u-224&u-779 .r   r3  )lowerendswithrI  rh   rJ  NotImplementedErroroptim_target_modulesr  r   r   r  replacenamed_modulesr[   r   Linearr  rA  appendr<  r:  updater  r   r;  "register_post_accumulate_grad_hookr@   )rh  ri  rj  rk  is_layerwiserM  
all_lineartarget_params_namesmodule_namerQ  target_module_existsis_regexrJ  rK  target_paramsnon_target_paramsr[  r  rv  r3  r   r   
optim_argsrN  s                      @r   setup_low_rank_optimizerFTrainer.get_optimizer_cls_and_kwargs.<locals>.setup_low_rank_optimizer,  sQ   $ *//1::;GL 2 2l6N6N NSi)K7GGi*jkk-=M((0 #TUcTddo!pqqd77$EE nos  pI  pI  oJ  K  } #J>JZZe!fgg 444c: P--55c3?<O 
 #%',':':'<#1K--{D2.$ "&"))44+H*m+A.AQQno +J#**;+BC (=" &'1, #??OrRVRkRkQlln!opp+0+A+A+C`+C41qG_Q+CM`/4/E/E/G h/Gtq1Kg/G h
+ ,-=9L9L
 33q8$z.1AAi%jkk!#.E,9Hug;N:O,dSc,dN5) /*E,9Hug;^Q];^:_,tcs,tN5) +:
 #--/E***@@P 0 !8 '')9>(JK##X|$<= "222A a hs   *L9LL$LF)scale_parameterrelative_stepr   )AdamWfusedz7Trainer failed to import syncfree AdamW from torch_xla.)NpuFusedAdamWz3Trainer failed to import FusedAdamW from torch_npu.)	FusedAdamzFTrainer tried to instantiate apex FusedAdam but apex is not installed!)r  LionRMSpropr9  Npaged8bitr6  adamlionrf  rmspropademamixr4  z0.44.0z{The AdEMAMix optimizer is not supported by your current version of `bitsandbytes`. Please install `bitsandbytes` >= 0.44.0.)AdEMAMixbeta1beta2beta3gH.?alphag      @rg  )rf  r  rg  t_alphat_beta3r5  is_pagedzOTrainer tried to instantiate bnb optimizer but `bitsandbytes` is not installed!z0.41.1zYou are using 8-bit optimizers with a version of `bitsandbytes` < 0.41.1. It is recommended to update your version as a major bug has been fixed in 8-bit optimizers.)AnyPrecisionAdamWuse_kahan_summationFalsemomentum_dtypefloat32variance_dtypecompensation_buffer_dtyperx  )r  r  r  r  z4Please install https://github.com/pytorch/torchdistxzYou need to install `galore_torch` in order to use GaLore optimizers install it with `pip install git+https://github.com/jiaweizzhao/GaLore`)GaLoreAdafactorGaLoreAdamWGaLoreAdamW8bitr     update_proj_gap   scaleg      ?	proj_typestd)r  r  r  r  zYou need to install `apollo_torch` in order to use APOLLO optimizers install it with `pip install git+https://github.com/zhuhanqing/APOLLO`)APOLLOAdamWprojrandom
scale_typechannel      ?)r  r  r  r  r  r  ziYou need to install `lomo_optim` in order to use LOMO optimizers install it with `pip install lomo-optim`0.30.0zGYou need to have `accelerate>=0.30.0` to be able to use LOMO optimizerszMYou need to pass a `model` in order to correctly initialize a LOMO optimizer.)AdaLomoLomoadar   z5Please install grokadamw with `pip install grokadamw`)	GrokAdamW
alpha_initg\(\?lambg       @gammag?grokking_signal_decay_rategradient_clipping)r  r  r  r  r  torchaoz0.4.0zYou need to have `torchao>=0.4.0` in order to use torch 4-bit optimizers.Install it with `pip install torchao` or follow the instructions here: https://github.com/pytorch/aor   z2.4zYou need to have `torch>2.4` in order to use torch 4-bit optimizers. Install it with `pip install --upgrade torch` it is available on pipy. Otherwise, you need to install torch nightly.z0.11.0)	AdamW4bit	AdamW8bitzInvalid optimizerzwYou need to install `schedulefree` in order to use schedulefree optimizers. Install it with `pip install schedulefree.`zOYou need to have `accelerate>=0.30.0` to be able to use schedulefree optimizers)AdamWScheduleFreeSGDScheduleFreer  zYou need to install `schedulefree>=1.4.0` in order to use RAdamScheduleFree optimizer. Install it with `pip install schedulefree.`)RAdamScheduleFreezInvalid schedulefree optimizerr1  warmup_stepsweight_lr_powerrr2  )r  r  z2Trainer cannot instantiate unsupported optimizer: T)sr  r|  splitlearning_rate
adam_beta1
adam_beta2adam_epsilonr  dictr   booltupler>  rg   	ADAFACTORr.   r  ADAMW_TORCHADAMW_TORCH_FUSEDtorch.optimr  ADAMW_TORCH_XLAtorch_xla.amp.syncfreerB  r  ADAMW_TORCH_NPU_FUSEDtorch_npu.optimr  ADAMW_APEX_FUSEDapex.optimizersr  	ADAMW_BNB
ADAMW_8BITPAGED_ADAMWPAGED_ADAMW_8BITADEMAMIXADEMAMIX_8BITPAGED_ADEMAMIXPAGED_ADEMAMIX_8BITLION	LION_8BIT
PAGED_LIONPAGED_LION_8BITRMSPROP_BNBRMSPROP_8BITRMSPROP_32BITbitsandbytes.optimr  r  r{   r   r   r   r   r  floatr  intr  rA  ADAMW_ANYPRECISIONtorchdistx.optimizersr  r   r8  r   SGDADAGRADAdagradRMSPROPGALORE_ADAMWGALORE_ADAMW_8BITGALORE_ADAFACTORGALORE_ADAMW_LAYERWISEGALORE_ADAMW_8BIT_LAYERWISEGALORE_ADAFACTOR_LAYERWISEr}   galore_torchr  r  r  r=  APOLLO_ADAMWAPOLLO_ADAMW_LAYERWISErz   apollo_torchr  LOMOADALOMOr   rx   
lomo_optimr  r  	GROKADAMWr~   	grokadamwr  ADAMW_TORCH_4BITADAMW_TORCH_8BITr   torchao.optimr  r  torchao.prototype.low_bit_optimSCHEDULE_FREE_RADAMSCHEDULE_FREE_ADAMWSCHEDULE_FREE_SGDr   schedulefreer  r  r  r1  r  )%r   r   mappingkeyvalueadam_kwargsr  rM  r  r  r  r  r  r  r5  additional_optim_kwargsr  
bnb_kwargsr  r  r  r  ri  galore_optim_kwargsr  apollo_optim_kwargsr  r  r  r  r  r  r  require_warmupr  r  rN  s%   ``                                 @@r   r<  $Trainer.get_optimizer_cls_and_kwargs  s    
????223;AA#F$]]3/
"'
3 G !$"4"45 oot7$$
 ,0	]	3]	3#CH~]	3 sCx.]	3 %)	]	3
 38_]	3 ]	3~ ::111%M##PU$VWx	 ...w	 ZZN668X8XYY)!M##K0zz^=== ''$8j	 ...i	 ZZ>999\8 % ''4^	 ...Y	 ZZ>???X9 - ''4N	 ...I	 ZZ>:::k5 ) ''4~ ...y ZZ$$%%&&++##(())..$$%%**&&''((
 
"8tCC 
 $*5'djj(#HTZZ'!"JTZZ'$)Mtzz)$(M/6$//8Z.[+$**,$+M /9+4::-022w}}!**22>B8h/80 )G 
 <$,M "*..$//"JK!*..$//"JK!*..&"AB"
 "'z~~gs'C!D$Z^^E4;L;L%MN/+ !J.=@IAV=W/	: J.=@IAV=W/	:*J7
DJJ.-5Jz* ''(?@ ''
3 )**w}}""**>:0h'0( r^ ...W ZZ><<<YC 1 ''4 !''/8H]_f9g/h*1%HXZc9d*e*1%HXZc9d*e5<!:>>2Mz#Z6		F ...o ZZ>---!KKOOMl ...k ZZ>111!KK//Mh ...g ZZ>111!KK//Md ...c ZZ'',,++116655
 
 -..!_  SR ++[00///55{::O99?! JNN6378#&z~~6G'M#Nz~~gt<='^^K?	# /G

-/B/+M+ zz^<<< ''ETY(Z[\ ...[ ZZ''11
 
 -..!^  1 ++[55{! JNN6378"vx8(nn\9E#&z~~6G'M#Nz~~gs;<'^^K?#  &&{3.F

-/B/+M+f ...a ZZN//1G1GHH$&&!@  +844!"kll} !pqq0

" ' $##We$45z ...y ZZ>333)++ !XYY+%M##"'
|T(J"K!*.."=>":>>'3#?@27
Gceh8i2j).z~~>QSV/W)Xj ...Y ZZ++++
 
 ())W]]9;M;M;U;UV_;`-adkdqdqe . "{  }}Y//77@AW]]SXEYY!K  }}Y//77	BCw}}U]G^^>>Pzz^<<< )~>>> ) !455##K0b ...a ZZ....,,
 

 -..!B  +844!"sttG&(#!Nzz^???099%F  ; 1*5'!&~AAA 1*5'~??? / !ABB6:6G6G#N3:>:K:K'7#**',Z^^<Ms-S'Tz~~c378 ##$;< ... QRVR\R\Q]^__[	  \ !Z[[\  X !VWWX  k !ijjkT  t !rsst6  Y !WXXYs>   ?{ ;{6 7| H|( 2B"} {36||%(|>}rY  c                    U R                   ci  [        U R                  R                  Uc  U R                  OUU R                  R                  U5      UU R                  R                  S9U l         SU l        U R                   $ )z
Setup the scheduler. The optimizer of the trainer must have been set up either before this method is called or
passed as an argument.

Args:
    num_training_steps (int): The number of training steps to do.
)rY  num_warmup_stepsr"  scheduler_specific_kwargsT)rZ  r/   r   lr_scheduler_typerY  get_warmup_stepslr_scheduler_kwargsr  r&  s      r   r%  Trainer.create_scheduler  sq     $ -		++,5,=$..9!%!;!;<N!O#5*.))*G*G!D *.D&   r   r  c                 (    UR                   n[        U[        5      (       a  [        UR                   R                   5      $ [        UR                   5      $ ! [        [
        [        4 a%    [        U5      U R                  R                  -  s $ f = f)z
Helper to get number of samples in a [`~torch.utils.data.DataLoader`] by accessing its dataset. When
dataloader.dataset does not exist or has no length, estimates as best it can
)	r  r   r>   r<  	NameErrorAttributeError	TypeErrorr   per_device_train_batch_size)r  r  r  s      r   num_examplesTrainer.num_examples  sz    
	K ((G'#788:--5566z))**>95 	Kz?TYY%J%JJJ	Ks   ?A A 7BBtrain_dlrj  c                     Sn U  H#  nUS   R                  5       nUb  XA-  s  $ X$-  nM%     U$ ! [         a    [        R                  S5         U$ f = f)za
Helper to get number of tokens in a [`~torch.utils.data.DataLoader`] by enumerating dataloader.
r   	input_idsz%Cannot get num_tokens from dataloader)rE  KeyErrorr  rA  )r&  rj  train_tokensbatchtokenss        r   
num_tokensTrainer.num_tokens  sq    
 	D!{+113(!--&	 "   	DNNBC	Ds    / / AAtrialzoptuna.Trialc           	         Xl         U R                  b  Uc  gU R                  [        R                  :X  a  U R	                  U5      nOU R                  [        R
                  :X  a  UnUR                  SS5        OU R                  [        R                  :X  aP  UR                  R                  5        VVs0 s H(  u  p4U[        U[        5      (       a  [        U5      OU_M*     nnnO U R                  [        R                  :X  a  UnWR                  5        H|  u  pV[        U R                  U5      (       d  [         R#                  SU S35        M;  [%        U R                  US5      nUb  ['        U5      " U5      n[)        U R                  XV5        M~     U R                  [        R                  :X  a"  [         R+                  SUR,                   35        U R                  [        R                  :X  a"  [         R+                  SUR                   35        U R                  [        R                  :X  a  [         R+                  SU 35        U R.                  (       a  U R                  R0                  c  [3        S5      eU R4                  R7                  5         S	S
KJn  S	SKJn	  U	" U R                  R0                  5      U R                  l         U R                  R@                  RC                  U R                  5        U" U R                  R@                  S9U R                  l"        [G        5       RI                  5         U RK                  5         gs  snnf )zHP search setup codeNwandbzTrying to set zY in the hyperparameter search but there is no corresponding field in `TrainingArguments`.zTrial: zSigOpt Assignments: zW&B Sweep parameters: z7For sweeps with deepspeed, `args.deepspeed` must be setr   )DeepSpeedPluginHfTrainerDeepSpeedConfig)hf_ds_config)&_trialr~  rT   OPTUNAhp_spaceRAYr=  SIGOPTassignmentsitemsr   r  r  WANDBr@  r   r  rA  r8  r   setattrr  r  rH  r(  r  rT  free_memoryaccelerate.utilsr2  #transformers.integrations.deepspeedr4  hf_deepspeed_configtrainer_config_processdeepspeed_pluginr   _reset_stater*  )
r  r/  r  r  vr  r  old_attrr2  r4  s
             r   _hp_search_setupTrainer._hp_search_setup  s   !!)U]!!_%;%;;]]5)F##':'::FJJw%##'='==INIZIZI`I`IbcIba:a#5#5Q1<IbFcF##'<'<<F ,,.JC499c**$SE *, , tyy#t4H#Xu-DIIs* ) !!_%;%;;KK'%,,01!!_%;%;;KK.u/@/@.ABC!!_%:%::KK089$$yy""* !Z[[((* 9T,DTYYEXEX,YDII)II))@@K)8diiFcFc)dDII& ++-//1U ds   6/Mrt  metricsc                    U R                   b  Uc  g UR                  5       nU R                  U5      U l        U R                   [        R
                  :X  a  SS Kn[        US5      (       a  UR                  R                  5       (       d~  UR                  U R                  U5        UR                  5       (       aL  U R                  R                  U R                  U R                  U R                   5        UR"                  " 5       eg g g U R                   [        R$                  :X  a  SS Kn[(        R*                  " 5        nS nU R                   R,                  (       a4  U R/                  US9  UR0                  R2                  R5                  U5      nU R                  US'   UR0                  R                  X7S9  S S S 5        g g ! , (       d  f       g = f)Nr   study)checkpoint_dir	objective)
checkpoint)r~  copycompute_objectiverN  rT   r7  optunar@  rL  _is_multi_objectivereportshould_pruner^  on_train_endr   ru  r|  TrialPrunedr9  	ray.traintempfileTemporaryDirectoryrf  _tune_save_checkpointtrain
Checkpointfrom_directory)r  r/  rt  rJ  rR  raytemp_checkpoint_dirrO  s           r   _report_to_hp_searchTrainer._report_to_hp_search4  sj   !!)U],,.//8!!_%;%;;ug&&u{{/N/N/P/PT^^T2%%''))66tyy$**dll[ ,,.. ( 0Q&
 ##':'::,,.2E!
<<++..>Q.R!$!5!5!D!DEX!YJ'+~~$		   @ /. ; /.s   A:G
GrM  c                    [         R                  R                  U[         SU R                  R
                   35      nU R                  USS9  U R                  R                  (       Ga  U R                  R	                  5       U R                  R                  S'   U R                  R                  [         R                  R                  U[        5      5        [        R                  " U R                  R!                  5       [         R                  R                  U["        5      5        [        R                  " U R$                  R!                  5       [         R                  R                  U[&        5      5        g g )Nro  T_internal_callr:   )rg  pathr  rP   ru  global_step
save_modelr   rf  r|  r  save_to_jsonTRAINER_STATE_NAMEr   saverY  
state_dictOPTIMIZER_NAMErZ  SCHEDULER_NAME)r  rM  r   s      r   r[  Trainer._tune_save_checkpointL  s    WW\\.5J4K1TZZMcMcLd2ef

4899   >Bll>P>P>RDJJ))*:;JJ##BGGLL=O$PQJJt~~002BGGLL^4\]JJt((335rww||JP^7_` !r   c                     [        U R                  5      nUS:X  a  U R                  5       nO#US:X  a  U R                  U5      nO[        S5      eUc  [        S5      eU$ )Nr   r   z'model_init should have 0 or 1 argument.z"model_init should not return None.)rc   r   r2  )r  r/  model_init_argcountr   s       r   r1  Trainer.call_model_initV  s]    1$//B!#OO%E A%OOE*EHII=CDDr   c                 >   U(       Gd  Uc  [         R                  S5        U$ [        [        U5      5      nU R	                  U5      n [
        R
                  " U5      nUR                  5         UR                  R                  SS 5      nU(       a  Xel	        [        SS9nU R                  R                  US9   [        R                  " 5          [        U[         5      (       a  [        R"                  R%                  XTSS9nO2[        R"                  R%                  UU Vs0 s H  oXH   _M	     snSS9nS S S 5        S S S 5        [        R"                  R'                  U5      n[        R                  " 5          U" S	0 UD6  U" S	0 UD6  S S S 5        UnSU l        U$ U$ s  snf ! , (       d  f       Nu= f! , (       d  f       N~= f! , (       d  f       NB= f! [*        [,        [.        [0        [2        4 a$  n	[         R                  SU	 S35         S n	A	U$ S n	A	ff = f)
NzAfailed to use PyTorch jit mode due to current dataloader is none._original_forwardF)cache_enabled)autocast_handler)example_kwarg_inputsstrictz'failed to use PyTorch jit mode due to: .r   )r  rA  nextiter_prepare_inputsrP  r  __dict__r=  rU  r   rT  autocastr   no_gradr   r  jittracefreezerq  r2  r"  r  r   
IndexError)
r  r   r  trainingexample_batch	jit_modeloriginal_forwardrv  r  es
             r   torch_jit_model_evalTrainer.torch_jit_model_evald  s   !bc j!12M 00?MO IIe,	 #,#5#5#9#9:Mt#T #(8%#1#F %%..@P.QSXS`S`Sb!-66$)IIOOIjoO$p	$)IIOO%Ub1cUbc}7I2IUb1c#( %4 %		 TcQ "II,,Y7	]]_.... % "#(  u 2d TcSbQQ %_
 !)ZJO O!H1MNNOst   	A1G :F7AF&#F!1F&7F7?<G ;GG !F&&
F4	0F77
GG 
GG H8HHc                    [        5       (       d  [        S5      eSS KnU(       dq  UR                  5         U R                  (       d+  U R
                  R                  (       a  [        R                  OUnUR                  XSSU R                  (       + S9nU$ UR                  (       d  UR                  5         UR                  XU R                  SSS9u  ol        U$ )NzUsing IPEX but IPEX is not installed or IPEX's version does not match current PyTorch, please refer to https://github.com/intel/intel-extension-for-pytorch.r   O1F)r   levelconv_bn_foldinginplaceT)r   rY  r  r  )r   rB  intel_extension_for_pytorchr  r)  r   rM  r   rx  optimizer  r\  rY  )r  r   r  r   ipexs        r   ipex_optimize_modelTrainer.ipex_optimize_model  s     ""L 
 	3JJL*.*:*:tyy?W?WENN]bEMM%DRWeieueuauMvE  >>$(MMdnndRV %2 %!E> r   c           	      |   SSSS.nSnSnUR                  5        H?  u  pg[        XS 5      n[        X'S 5      n	Uc  M"  U	c  M'  X:w  d  M.  USU SU S	U	 S
3-  nSnMA     UR                  n
UR                  [	        SUR
                  5      -  nX:w  a  USU
 S	U S
3-  nSnU(       a  [        R                  U5        g g )Nlogging_steps
eval_steps
save_steps)r  r  r  FztWarning: The following arguments do not match the ones in the `trainer_state.json` within the checkpoint directory: z
	r7  z (from args) != z (from trainer_state.json)Tr   z
	per_device_train_batch_size: )r<  r8  r#  r  maxn_gpur  warning_once)r  training_argstrainer_stateattributes_maphas_warningwarning_strarg_attr
state_attr	arg_valuestate_valuetrain_bs_argstrain_bs_states               r   #compare_trainer_and_checkpoint_args+Trainer.compare_trainer_and_checkpoint_args  s    ,&&
  M$2$8$8$: H>I!-TBK$)@YE]hZr)<L[MYstt" %; &AA&773q-BUBU;VV*>}oM]^l]m  nH  I  IKK, r   c                 
  ^ ^^^ T R                   R                  (       aA  T R                  (       a  [        R                  O[        R
                  nT R                  XUS9n[        5       (       ah  [        T R                  [        R                  R                  5      (       a  T R                  $ [        R                  " UT R                   R                  S9$ T R                  R                  USS9ULa  U$ T R                   (       aC  U(       a<  ["        R$                  " UT R&                  T R                   R(                  S9u  nT l        T R                   R*                  S:  a(  [-        USS5      (       d  [.        R0                  " U5      nT R                   R2                  (       aN  [4        R4                  " 5       nT R7                  XU5      n[9        [4        R4                  " 5       U-
  S5      T l        U(       d  U$ T R<                  (       Ga   S	S
KJ m  S	SKJ!m  S	SK"J#nJ$n  T RJ                  (       a  S	SK&J'm  S nS n	[-        USS 5      n
T R                   RR                  RU                  SU
5      nT R                   RR                  S   S	:  a-  [V        RX                  " UT R                   RR                  S   S9nOUUbR  [[        5       nU H-  n[]        X5      nUc  [_        S5      eURa                  U5        M/     [V        RX                  " UUS9nT R                   Rb                  nT R                   RR                  S   (       aJ  URd                  Rf                  (       a&  [h        Rk                  S5        SURd                  l3        UUUU 4S jn	T RJ                  (       a  S nT" UUUU	S9=T l        nOT" U4UU	S.UD6=T l        nS0 4S jnU[l        l7        U$ [q        5       (       a>  [.        Rr                  Ru                  U[w        [x        Rz                  " S5      5      /S9nU$ T R                   R|                  [~        R                  :X  a  [        5       (       a  U$ 0 nT R                   R                  b  T R                   R                  US'   O/[        U[        5      (       a  UR                  (       + US'   OSUS'   T R                   R                  b  T R                   R                  US '   T R                   R                  b  T R                   R                  US!'   [        S"0 UD6T R                  lH        U$ ! [P         a    [Q        S5      ef = f)#N)r   )backward_passes_per_stepFkeep_torch_compile)	opt_levelr   is_loaded_in_8bit   r   )XlaFullyShardedDataParallel)checkpoint_module)size_based_auto_wrap_policytransformer_auto_wrap_policy)SpmdFullyShardedDataParallelzJMissing XLA FSDP related module; please make sure to use torch-xla >= 2.0._no_split_modulestransformer_layer_cls_to_wrapmin_num_params)r  z@Could not find the transformer layer class to wrap in the model.)transformer_layer_clsxla_fsdp_grad_ckptzX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.c                 R   > TR                   (       d  TOTnU" T" U 5      /UQ70 UD6$ r  )r  )mr   kwargs
target_clsFSDPFSDPv2r  r  s       r   auto_wrapper_callable2Trainer._wrap_model.<locals>.auto_wrapper_callable  s-    -1-H-HfJ%&7&:LTLVLLr   c                    SSK Jn  S n[        U [        R                  5      (       a  U nO7[        U [
        5      (       a  U S   nO[        X5      (       a  U R                  nUc  [        S5      e[        R                  " X1S5        g )Nr   )CausalLMOutputWithPastr   zASomething went wrong, the output of the model shouldn't be `None`)r  NN)
modeling_outputsr  r   r   Tensorr  logitsr  r  mark_sharding)outputmeshr  real_outputs       r   shard_output)Trainer._wrap_model.<locals>.shard_output  sm    H"&K!&%,,77&,#FE22&,Qi#FCC&,mm"*()lmm$$[8LMr   )r  auto_wrap_policyr  )r  r  c                 b    U R                   " S0 UD6nU(       a  [        R                  " 5         U$ )Nr   )rt  xm	mark_step)rY  barrieroptimizer_argslosss       r   patched_optimizer_step3Trainer._wrap_model.<locals>.patched_optimizer_step4  s$     ~~77LLNr   SMDATAPARALLEL_LOCAL_RANK)
device_idsfind_unused_parametersTbucket_cap_mbbroadcast_buffersr   )Ir   use_ipexrq  r   rx  r  r  r   r   rS  rt  r   DistributedModelr  rT  r+   rp  r   
initializerY  fp16_opt_levelr  r8  r   DataParalleljit_mode_evaltimer  roundjit_compilation_timerG  torch_xla.distributed.fsdpr  r  torch_xla.distributed.fsdp.wrapr  r  r  7torch_xla.experimental.spmd_fully_sharded_data_parallelr  rB  rF  r  	functoolsr   r:  rG   	Exceptionaddxla_fsdp_configconfig	use_cacher  r  r  optimizer_stepr   parallelDistributedDataParallelr  rg  getenvrI  rh   rJ  r   ddp_find_unused_parametersr)   is_gradient_checkpointingddp_bucket_cap_mbddp_broadcast_buffersr   ddp_handler)r  r   r  r  r   
start_timer  r  r  r  %default_transformer_cls_names_to_wrap"fsdp_transformer_layer_cls_to_wraptransformer_cls_to_wraplayer_classtransformer_clsfsdp_kwargsr  r  r  r  r  r  s   `                  @@@r   _wrap_modelTrainer._wrap_model  s   99&*&6&6ENNEMME,,UE,JE"$$$,,cii.H.HII)))''		HmHmnn ((5(IQVVL ==X$'NN5$..TXT]T]TlTl$m!E4> 99??Qwu6I5'Q'QOOE*E99""J--eJE(-diikJ.F(JD% L ###pZH
 ..
  $$(!4;ECVX\4]1151F1F1J1J/1V2. yy$$%56:#,#4#4/		@U@UVf@g$  4?*-%'#EK&@&TO&.'(jkk/33OD $F $-#4#40*A$ 
 ))33Kyy$$%9:<<))''r .3ELL*M M
 **N &,!-%5*?	& 
U &*&%5*?& "	& 
U ;@PR  !7B4 3 %&&KK773ryy1L'M#N"O 8 E0 + YY$$(@(@@,..Fyy33?37993W3W/0E?33 8=7V7V3V/037/0yy**6*.))*E*E'yy..:.2ii.M.M*++H+R6+RD(U  p!"noops   +U Uresume_from_checkpointignore_keys_for_evalc           	         USL a  SnU R                   R                  5         U R                  nSU l        U R                  b   U R                  U R                  5      U l        UR                  (       d  UR                  (       aU  UR                  (       dD  U R                  (       d3  U R                  c&  U R                  U R                  UR                  5        SU;   a,  UR                  S5      n[        R                   " S["        5        [%        U5      S:  a5  ['        SSR)                  [+        UR-                  5       5      5       S	35      eU R/                  U5        U R                  R0                  U l        SnU R                  b  U R                  R4                  (       a  [7        U R                  R8                  5      O[;        U R                  R8                  5        U R=                  U5      U l        SnS
u  U l        U l         [C        U[D        5      (       a8  U(       a1  [G        URH                  5      nUc  [K        SURH                   S35      eUb  [M        5       (       d3  U RN                  (       d"  U RP                  (       d  U RS                  U5        [T        RV                  " [X        RZ                  R)                  U[\        5      5      nUR0                  b  UR0                  U l        U(       aH  U R^                  (       a&  U R                  U R                  UR                  5        U R                  U l0        [c        U Rd                  U R2                  URf                  5      nURh                  (       a4   [j        Rl                  " 5         U" UUUUS9[j        Rn                  " 5         $ U" UUUUS9$ ! [j        Rn                  " 5         f = f)a  
Main training entry point.

Args:
    resume_from_checkpoint (`str` or `bool`, *optional*):
        If a `str`, local path to a saved checkpoint as saved by a previous instance of [`Trainer`]. If a
        `bool` and equals `True`, load the last checkpoint in *args.output_dir* as saved by a previous instance
        of [`Trainer`]. If present, training will resume from the model/optimizer/scheduler states loaded here.
    trial (`optuna.Trial` or `Dict[str, Any]`, *optional*):
        The trial run or the hyperparameter dictionary for hyperparameter search.
    ignore_keys_for_eval (`List[str]`, *optional*)
        A list of keys in the output of your model (if it is a dictionary) that should be ignored when
        gathering predictions for evaluation during the training.
    kwargs (`Dict[str, Any]`, *optional*):
        Additional keyword arguments used to hide deprecated arguments
FNT
model_pathzi`model_path` is deprecated and will be removed in a future version. Use `resume_from_checkpoint` instead.r   z*train() got unexpected keyword arguments: r  ry  r   z/No valid checkpoint found in output directory ())r   r  r/  r   )8r,  r-  r   r)  rX  r  r   rL  rM  rN  r9  r   rQ  r=  r=  r3  r4  r5  r<  r"  r  r   r  rH  r  r  r%  r^   r&  re   r1  rY  rZ  r   r  r`   r   r  r   rH  rO  _load_from_checkpointr;   load_from_jsonrg  rf  rj  rK  rS  r_   _inner_training_loopauto_find_batch_sizerd  hf_hub_utilsdisable_progress_barsenable_progress_bars)	r  r  r/  r   r  r   model_reloadedru  inner_training_loops	            r   r\  Trainer.trainV  s   . "U*%)" 	""$yy ##///

;DJ
   D$7$7MM**'&&tzz4;;?6!%+ZZ%="MM
 v;?HSWX^XcXcXeSfIgHhhijkke$!%!;!; ??&7;yy7Q7Q#DIINN3W_`d`i`i`n`nWo--e4DJ!N0:-DND- ,d338N%8%I"%- #RSWSbSbRccd!eff!-*,,T5N5NW[WkWk**+AB //=SUg0hiE%%1).)?)?& ))**4::t{{C!%D8%%t'='=t?X?X
 
4224*+A)=	 113&'=%9	  113s   >N: :Oc                 2   U R                   R                  5         Xl        U R                  R                  (       a  U R
                  R                  U R                  :w  a  SSKJn  U" U R                  5      u  U l	        U R                  U l	        U R                  (       as  U R                  R                  nU R                  [        SU R                  R                  5      -  U R                  l        U R                  S5        XpR                  l        U R                  U R
                  l        [         R#                  SU R                   35        U R%                  5       nU R&                  (       a  [)        U5      nU R                  UR*                  -  UR,                  -  n	U R/                  X(U	5      u  n
nnnnnnS nU R                  R0                  (       aC  U R3                  X(       a  S OU5      nUb  U(       a  UUR4                  -  nOUUR*                  -  n[6        R8                  U R                  R"                  ;   a:  U R                  R                  S:  a  [;        S5      e[=        U R                  5      n[?        5       =(       d    U R@                  =(       d    U RB                  nU RB                  =(       a.    [E        U R                   R
                  RF                  SS5      S:H  nU(       a  S	nU RH                  (       a  S U l%        S	U l$        U R                  (       a  [M        U US
9u  U l'        U l%        U(       d  U RQ                  US
9  [S        U RT                  RV                  U RX                  /-    Vs/ s H  n[[        U[\        5      (       d  M  UPM     snS9U l        US LU R
                  l/        U R                  U R
                  l        U R
                  Ra                  UU5        URb                  (       a#  U R                  Re                  URf                  S9  U Ri                  U R                  5      nUU R                  L a  SOS	nU(       a*  U RB                  (       a  [k        U R                  SS9U l
        U(       aj  U(       aT  U Rm                  5         U R                   Rn                  S:w  a*  U R                   Rq                  U R                  5      U l
        U RQ                  US
9  U(       a  U R                  Rs                  5         [u        U RJ                  S5      (       ap  U Rv                  (       a&  U R                   Rq                  U R                  5      nOU R                   Rq                  U R                  U RN                  5      u  nU l'        OU R                   Rq                  U R                  U RN                  U RJ                  5      u  nU l'        U l%        ObU R                  Rx                  [z        R|                  [z        R~                  4;   a*  U R                   Rq                  U RN                  5      U l'        U RB                  (       a  U=U l
        U l	        UU R                  La  UU l	        U R                  (       a  U R                  U l@        Ubz  U R                  (       a.  [        U R                  U[        U R                  5      (       + S9  O;[?        5       (       d  U RB                  (       a  U R                  X0R                  5        U R                  U5        U R                  U5        [         R                  S5        [         R                  SUS 35        [         R                  SU
S 35        [         R                  SU R                  R                  S 35        U R                  R                  U R                  :w  a#  [         R                  SU R                  S 35        [         R                  SU	S 35        [         R                  SUR*                   35        [         R                  SUS 35        [         R                  S[        USS9S 35        SU R
                  lH        [        R                  " 5       nSnSnS nUGb  [        R                  R                  [        R                  R                  U[        5      5      (       GaW  [R        R                  " [        R                  R                  U[        5      5      U l        U R                  U R                  U R
                  5        U R                  5         [        U R
                  R                  U-  5      nUR                  (       d)  U R
                  R                  U-  nUUR*                  -  nOSn[         R                  S5        [         R                  SU 35        [         R                  SU R
                  R                   35        UR                  (       d  [         R                  SU S U S!35        S" H$  n[        U RT                  U[E        U U5      5        M&     XRT                  lV        U R
                  R                  U UX5        [        R                  " S#UR                  S$9nS#U l[        U R
                  R                  U l\        UR                  5         S nS nU RT                  R                  X R
                  U RX                  5      U l,        UR                  (       a  U R                  XESS%9  [        UU
5       G
H}  n Un![u        U!S&5      (       a  U!R                  U 5        UR                  S:  a  S U ld        Ub  [        U!5      OUR                  UR*                  -  n"U RT                  R                  X R
                  U RX                  5      U l,        U U:X  a  Ub  US:X  a  U R                  U5        S	n#Sn$US:  a  [        U!U5      n!Un$SnSn#S'n%[        U!5      n&U"UR*                  -  n'U'S:X  a  UR*                  n'S'n(U"UR*                  -  [        U'UR*                  :  5      -   n)[        U)5       GH  n*U(S-  n(U(U)S-
  :w  a  UR*                  OU'n+U R                  U&U+UR                  5      u  n,n-[        U,5       GH_  u  n.n/U%S-  n%U%S-   UR*                  -  S:H  =(       d    U%S-   U":H  n0U R                   R                  R                  U05        U R                  R                  (       a  [E        U R                  S(S)5      n1U1U/;  a  [         R                  S*5        OU/U1   R                  5       n2[        R                  " U2U R                  R                  [        R                  S+9n2U R
                  =R                  U R                   R                  U25      R                  5       R                  5       -  sls        U#(       a  U R                  U5        S	n#US:  a3  US-  nUb  UR                  S5        US:X  a  U R                  U5        GM  Ub  UR                  5         S nU%UR*                  -  S:X  a5  U RT                  R                  X R
                  U RX                  5      U l,        U.[        U,5      S-
  :w  aQ  U R                   R                  [        R                  :w  a)  [        R                  " U R                   R                  US,9OG[         GR                  n3U3" 5          U GR                  UU/U-5      n4S S S 5        UGR                  (       au  G[	        5       (       de  [        GR
                  " W45      (       d  [        GR                  " U45      (       a-  UUSU R
                  R                  -   U R                  -
  -  -   nODUR                  W4R                  :w  a%  [;        S-UR                   S.U4R                   35      eUU4-   nU =GR                  G[        U GR                  U/5      5      -  sl        U0(       Ga:  U R                   R                  R                  S5        UGR                  Gb_  UGR                  S:  GaM  [?        5       (       a:  UGR                  (       a(  U RN                  GR                  UGR                  5      n5OU Rv                  (       aO  G[        GR                  GR                  G[         GR"                  " U RN                  5      UGR                  5      n5O7U R                   GR                  UGR%                  5       UGR                  5      n5G['        5       (       a[  U R                   R                  [        R                  :X  a3  UGR)                  5       n[u        US/5      (       a  UR                  5       nOU5nU RT                  GR+                  X R
                  U RX                  5      U l,        U RN                  GR-                  5         U RT                  GR/                  X R
                  U RX                  5      U l,        U GR1                  5       nU R                   GR2                  (       dY  [[        U RJ                  [        Rx                  RJ                  GR4                  5      (       d  U RJ                  GR-                  5         UR                  5         U R
                  =R                  S-  slS        U U%S-   U$-   U"-  -   U R
                  lH        U RT                  GR7                  X R
                  U RX                  5      U l,        U GR9                  UUUUU UUUS09  O6U RT                  GR;                  X R
                  U RX                  5      U l,        U RX                  GR<                  (       d  U RX                  GR>                  (       d  GM9  G[	        5       (       a  G[@        GRB                  " 5           O   U RX                  GR<                  (       d  U RX                  GR>                  (       d  GM  G[	        5       (       a  G[@        GRB                  " 5           O   U%S:  aA  [         R                  S1U R
                  R                   S2U S335        SU RX                  l        U RT                  GRE                  X R
                  U RX                  5      U l,        U GR9                  UUUUU UUUS09  [6        GRF                  U R                  R"                  ;   aS  G[	        5       (       a.  G[@        GRH                  " G[J        GRL                  " 5       5        O[         R                  S45        U RX                  GR>                  (       d  G
M~    O   UR                  (       a  [u        U S55      (       a  G[O        U S55        [         R                  S65        UGRP                  (       a  U R
                  GRR                  b  G[	        5       (       a  G[@        GRT                  " S75        O_UGRV                  G[X        GRZ                  :X  a  G[\        GR^                  " 5         O&[?        5       (       a  G[`        GR^                  " 5         U GRc                  5         U =R                  UR                  5       -  sl[        [        U R
                  R                  S85      n6U R                  U6-  n7G[e        S9UUU R
                  R                  US:9n8U GRg                  5         U R
                  GRh                  U8S;'   U7U8S<'   S	U l        U GRl                  GRo                  U85        U GRq                  U85        U GRs                  U5      n9U GRu                  S	U9S=9n:U R                  GRv                  (       a  U R
                  GRR                  b  U R                  GRx                  S:X  av  U: Hp  n;[        R                  GR{                  U;U R
                  GRR                  5      (       a  M@  [         R                  S>U; S?35        G[|        GR~                  " U;SS@9  Mr     U RT                  GR                  X R
                  U RX                  5      U l,        U GR                  5         U GR                  b  U GR                  U R                  5        G[        U R
                  R                  U7U85      $ s  snf ! , (       d  f       G	N= f)ANr   )release_memoryr   Tz)Currently training with a batch size of: zCurrently --debug underflow_overflow is not supported under DP. Please use DDP (torchrun or torch.distributed.launch (deprecated)).fsdp_version   F)r"  )r  )gradient_checkpointing_kwargs)	recursivefp8rt  load_module_strictz***** Running training *****  Num examples = rd  z  Num Epochs = z(  Instantaneous batch size per device = zA  Training with DataParallel so batch size has been adjusted to: zE  Total train batch size (w. parallel, distributed & accumulation) = z   Gradient Accumulation steps = z  Total optimization steps = z#  Number of trainable parameters = )trainable_onlyzE  Continuing training from checkpoint, will skip to saved global_stepz!  Continuing training from epoch z'  Continuing training from global step z  Will skip the first z epochs then the first z batches in the first epoch.)r   rY  rZ  r2  r=  )skip_scheduler	set_epochmain_input_namer(  zTried to track the number of tokens seen, however the current model is not configured properly to know what item is the input. To fix this, add a `main_input_name` attribute to the model class you are using.)r=  r   r   z0Calculated loss must be on the original device: z but device in use is item)r  zXThere seems not to be a single sample in your epoch_iterator, stopping training at step zI! This is expected if you're using an IterableDataset and set num_steps (z.) higher than the number of available samples.zYou enabled PyTorch/XLA debug metrics but you don't have a TPU configured. Check your training configuration if this is unexpected._pastzU

Training completed. Do not forget to share your model on huggingface.co/models =)

r#  gMbP?r\  )num_samples	num_stepsr-  
total_flos
train_loss	use_mtimer   Deleting older checkpoint [] due to args.save_total_limitignore_errors)rT  r?  r  r   r  ru  r  r@  r  rS  r   rH  r#  r  r  propagate_args_to_deepspeedr  rG  r
  r  r'   r  r  set_initial_training_valuesinclude_tokens_per_secondr-  rk  r   UNDERFLOW_OVERFLOWr  r   r   rG  rO  r8  fsdp_pluginr  rZ  r$   rY  r'  r;   r^  r   r|  r   r6   is_hyper_param_searchcompute_stepsgradient_checkpointinggradient_checkpointing_enabler  r  r+   _fsdp_qlora_plugin_updatesmixed_precisionr  r\  r@  rp  r>  rg   r  r  r(  r%   r   r  _load_optimizer_and_scheduler_load_scalerr  rF   epochr  rg  rf  isfiler  rj  r  r  _load_callback_stater  rg  ignore_data_skipr>  train_dataloaderinit_training_referencesr   r  r=  _total_loss_scalar_globalstep_last_loggedru  on_train_begineval_on_start	_evaluater  r  
past_indexr  r<  rj  on_epoch_begin_load_rng_stater   r{  get_batch_samples	enumerategradient_state_set_sync_gradientsinclude_num_input_tokens_seenrA  rE  int64num_input_tokens_seengatherrC  r  r  closeon_step_begindistributed_typer   	DEEPSPEEDr  r   no_syncr   r   training_steplogging_nan_inf_filterr   isnanisinfr}  r  floating_point_opsmax_grad_normr  clip_master_gradsr   rl  clip_grad_norm_r   master_paramsr   rx   get_global_grad_normon_pre_optimizer_steprt  on_optimizer_stepr   optimizer_step_was_skippedReduceLROnPlateauon_step_end_maybe_log_save_evaluateon_substep_endshould_epoch_stopshould_training_stopr  r  on_epoch_endTPU_METRICS_DEBUGmaster_printmetmetrics_reportdelattrr#  best_model_checkpoint
rendezvousrI  rh   rJ  distr  rt  _load_best_modelrf   
store_flosr"  r)  r,  r  log_get_output_dir_sorted_checkpointsrf  save_total_limitsamefileshutilrmtreerV  _finish_current_pushrX  r  rZ   )<r  r  r   r  r/  r   r  original_bsr;  total_train_batch_sizerk  num_update_steps_per_epochr$  num_train_samplesepoch_basedlen_dataloaderrj  num_train_tokensdebug_overflowdelay_optimizer_creationis_fsdp2r  r   use_accelerator_preparer  epochs_trainedsteps_trained_in_current_epochsteps_trained_progress_barattrtr_loss	grad_normr  r7  epoch_dataloadersteps_in_epochrng_to_syncsteps_skippedrt  epoch_iterator	remainderupdate_steptotal_updatesrn  num_batchesbatch_samplesnum_items_in_batchiinputsdo_sync_stepr  input_tokenscontexttr_loss_step
_grad_normeffective_global_stepr#  rJ  run_dircheckpoints_sortedrO  s<                                                               r   r  Trainer._inner_training_loop  s     	$$&!+99))zz**d.D.DD;(6t7I7I(J%#%)ZZ" ,,"&))"G"GK<@<R<RVYZ[]a]f]f]l]lVm<mDII944T:<GII9*.*@*@DJJ'@AWAW@XYZ446&&23CD "&!7!7$:Z:Z!Z]a]l]l!l ,,TE[\	
&  99..#/?Zcd)k D$9$99  !D$D$DD ))TYY__<yy" !L 
 "8

!C#:#<#p@X@X#p\`\p\p  ''qWT5E5E5K5K5W5WYgij-kop-p',$ %% $D).D&$$0>tXa0b-DND-'//9/M!!22<<~M MrQ[\^`oQpM 


 ,1+<

(&*&<&<

# 	

  y1 &&JJ44SWSuSu4v  !3!34
 +04::*=$5"t';'; &djjDADJ#&//1##33u<!%!1!1!9!9$**!EDJ//9/M #JJt((&11== ,,44TZZ@E,0,<,<,D,DTZZQUQ_Q_,`)E4> <@;K;K;S;SJJ0A0A<8t~t'8 YY__!4!4n6L6L MM!--55dnnEDN.33DJ+ 

"!&D $$!//DN "-(()&&(>WefjfpfpWqSq )**d.B.B**+ACUCUV 	**+AB01 	23'Q'789o&6q%9:;>tyy?d?def>ghi9900D4J4JJKK[\`\r\rst[uvw[\rst[uvw6t7W7W6XYZ3Ia=AB9:OPUfj:klm9nop

YY[
)*&%)" "-"''..GGLL/1CD3
 3
 &44RWW\\BXZl5mnDJ44TYY

K%%' !7!7;U!UVN((151G1GKe1f..$2R2RR.12.KK_`KK;N;KLMKKA$**BXBXAYZ[((,^,< =677SU ;DD))4t1DE ;1A.

++D)=MU ,,s4;;7"%'+zz'='=$%)	,,;;D**dll[NN5tNL>+;<E/'55 **51 !#!
 "- $%^^d&F&FF 
  00??jjRVR^R^_DL&+A+MRptuRu$$%;<KM-1#56FHf#g  >12."D!"23N&)I)IIIA~ <<	K*d.N.NNQTD<<<R M =)q BMR_bcRcBdd>>js484J4J>[fhlhshs4t11!*=!9IAvAID$(1H0P0P#PTU#U#uZ^abZbguYuL$$33GGUyy>>*1$**>OQ\*]*&8"NN!b ,2/+B+H+H+JL+0<<TYYM]M]ejepep+qL JJ<<@P@P@W@WXd@e@i@i@k@p@p@rr<",,-CD&+ 696!;65A6==a@9Q> 001GH 3?288:592d>>>!C'+'<'<'J'J4Q[Q[]a]i]i'j
 M 2Q 66 ,,==AZAZZ "))$*:*:*B*B%P (33	  !'+'9'9%I['\ # 333 6 8 8"[[66%++l:S:S #*Gq4::;Q;Q7QTXTpTp7p,q"q">>\-@-@@","RSZSaSaRbbx  zF  zM  zM  yN  !O#  #*L"8%%t/F/Fv/N)OO%#((77KKDQ  --9d>P>PST>T688TYYY-1^^-M-MdN`N`-a
!%-/XX-E-E$'$5$5dnn$E$($6$6."

 .2-=-=-M-M$)$4$4$6$($6$6."
 !8 9 9$($4$4$E$EIbIb$b,1,F,F,H	#*9f#=#=090@I,6	'+'<'<'R'RSWYcYceieqeq'r++-'+'<'<'N'NtU_U_aeamam'n )-(?(?(A#//JJJ#-d.?.?AYAYAkAk#l#l $ 1 1 6 6 8)

..!3.+0D1H}4LP^3^+^

('+'<'<'H'Hzz[_[g[g'h55#%!!!0&*7 6 	 (,'<'<'K'KDR\R\^b^j^j'k
 ||5559Z9Z9Z133LLNG ":J <<111T\\5V5V5V-//Y *Z ax

../ 0##,+-[]
 59100==dJJPTP\P\]DL))E5%9Mziv *  ,,		?)++OOC$6$6$89NN_ ||000S =V ??wtW55D'"op&&&4::+K+K+W%''67##|'?'??(**!!# 	7<<>1 #DJJ$:$:E B,,/DD
)jj**'
 	 $

 5 5 * 44W=&&u-!55RY5Z 99   TZZ%E%E%QVZV_V_VpVptuVu0
ww''
DJJ4T4TUUKK"=j\Ig hiMM*DA 1
 ,,99$

DLLY 	!!# ##/$$TZZ04::11:wGGe D #s   Ad4Ad4	Ad9	d9
Aec                    U R                   Gb6  UGb2  U R                   [        R                  :X  a  UR                  nOU R                   [        R                  :X  a-  SS KnUR                  R                  5       R                  5       nOcU R                   [        R                  :X  a  UR                  nO8U R                   [        R                  :X  a  SS KnUR                  R                  nU R                  b  U R                  U5      OSW 3n[        R                   R#                  U R$                  R&                  U5      nU$ U R$                  R&                  nU$ )Nr   zrun-)r~  rT   r7  numberr9  rX  r\  get_contextget_trial_idr:  idr=  r1  runr'  rg  rf  r  r   r   )r  r/  run_idr_  r1  run_namer  s          r   rq  Trainer._get_output_dir
  s    !!-%2C%%)?)??''?+>+>> ..0==?''?+A+AA''?+@+@@.2ll.Ft||E*dSYRZOHggll499#7#7BG  ii**Gr   c           
        ^ Uc  U R                   n[        R                  R                  T[        5      n[        R                  R                  T[
        5      n[        R                  R                  T[        5      n[        R                  R                  T[        5      n[        R                  R                  T[        5      n[        R                  R                  T[        5      n[        R                  R                  T[        5      n	[        R                  R                  T5      =(       at    [        U4S j[        R                  " T5       5       5      =(       dD    [        R                  R                  [        R                  R                  T[         S35      5      n
[        R                  R                  T5      (       a  [        R                  " T5       Vs/ s H  n[        R                  R                  [        R                  R                  TU5      5      (       d  MG  [        R                  R                  [        R                  R                  TU[
        5      5      (       dI  [        R                  R                  [        R                  R                  TU[        5      5      (       d  M  UPM     snO/ nU
(       a   U R                   (       d  [#        ST S35      e[        S UUUU	UU4 5       5      (       d  U
(       d  U(       d  [#        ST 35      e[$        R'                  ST S35        [        R                  R                  U5      (       aO  [(        R*                  " U5      nUR,                  nUb*  U[.        :w  a   [$        R1                  S	U S
[.         S35        [        R                  R                  U5      (       d,  [        R                  R                  U5      (       d  U
(       Ga  [3        5       (       a  [        R                  R                  [        R                  R                  TS5      5      (       a  [4        R6                  " T[        SSS9  g [9        U R:                  S5      (       a.  U R:                  R<                  SL a  [$        R1                  S5        [?        5         [@        RB                  " USSS9nSUS'   URE                  USS9nAg U R                   (       a@  [G        U RH                  RJ                  RL                  U RH                  UT40 [O        5       D6  g U R:                  RP                  (       aC  [        R                  R                  U5      (       a  [R        R@                  RU                  USS9nO [?        5         [@        RB                  " USSS9nURE                  US5      nAU RW                  U5        g [Y        U5      (       GaG  [9        US5      (       d  [9        US5      (       Ga  [9        US5      (       a  [        R                  R[                  T5      (       a  [9        US5      (       a6  UR\                  n[_        U5      S:  a  [$        R1                  S5        US   nOUR`                  nU(       aO  U H7  n[        R                  R                  TU5      nURc                  UUUU:H  S9  M9     URe                  U5        g URc                  TUSS9  g [$        R1                  S[
         S35        g [$        R1                  S 5        g [g        UT[3        5       U R:                  RP                  S!9n[3        5       (       d  U RW                  U5        g g s  snf )"Nc              3      >#    U  HR  n[         R                  R                  [         R                  R                  TU5      5      (       d  MG  [        U;   v   MT     g 7fr  )rg  rf  isdirr  FSDP_MODEL_NAME)r  folder_namer  s     r   r	  0Trainer._load_from_checkpoint.<locals>.<genexpr>
  s?      #EK77==.Dk!RS /;.#Es   AAAz.binzCheckpoint found at z* is only supported when using PyTorch FSDPc              3   `   #    U  H$  n[         R                  R                  U5      v   M&     g 7fr  )rg  rf  r8  )r  fs     r   r	  r  
  s+      
A q!!s   ,.z!Can't find a valid checkpoint at zLoading model from ry  z9You are resuming training from a checkpoint trained with z- of Transformers but your current version is zJ. This is not recommended and could yield to errors or unwanted behaviors.user_content.ptFrf  tagr   load_optimizerr  TzOEnabling FP16 and loading from smp < 1.10 checkpoint together is not supported.r   map_locationweights_only_smp_is_partialrx  r  active_adapteractive_adaptersload_adapterr   zFMultiple active adapters detected will only consider the first adapterr   )rC  jThe intermediate checkpoints of PEFT may not be saved correctly, consider using a custom callback to save i in corresponding saving folders. Check some examples here: https://github.com/huggingface/peft/issues/96GCould not load adapter model, make sure to have `peft>=0.3.0` installed)rx  prefer_safe)4r   rg  rf  r  rm   rl   rk   rq   rp   ro   rn   r  rW  listdirr8  r  rO  r  r  r  r   from_json_filetransformers_versionr   rA  r   rt  r  r@  r   r  rv   r   loadload_state_dictr   rT  ru  r.  r   save_safetensorssafetensors	load_file_issue_warnings_after_loadr   existsr  r<  r  r  set_adapterr*   )r  r  r   config_fileadapter_weights_fileadapter_safe_weights_fileweights_fileweights_index_filesafe_weights_filesafe_weights_index_fileis_fsdp_ckptr  adapter_subdirsr  checkpoint_versionrl  load_resultr  r  subdir_namepeft_ids    `                   r   r  Trainer._load_from_checkpoint
  s   =JJEggll#9;G!ww||,BDXY$&GGLL1GIb$c!ww||$:LIWW\\*@BTUGGLL)?ARS"$'',,/EG^"_ww}}%;< 	
 #%::.D#E  ^ ww~~bggll+AoEVVZC[\] 	* ww}}344 $&::.D#E#EK77==.Dk!RS  GGNN277<<0FUi#jkkww~~bggll3I;Xq&rs #E  	  4 434J3KKuvww  
 !%&+(-
 
 
 @AW@XYZZ)*@)ACD77>>+&&%44[AF!'!<!<!-2D2SOPbOc d@@K} M== 77>>,''277>>:K+L+LP\&((77>>"'',,/EGX"YZZ ..3uej tyy&11diinn6Lm -.!&Lu[_!`J49J01"'"7"7
4"7"PK"%%$$**66$$*	
 ,- 99--"''..AR2S2S!,!2!2!<!<=NW\!<!]J,.!&Lu[_!`J $33JF//< E"" /00GECT4U4U[b~\ \ 77>>"899u&788*/*?*?/!3"NN+st)8);).)=)=&+:K&(ggll3I;&WG!..wS^bpSp.r ,; )).9**+A>`d*eNNDDXCY Zbb hi 2-6M6O]a]f]f]w]wK +,,//< -As   #A^-B^=^c                    [         R                  SU R                  R                   SU R                  R                   S35        [
        R                  R                  U R                  R                  [        5      n[
        R                  R                  U R                  R                  [        5      n[
        R                  R                  U R                  R                  [        5      n[
        R                  R                  U R                  R                  [        5      n[        5       (       a  U R                  OU R                  nU R                  (       aB  [!        U R                  U R                  R                  [#        U R                  5      (       + S9  g U R$                  (       aT  ['        U R(                  R                  R*                  U R(                  UU R                  R                  40 [-        5       D6ng [
        R                  R/                  U5      (       dm  [
        R                  R/                  U5      (       dI  [
        R                  R/                  U5      (       d%  [
        R                  R/                  U5      (       Ga=  Sn[        5       (       Ga  [
        R                  R1                  [
        R                  R                  U R                  R                  S5      5      (       a0  [2        R4                  " U R                  R                  [        SSS9  g U R6                  R8                  (       aC  [
        R                  R1                  U5      (       a  [:        R<                  R?                  US	S
9nO [A        5         [<        RB                  " US	SS9nSUS'   URE                  USS9ng [#        U5      (       GaF  [G        US5      (       d  [G        US5      (       Ga  [G        US5      (       a  [G        US5      (       a>  URH                  S   n	[K        URH                  5      S:  a  [         RM                  S5        OURN                  n	[
        R                  R/                  U5      (       d$  [
        R                  R/                  U5      (       a7   URQ                  U R                  R                  U	5        SSK.J/n  U" / / 5      nO[         RM                  S[         S35        SnO[         RM                  S5        SnOU R6                  R8                  (       aC  [
        R                  R1                  U5      (       a  [:        R<                  R?                  US	S
9nO [A        5         [<        RB                  " US	SS9nURE                  US5      n[        5       (       d  U(       a  U Ra                  W5        g g g [
        R                  R/                  [
        R                  R                  U R                  R                  [b        5      5      (       dZ  [
        R                  R/                  [
        R                  R                  U R                  R                  [d        5      5      (       aH  [g        XPR                  R                  [        5       S9n[        5       (       d  U Ra                  U5        g g [         RM                  SU S35        g ! [R         aW  n
URT                  U	   RV                  (       a3  SURT                  U	   RX                  RZ                   S3n[S        U5      U
ee S n
A
ff = f)NzLoading best model from z	 (score: rq  r  Tr  Fr  r   r  r  r  r  r  r  r  r   r   zCDetected multiple active adapters, will only consider the first onez0When using prompt learning PEFT methods such as z, setting load_best_model_at_end=True can lead to errors, it is recommended to set this to False and to load the model manually from the checkpoint directory using PeftModel.from_pretrained(base_model, <path>) after training has finished.)_IncompatibleKeysr  r  r  z#Could not locate the best model at zi, if you are running a distributed training on multiple nodes, you should activate `--save_on_each_node`.)4r  r  ru  rk  best_metricrg  rf  r  rq   ro   rl   rk   r   rS  r   rH  r%   r   rO  r   rT  r.  r   r  r8  rt  r  r   r  r  r   r  rv   r  r  r@  r  r<  rA  r  r  r2  peft_configis_prompt_learning	peft_typer  torch.nn.modules.moduler  r  rn   rp   r*   )r  best_model_pathbest_safe_model_pathbest_adapter_model_pathbest_safe_adapter_model_pathr   r  has_been_loadedrl  r  excmsgr  s                r   rn  Trainer._load_best_modelZ  s^   .tzz/O/O.PPYZ^ZdZdZpZpYqqstu'',,tzz'G'GV!ww||DJJ,L,LN_`"$'',,tzz/O/OQe"f')ww||DJJ4T4TVo'p$&=&?&?""TZZ$$%""

00'5djj'A#A
 !!)  &&22  

00	
 ()K GGNN?++ww~~233ww~~566ww~~:;;"O&((77>>"'',,tzz/O/OQb"cdd ..!ZZ==( %',	 yy11bggnnEY6Z6Z%0%6%6%@%@AU^c%@%d
02%*ZZebf%g
49J01"'"7"7
4"7"PK!%((  '788GEK\<]<]cj~d d #5*;<<-2-B-B1-EN"5#8#89A= &/t u-2-A-AN77>>*ABBbggnnUqFrFr* % 2 24::3S3SUc d  R*;B*CK"NN!LL`Ka bj!j
 /4O'pq*/ yy11bggnnEY6Z6Z%0%6%6%@%@AU^c%@%d
02%*ZZebf%g

 #("7"7
E"JK.00_33K@ 6E0WW^^BGGLL)I)IKbcddhjhohohvhvGGLL99;MNi
 i
 2zz77@W@YK +,,//< - NN5o5F GP Pg $0 *#(#4#4^#D#W#W )[+0+<+<^+L+V+V+\+\*] ^8)8 %( +7s*;$D$)*s   *&[( (
]	2A]]	c                    [        UR                  5      S:w  a  U R                  R                  bQ  [	        UR                  5      [	        U R                  R                  5      :X  a  U R                  R                  5         O#[        R                  SUR                   S35        [        UR                  5      S:w  a$  [        R                  SUR                   S35        g g )Nr   z8There were missing keys in the checkpoint model loaded: ry  z;There were unexpected keys in the checkpoint model loaded: )	r<  missing_keysr   _keys_to_ignore_on_saver:  r  r  rA  unexpected_keys)r  r  s     r   r  "Trainer._issue_warnings_after_load  s    {''(A-zz11=#kF^F^B_cf

22d C 

&&(!YZeZrZrYsstuv{**+q0NNMkNiNiMjjkl 1r   c           
         U R                  US9nU R                  XR                  R                  U5        [	        U R
                  [        R                  R
                  R                  5      (       aX  U(       dQ  U R                  R                  nUR                  S5      (       d  SU 3n U R
                  R                  XE   5        U$ U$ ! [         a2  n[        SU S[        UR                  5       5       SU S35      UeS nAff = f)Nignore_keyseval_9The `metric_for_best_model` training argument is set to 'W', which is not found in the evaluation metrics. The available evaluation metrics are: zX. Please ensure that the `compute_metrics` function returns a dictionary that includes 'zM' or consider changing the `metric_for_best_model` via the TrainingArguments.)evaluatera  ru  rg  r   rZ  r   r>  r_  r   r$  
startswithrt  r)  r   r  )r  r/  r   r  rJ  metric_to_checkr  s          r   rA  Trainer._evaluate  s   --,@-A!!%)?)?I d'')A)A)S)STT]k"ii==O"--g66$)/):";	!!&&w'?@ w  OP_O` a==A',,.=Q<R Smm|l} ~_` s   ,C 
D	-DD	c	                    U R                   R                  (       GaQ  U R                  R                  U R                  :  Ga,  [        5       (       a  [        R                  " 5         0 n	U R                  U5      R                  5       R                  5       n
X-  n[        XR                  R                  U R                  -
  -  S5      U	S'   Ub4  [        U[        R                  5      (       a  UR                  5       OUU	S'   Ub  XS'   OU R                  5       U	S'   U =R                   U
-  sl        U R                  R                  U l        U R#                  5         U R%                  X5        S nU R                   R&                  (       aX  U R)                  XF5      nU R+                  XS9nU R,                  R.                  [0        R2                  :X  a  XR                   l        U R                   R4                  (       aR  U R7                  X45        U R8                  R;                  U R,                  U R                  U R                   5      U l         g g )Nr  r  r  r  )rJ  r/  )r|  
should_logru  rg  r>  r   r  r  _nested_gathermeanr  r  r   r   r  r   r=  ro  rp  should_evaluaterA  _determine_best_metricr   r!  rX   r"  rf  _save_checkpointr^  on_save)r  r  r  r   r/  r7  r   r  r  logstr_loss_scalarrJ  is_new_best_metrics                r   ra   Trainer._maybe_log_save_evaluate  s    <<"""tzz'='=@\@\'\%''%'D "009>>@EEGN G ::3I3IDLhLh3h!iklmDL$8B9ell8[8[INN$4aj[!((5_%(,(?(?(A_%##~5#+/::+A+AD(OOHHT&<<''nnUAG!%!<!<W!<!Zyy&&,*;*;;+=(<<##!!%/0088DJJPTP\P\]DL $r   c                    Uc  g U R                   R                  S:  ay  U R                   R                  n[        R                  R                  USU S35      n[        R                  R                  U5      (       d  [        R                  SU S35        g OZ[        R                  R                  US5      n[        R                  R                  U5      (       d  [        R                  S5        g [        5          [        R                  " U5      nS S S 5        [        R                  " WS   5        [        R                  R                  US	   5        [        R                  R!                  US
   5        [#        5       (       a  [$        R                   " US   5        U R                   R&                  [(        R*                  :H  n[        R,                  R/                  5       (       a  [1        S[        R,                  XE5        [3        5       (       a  [1        S[        R4                  XE5        [7        5       (       a  [1        S[        R8                  XE5        [;        5       (       a  [1        S[        R<                  XE5        [?        5       (       a  [1        S[        R@                  XE5        g g ! , (       d  f       GN= f)Nr   
rng_state_.pthz$Didn't find an RNG file for process zr, if you are resuming a training that wasn't launched in a distributed fashion, reproducibility is not guaranteed.rng_state.pthzDidn't find an RNG file, if you are resuming a training that was launched in a distributed fashion, reproducibility is not guaranteed.pythonnumpyr   r   CUDANPUHPUMLUMUSA)!r   r  r  rg  rf  r  r8  r  r  r   r   r  r  setstater   	set_stateset_rng_stater   r  rI  rh   rJ  cudais_availablerO   r   npur   hpur   mlur   musa)r  rO  r  rng_filecheckpoint_rng_stateis_distributeds         r   rD  Trainer._load_rng_state!  s   99!# II33Mww||J*]O40PQH77>>(++:=/ Jc c  , ww||J@H77>>(++B ^#(::h#7  ,X67
		09:""#7#>?!##1%8900L4L4LL::""$$$VUZZ9M^!##$UEII7K\!##$UEII7K\!##$UEII7K\"$$$VUZZ9M^ %# ^s   <J//
J>c           
      b   SnU R                   R                  GbX  U R                   R                  nUR                  S5      (       d  SU 3n X   nU R                   R                  (       a  [        R                  O[        R                  nU R                  R                  c@  U R                   R                  (       a  [        S5      O
[        S5      U R                  l        U" XPR                  R                  5      (       ao  XPR                  l        U R                   R                  [        R                  [        R                   4;   a%  U R                  R"                  U R                  l        S	nU$ ! [         a/  n[        SU S[	        UR                  5       5       S35      UeSnAff = f)
z
Determine if the model should be saved based on the evaluation metrics.

Returns:
    bool: True if a new best metric was found, else False
FNr  r  r  zJ. Consider changing the `metric_for_best_model` via the TrainingArguments.z-infinfT)r   r$  r  r)  r   r  greater_is_betterr   greaterlessru  r  r  r!  rX   STEPSEPOCHrg  best_global_step)r  rJ  r/  r  r  metric_valuer  operators           r   r  Trainer._determine_best_metricL  s[    #99**6"ii==O"--g66$)/):";&7 &*YY%@%@rzzbggHzz%%-:>)):U:Uv[`af[g

&jj&<&<==)5

&99**|/A/A<CUCU.VV26**2H2HDJJ/%)"!!'  OP_O` a==A',,.=Q<R  S]^ s   E5 5
F.?*F))F.c                 ^   [          SU R                  R                   3nU R                  c  Uc  U R	                  5         U R                  US9n[        R                  R                  XC5      nU R                  USS9  U R                  R                  [        R                  [        R                  4;   a  U R                  R                  (       ar  [          SU R                  R                   3n[        R                  R                  XF5      n[        R                  R!                  U5      (       a  XpR                  l        U R                  R$                  (       d3  U R'                  U5        U R)                  U5        U R+                  U5        U R                  R,                  (       Ga$  U R.                  R0                  U R2                  /-    Vs/ s H  n[5        U[6        5      (       d  M  UPM     sn H  nUR8                  R:                  n	UR                  5       n
[5        U R                  R<                  U	   [>        5      (       a*  U R                  R<                  U	   RA                  U
5        M  XR                  R<                  U	'   M     U R                  RC                  [        R                  R                  U[D        5      5        U R                  RF                  (       a  U RI                  U5        U R                  R,                  (       a  U RK                  SUS9  g g s  snf )Nro  )r/  Trd  r$  )&rP   ru  rg  r~  ro  rq  rg  rf  r  rh  r   r!  rX   r   r!  r"  r  rk  save_only_model_save_optimizer_and_scheduler_save_scaler_save_rng_staterf  r^  r   r|  r   r6   r6  r7  r  r   r  ri  rj  rd  _push_from_checkpoint_rotate_checkpoints)r  r   r/  checkpoint_folderr  r   best_checkpoint_folderbest_checkpoint_dirr  cb_namecb_states              r   r  Trainer._save_checkpointr  sO     55Qtzz7M7M6NO!!)emOO&&U&3WW\\'=

4899""|'9'9<;M;M&NNSWS]S]SnSn(='>a

@[@[?\%]""$'',,w"Oww~~1223F

0yy((..z:j)  , 99    "22<<~MMrQ[\^`oQpM ,,//88:djj;;GDdKKJJ11':AA(K=EJJ11': JJ##BGGLL=O$PQ99  &&z2 99  $$t$H !s   L*0L*c           	         [         R                  " 5       [        R                   R                  5       [        R                   R                  5       S.n[        R                  R                  5       (       a  U R                  R                  [        R                  :X  a,  [        R                  R                   R                  5       US'   O+[        R                  R                   R                  5       US'   [        5       (       a  [        R
                  " 5       US'   [        5       (       a  U R                  R                  [        R                  :X  a,  [        R                   R                   R                  5       US'   O+[        R                   R                   R                  5       US'   [#        5       (       a  U R                  R                  [        R                  :X  a,  [        R$                  R                   R                  5       US'   O+[        R$                  R                   R                  5       US'   ['        5       (       a  U R                  R                  [        R                  :X  a,  [        R(                  R                   R                  5       US'   O+[        R(                  R                   R                  5       US'   [+        5       (       ak  U R                  R                  [        R                  :X  a"  [        R,                  R                  5       US'   O![        R,                  R                  5       US'   [.        R0                  " USS	9  U R                  R2                  S
::  a6  [        R4                  " U[.        R6                  R9                  US5      5        g [        R4                  " U[.        R6                  R9                  USU R                  R:                   S35      5        g )N)r  r  r   r  r   r  r  r  r  Tr  r   r  r  r  )r  getstater   	get_stater   get_rng_stater  r  r   rI  rh   rJ  get_rng_state_allr   r  r   r  r   r  r   r  r   r  rg  rh  r  rk  rf  r  r  )r  r   
rng_statess      r   r*  Trainer._save_rng_state  s    oo'YY((*<<--/


 ::""$$yy&&,*B*BB%*ZZ%6%6%H%H%J
6"%*ZZ%6%6%D%D%F
6"!## " 0 0 2Ju!##yy&&,*B*BB$)II$4$4$F$F$H
5!$)II$4$4$B$B$D
5!!##yy&&,*B*BB$)II$4$4$F$F$H
5!$)II$4$4$B$B$D
5!!##yy&&,*B*BB$)II$4$4$F$F$H
5!$)II$4$4$B$B$D
5!"$$yy&&,*B*BB%*ZZ%A%A%C
6"%*ZZ%=%=%?
6" 	J.991$JJz277<<
O#LMJJz277<<
jI`I`Haae<f#ghr   c                 
   [        5       (       Ga  [        R                  " S5        U R                  (       a  U R                  R                  5       U R                  R                  5       S.n[        R                  " U[        R                  R                  USU R                  R                   SU R                  R                   S[         35      SS9  OQ[        R                  " U R                  R                  5       [        R                  R                  U[        5      5        [         R"                  " SS	9 n[        R                  " U R$                  R                  5       [        R                  R                  U[&        5      5        [)        U5        S S S 5        GO[+        5       (       a  U R                  R-                  SS
9n[.        R0                  " 5         [.        R2                  " 5       S:X  d)  [.        R4                  R6                  R8                  (       a[  [.        R                  " U[        R                  R                  U[        5      S[.        R4                  R6                  R8                  S9  GOU R:                  (       a  S[=        [>        R@                  " U RB                  RD                  5      RF                  RI                  5       5      ;   nU(       a6  [K        U R                  5      (       a  U RB                  RE                  USS9  GO/U RB                  RE                  U5        GOU RL                  (       a  [O        U RP                  R4                  RR                  U RP                  U R                  U40 [U        5       D6  [W        U RP                  R4                  RR                  U RP                  U R                  U R                  U5        OlU R                  RX                  (       aQ  [Z        R                  " U R                  R                  5       [        R                  R                  U[        5      5        U R:                  =(       a    []        U R$                  [^        5      (       + nU R                  RX                  (       a  U R:                  (       a  U(       a  [        5       (       dz  [         R"                  " SS	9 n[Z        R                  " U R$                  R                  5       [        R                  R                  U[&        5      5        S S S 5        [)        W5        g g g g ! , (       d  f       GN = f! , (       d  f       N/= f)Nsaving_optimizer_states)rY  shard_metadatar  -of-ro  Fmaster_onlyTrecord)gather_if_shardr   )r   v3exclude_frozen_parameters)rD  )0r   r  rl  r  rY  rl  r   get_shard_metadatark  rg  rf  r  r   r  r  rm  r3  catch_warningsrZ  rn  rM   r   local_state_dictrt  r  rdp_rankru  rv  shard_optimizer_staterH  r:  r   r   rS  save_checkpointr   r  r   rO  r   rT  r.  r   r   rf  r   r   r   )r  r   optmcaught_warningsopt_state_dict accept_exclude_frozen_parametersis_deepspeed_custom_schedulers          r   r(  %Trainer._save_optimizer_and_scheduler  s   !##MM34**!%!:!:!<&*jj&C&C&E GGLL"d499+B+B*C4		H\H\G]]^_m^n$o !& 113RWW\\*n5]^((5))446ZQ_8`a#O4 65 %&&!^^<<U<SNKKM||~"ciimm&I&I"GGLL^< yy}}::	 && 0Kc!!$"4"4"D"DEPPUUWO 0, 0N4::4N4N""22:Y]2^""22:>!!  &&22D4D4DdjjR\`u`w    &&22D4D4DdnnVZV`V`bl YY""JJt~~002BGGLL^4\] )-(A(A )
*8K
 G
% II!!..2O*,,((5

4,,779277<<
Tb;cd 60	 - 3P "Q 65X 65s   <AT;AU;
U

Uc                   ^ Tc  gU R                   (       a  [        U R                  [        5      (       d  [        R
                  " SS9 n[        5         U R                  R                  [        R                  " [        R                  R                  T[        5      SS95        SSS5        [        W5        g[        5       (       a;  [         R                   " [        R                  R                  T["        5      S-   5      O[        R                  R%                  [        R                  R                  T["        5      5      =(       d    [        R                  R%                  [        R                  R                  T[&        5      5      =(       dO    [        R                  R)                  T5      =(       a)    [+        U4S j[        R,                  " T5       5       5      nU R.                  (       aR  [         R                   " [        R                  R                  TSU R0                  R2                   S["         35      5      OUnU(       Ga
  [        R                  R%                  [        R                  R                  T[        5      5      (       Ga  [5        5       (       Ga  U R.                  (       ay  [        5         [        R                  " [        R                  R                  TS	U R0                  R6                   S
U R0                  R2                   S["         35      SSS9nUS   nOB[        5         [        R                  " [        R                  R                  T["        5      SSS9n[        R
                  " SS9 n[        5         [        R                  " [        R                  R                  T[        5      SSS9nSSS5        [        W5        [8        R:                  " X@R0                  R<                  5        [8        R:                  " WU R0                  R<                  5        U R>                  R                  U5        U R                  R                  U5        g[        5       (       ak  [        R                  R%                  [        R                  R                  TS5      5      (       a  U4S jnOU4S jnU R@                  RC                  U5        OU R0                  R2                  S:  a  U R0                  R<                  OSnU RD                  (       aU  [G        U RH                  RJ                  RL                  U RH                  U R>                  U RN                  T40 [Q        5       D6  O[[        5         U R>                  R                  [        R                  " [        R                  R                  T["        5      USS95        [        R
                  " SS9 n[        5         U R                  R                  [        R                  " [        R                  R                  T[        5      SS95        SSS5        [        W5        ggg! , (       d  f       GN= f! , (       d  f       GN= f! , (       d  f       N@= f)z3If optimizer and scheduler states exist, load them.NTr@  r  _*c              3      >#    U  Hd  n[         R                  R                  [         R                  R                  TU5      5      (       d  MG  [        R                  S 5      S   U;   v   Mf     g7f)ry  r   N)rg  rf  r  r  OPTIMIZER_NAME_BINr  )r  r  rO  s     r   r	  8Trainer._load_optimizer_and_scheduler.<locals>.<genexpr>0  sP      +AK77==j+)NO H*005a8KG+As   AA/"A/z	rank*-of-ro  r  r=  r   r  rY  r  c                    > UR                  [        R                  " [        R                  R                  T[        5      SS95        g )NTr   )r  rt  r  rg  rf  r  rm  modoptrO  s     r   opt_load_hook<Trainer._load_optimizer_and_scheduler.<locals>.opt_load_hooka  s-    //jR`9ako0pqr   c                 8  > [         (       aH  UR                  [        R                  " [        R
                  R                  T[        5      SSS95        g UR                  [        R                  " [        R
                  R                  T[        5      SS95        g )NT)r   back_compatr   )rs  r  rt  r  rg  rf  r  rm  rX  s     r   r[  r\  f  sd    88 # 3 3$'HHRWW\\*n-U_cqu$v!" !$ 3 3CHHRWW\\*Vd=eos4t ur   r   ))rH  r   rZ  r   r3  rF  rv   r  r   r  rg  rf  r  rn  rM   r   globrm  r8  rU  r  rW  r  r  r   r  r   r  r  send_cpu_data_to_devicer=  rY  rS  register_post_step_hookrO  r   rT  ru  r.  r   r   )r  rO  rL  checkpoint_file_existsoptimizer_statelr_scheduler_stater[  r  s    `      r   r5  %Trainer._load_optimizer_and_scheduler  sq   $$d//1JKK,,D9_,.%%55

277<<
N#KZ^_ :
 $O4 '(( IIbggll:~>EF rww||JGH 	77>>"'',,z;M"NO	 GGMM*-  +-::j+A  	$ ** IIbggll:499;O;O:PPQR`Qa/bcd' 	
 "bggnnRWW\\*n5]&^&^%''..,.&+jj&$tyy/F/F.GtDIIL`L`Kaabcqbr(s &+%)'O '6k&BO,.&+jjZ@ucg'O ,,D9_,.).Z@ucg*& :
 $O4**?II<L<LM**+=tyy?O?OP..?!!112DE*,,ww~~bggll:?P&QRRr
v &&>>}M
 8<yy7K7Ka7O499#3#3UZL+++ ,,22>> ,, NN JJ& 45 1266!JJ "Z HWcrv
 ,,D9_,.%%55

277<<
N#KZ^_ :
 $O4Y '_!; :9b :9f :9s'   
AYAY,)AY>
Y),
Y;>
Zc                 L    U R                   R                  nUc  g [        5       (       a  [        R
                  " S5        [        R                  " SS9 n[        R                  " U R                   R                  R                  5       [        R                  R                  U[        5      5        [        U5        S S S 5        U R                  R                   (       a  [        5       (       d  [        R                  " SS9 n["        R                  " U R                   R                  R                  5       [        R                  R                  U[        5      5        S S S 5        [        W5        g g g ! [         a     g f = f! , (       d  f       N= f! , (       d  f       N== f)Nsaving_scaler_stateTr@  )rT  scalerr!  r   r  rl  r3  rF  rk  rl  rg  rf  r  SCALER_NAMErM   r   rf  r   )r  r   rh  rL  s       r   r)  Trainer._save_scaler  s   	%%,,F >!##MM/0((5((//::<bggll:Wb>cd#O4 6
 99  )?)A)A((5

4++22==?jZeAfg 60 *B   		 65 65s+   E4 A'FAF4
F F
F
F#c           	         Uc  g[         R                  R                  [         R                  R                  U[        5      5      nU(       GaW  [        5       (       a  [        R                  " SS9 n[        5         [        R                  " [         R                  R                  U[        5      SSS9nSSS5        [        W5        [        R                  " WU R                  R                  5        U R                   R"                  R%                  U5        g[        R                  " SS9 n[        5         U R                   R"                  R%                  [        R                  " [         R                  R                  U[        5      SS95        SSS5        [        W5        gg! , (       d  f       N= f! , (       d  f       N,= f)z If scaler state exists, load it.NTr@  r   r  rR  )rg  rf  r8  r  ri  r   r3  rF  rv   r   r  rM   r  r`  r   r=  rT  rh  r  )r  rO  rb  rL  scaler_states        r   r6  Trainer._load_scaler  s-   !#Z0U!V! &'',,D9_,.#(::Z=E`d$L :
 $O4**<9I9IJ  ''77E,,D9_,.$$++;;

277<<
K#HW[\ :
 $O4% " :9 :9s   1AF&,A%F7&
F47
Gc                 >  ^ U R                   R                  (       d  g/ n/ nU R                  R                  U R                  /-   nU R
                  R                  R                  5        GHO  u  mn[        U[        5      (       d  U/n[        U4S jU 5       5      (       Ga  U Vs/ s H   oUR                  R                  T:X  d  M  UPM"     nn[        Xd5       H  u  pWUR                  S0 5      nUR                  S0 5      n	[        U5      " S
0 UD6n
U	R                  5        H  u  p[!        XU5        M     [        U["        5      (       a  Xl        OUR%                  U
5        U R                  R'                  [        U
5      5        M     [(        R+                  S5        GM>  UR%                  T5        GMR     [-        U5      S:  a(  [(        R/                  SSR1                  U5       S	35        U H  nU R                  R3                  U5        M      gs  snf )zLIf callback states exist and were passed in, restore their states if enabledNc              3   T   >#    U  H  oR                   R                  T:H  v   M     g 7fr  )r6  r7  )r  r  stored_callbacks     r   r	  /Trainer._load_callback_state.<locals>.<genexpr>  s"     eRdh%%../ARds   %(r   
attributeszPContinuing training from checkpoint, restoring any callbacks that were passed inr   zPCheckpoint included callbacks not included in current configuration. Ignoring. (r  r  r   )r   'restore_callback_states_from_checkpointr^  r   r|  ru  r  r<  r   r   rW  r6  r7  zipr  r   r>  r:   r  r  r  r  r<  rA  r  r_  )r  	not_foundnew_callbacksoriginal_callbacksrm  r  
duplicatescallback_datar   rr  new_callback	attributer  rp  s                @r   r9  Trainer._load_callback_state  s   yy@@	!22<<~M%)ZZ%B%B%H%H%J!OTdD))veRdeee .@-?CUCUC^C^bqCqH-?   03:/D+H(,,VR8D!.!2!2<!DJ#'>#9D#9L,6,<,<,>(	? -?!(N;;'3%,,\:))99$|:LM 0E no  1/ &K0 y>ANNbcgclclmvcwbxxyz &H!!..x8 &/s   (H	Hr8  rQ  n_trials	directionbackendr  r'  c                 <   Uc
  [        5       n[        U5      n[        U   " 5       nUR                  5         XPl        U R
                  c  [        S5      eUc  UR                  OUU l        X`l	        Uc  [        OUU l        UR                  " XU40 UD6n	SU l        U	$ )a  
Launch an hyperparameter search using `optuna` or `Ray Tune` or `SigOpt`. The optimized quantity is determined
by `compute_objective`, which defaults to a function returning the evaluation loss when no metric is provided,
the sum of all metrics otherwise.

<Tip warning={true}>

To use this method, you need to have provided a `model_init` when initializing your [`Trainer`]: we need to
reinitialize the model at each new run. This is incompatible with the `optimizers` argument, so you need to
subclass [`Trainer`] and override the method [`~Trainer.create_optimizer_and_scheduler`] for custom
optimizer/scheduler.

</Tip>

Args:
    hp_space (`Callable[["optuna.Trial"], Dict[str, float]]`, *optional*):
        A function that defines the hyperparameter search space. Will default to
        [`~trainer_utils.default_hp_space_optuna`] or [`~trainer_utils.default_hp_space_ray`] or
        [`~trainer_utils.default_hp_space_sigopt`] depending on your backend.
    compute_objective (`Callable[[Dict[str, float]], float]`, *optional*):
        A function computing the objective to minimize or maximize from the metrics returned by the `evaluate`
        method. Will default to [`~trainer_utils.default_compute_objective`].
    n_trials (`int`, *optional*, defaults to 100):
        The number of trial runs to test.
    direction (`str` or `List[str]`, *optional*, defaults to `"minimize"`):
        If it's single objective optimization, direction is `str`, can be `"minimize"` or `"maximize"`, you
        should pick `"minimize"` when optimizing the validation loss, `"maximize"` when optimizing one or
        several metrics. If it's multi objectives optimization, direction is `List[str]`, can be List of
        `"minimize"` and `"maximize"`, you should pick `"minimize"` when optimizing the validation loss,
        `"maximize"` when optimizing one or several metrics.
    backend (`str` or [`~training_utils.HPSearchBackend`], *optional*):
        The backend to use for hyperparameter search. Will default to optuna or Ray Tune or SigOpt, depending
        on which one is installed. If all are installed, will default to optuna.
    hp_name (`Callable[["optuna.Trial"], str]]`, *optional*):
        A function that defines the trial/run name. Will default to None.
    kwargs (`Dict[str, Any]`, *optional*):
        Additional keyword arguments for each backend:

        - `optuna`: parameters from
          [optuna.study.create_study](https://optuna.readthedocs.io/en/stable/reference/generated/optuna.study.create_study.html)
          and also the parameters `timeout`, `n_jobs` and `gc_after_trial` from
          [optuna.study.Study.optimize](https://optuna.readthedocs.io/en/stable/reference/generated/optuna.study.Study.html#optuna.study.Study.optimize)
        - `ray`: parameters from [tune.run](https://docs.ray.io/en/latest/tune/api_docs/execution.html#tune-run).
          If `resources_per_trial` is not set in the `kwargs`, it defaults to 1 CPU core and 1 GPU (if available).
          If `progress_reporter` is not set in the `kwargs`,
          [ray.tune.CLIReporter](https://docs.ray.io/en/latest/tune/api/doc/ray.tune.CLIReporter.html) is used.
        - `sigopt`: the parameter `proxies` from
          [sigopt.Connection.set_proxies](https://docs.sigopt.com/support/faq#how-do-i-use-sigopt-with-a-proxy).

Returns:
    [`trainer_utils.BestRun` or `List[trainer_utils.BestRun]`]: All the information about the best run or best
    runs for multi-objective optimization. Experiment summary can be found in `run_summary` attribute for Ray
    backend.
NzXTo use hyperparameter search, you need to pass your model through a model_init function.)r"   rT   r!   ensure_availabler~  r   r2  default_hp_spacer8  r'  r\   rQ  r  )
r  r8  rQ  r}  r~  r  r'  r  backend_objbest_runs
             r   hyperparameter_searchTrainer.hyperparameter_search  s    @ ?/1G!'*8AC$$&!(??"j  9A8H44h>O>W!:]n??49GG!%r   r  r  c                 0   U R                   R                  b  U R                   R                  US'   U R                  R                  (       aI  U R                   R                  US'   Ub-  UR                  [        SX R                   R                  S95        0 UESU R                   R                  0EnU R                   R                  R                  U5        U R                  R                  U R                  U R                   U R                  U5      U l        g)z
Log `logs` on the various objects watching training.

Subclass and override this method to inject custom behavior.

Args:
    logs (`Dict[str, float]`):
        The values to log.
    start_time (`Optional[float]`):
        The start of training.
Nr7  rK  r\  )r-  rt  )ru  r7  r   rI  rK  r  rf   rg  log_historyr  r^  on_logr|  )r  r  r  r  s       r   rp  Trainer.log5  s     ::' JJ,,DM9922,0JJ,L,LD()%M':**JjJjkl=D=VTZZ%;%;<=

%%f-,,33DIItzz4<<Y]^r   rm  c           
        ^  [        U[        5      (       aD  [        U5      " UR                  5        VVs0 s H  u  p#UT R	                  U5      _M     snn5      $ [        U[
        [        45      (       a  [        U5      " U 4S jU 5       5      $ [        U[        R                  5      (       a  ST R                  R                  0nT R                  (       a  [        R                  " U5      (       d  [        R                  " U5      (       aI  UR                  ST R                  R                   R"                  R$                  R'                  5       05        UR(                  " S0 UD6$ U$ s  snnf )zl
Prepares one `data` before feeding it to the model, be it a tensor or a nested list/dictionary of tensors.
c              3   F   >#    U  H  nTR                  U5      v   M     g 7fr  )_prepare_input)r  rF  r  s     r   r	  )Trainer._prepare_input.<locals>.<genexpr>S  s     Cdd11!44d   !r=  r   r   )r   r   r   r<  r  r  r   r   r  r   r=  rH  is_floating_point
is_complexr  rT  ru  rD  r5  r   r  )r  rm  r  rF  r  s   `    r   r  Trainer._prepare_inputL  s    dG$$:TZZ\R\TQq$"5"5a"88\RSSudm,,:CdCCCell++		 0 01F((e.E.Ed.K.KuO_O_`dOeOe w(8(8(>(>(O(O(\(\(b(b(def77$V$$ Ss   E,
r  c                    U R                  U5      n[        U5      S:X  a(  [        SSR                  U R                  5       S35      eU R
                  R                  S:  a  U R                  b  U R                  US'   U$ )z
Prepare `inputs` before feeding them to the model, converting them to tensors if they are not already and
handling potential state.
r   zThe batch received was empty, your model won't be able to train on it. Double-check that your training dataset contains keys expected by the model: rd  ry  mems)r  r<  r  r  ro  r   rB  r  r  r  s     r   r|  Trainer._prepare_inputs^  s    
 $$V,v;!IILRVRiRiIjHkkln  991$)?!ZZF6Nr   c                 "    U R                  5       $ )z6
A helper wrapper to group together context managers.
)autocast_smart_context_managerr  s    r   compute_loss_context_manager$Trainer.compute_loss_context_managern  s     2244r   ru  c                     U R                   (       a3  [        R                  R                  R	                  XR
                  S9nU$ [        R                  " 5       nU$ )z
A helper wrapper that creates an appropriate context manager for `autocast` while feeding it the desired
arguments, depending on the situation.
)ru  r   )rq  r   r   r   r~  ry  r   r   )r  ru  ctx_managers      r   r  &Trainer.autocast_smart_context_managert  sN    
   ))--00}TbTb0cK  %002Kr   c                    UR                  5         [        U R                  S5      (       a>  [        U R                  R                   5      (       a  U R                  R                  5         U R	                  U5      n[        5       (       aa  [        XU R                  R                  5      nUR                  5       R                  5       R                  U R                  R                  5      $ U R                  5          U R                  XUS9nSSS5        AU R                  R                  Gb[  U R                   R"                  U R                  R                  -  S:X  Ga)  [%        5       (       a  [&        R(                  R+                  5         O[-        5       (       a  [&        R.                  R+                  5         O[1        5       (       a  [&        R2                  R+                  5         O[5        5       (       a  [&        R6                  R+                  5         Oq[9        5       (       a  [&        R:                  R+                  5         OC[=        5       (       a  [>        RA                  S5        O[&        RB                  R+                  5         0 nU R                  RD                  [F        RH                  [F        RJ                  4;   a  U RM                  5       US'   U R                  RN                  S:  a  WRQ                  5       nU RR                  (       a;  [T        RV                  " WU R                  5       nURY                  5         SSS5        gU RZ                  (       d&  U R\                  c  WU R                  R                  -  nU R^                  R`                  [b        Rd                  :X  a  SUS	'   U R^                  RX                  " W40 UD6  UR                  5       $ ! , (       d  f       GN= f! , (       d  f       g= f)
a  
Perform a training step on a batch of inputs.

Subclass and override to inject custom behavior.

Args:
    model (`nn.Module`):
        The model to train.
    inputs (`Dict[str, Union[torch.Tensor, Any]]`):
        The inputs and targets of the model.

        The dictionary will be unpacked before being fed to the model. Most models expect the targets under the
        argument `labels`. Check your model's documentation for all accepted arguments.

Return:
    `torch.Tensor`: The tensor with training loss on this batch.
r\  r  Nr   zW`torch_empty_cache_steps` is set but HPU device/backend does not support empty_cache().r  r   Fscale_wrt_gas)3r\  r@  rY  ri  r|  r   r   r   r  reduce_meandetachr  r=  r  compute_losstorch_empty_cache_stepsru  rg  r   r   xpuempty_cacher   r  r   r  r   r  r   mpsr   r  rA  r  r>  rg   r  r  r   r  r  rp  r   
scale_lossbackwardrV  r   rT  rO  r   rP  )r  r   r  r  loss_mbr  r  scaled_losss           r   rR  Trainer.training_step  s   ( 	4>>7++9M9M0N0NNN  "%%f-"$$*5$)):_:_`G&&(//144TYY5E5EFF..0$$UGY$ZD 1 II--9

&&)J)JJaO%''		%%''))		%%'(**

&&('))		%%''))		%%''))m 

&&( 99??~22N4J4JKK&*&=&=&?F?#99??Q99;D==dnn5$$& 65 11d6L6L6TdiiCCC 00O4M4MM*/'%%d5f5;;= c 10F 65s   ;O1O.
O+.
O<c           	      v   U R                   c  U R                  b  SU;   a  UR                  S5      nOSnU R                  (       a  0 nUb  XFS'   0 UEUEnU" S0 UD6nU R                  R
                  S:  a  XpR                  R
                     U l        Ub  U R                  R                  U5      n[        U5      (       a%  UR                  R                  R                  5       n	OUR                  5       n	U R                  b  U R                  XuUS9n
OU	[        R                  " 5       ;   a  U R                  XuSS9n
OU R                  Xu5      n
O[        U[         5      (       aR  SU;  aL  [#        S	S
R%                  UR'                  5       5       SS
R%                  UR'                  5       5       S35      e[        U[         5      (       a  US   OUS   n
U R                  R(                  (       a=  U R                  (       d  U R                  (       a  Ub  XR                  R*                  -  n
U(       a  X4$ U
$ )z
How the loss is computed by Trainer. By default, all models return the loss in the first element.

Subclass and override for custom behavior.
Nlabelsr  r   r  T)shift_labelsr  zJThe model did not return a loss from the inputs, only the following keys: rd  z,. For reference, the inputs it received are ry  r   )r{  r   r=  rV  r   rB  r  rT  r+   r   r  r   	_get_namer,   r;  r   r  r  r  r  average_tokens_across_devicesnum_processes)r  r   r  return_outputsr  r  loss_kwargsoutputsr  r  r  s              r   r  Trainer.compute_loss  s    +t/E/E/QW_ciWiZZ)FF))K!-4F01..+.F/&/ 991$ !5!56DJ"..;;EBOo..,77==GGI
,668
%%1--gRd-e@GGII**7*N**7;'4((V7-B `xx/00\]`]e]eflfqfqfs]t\uuvx 
 '1$&?&?76?WQZD II33//43I3I".$$222D"0:d:r   c                 4    U R                   R                  S:H  $ )z
Whether or not this process is the local (e.g., on one machine if training in a distributed fashion on several
machines) main process.
r   )r   local_process_indexr  s    r   r  Trainer.is_local_process_zero  s    
 yy,,11r   c                     [        5       (       a  [        R                  " 5       S:H  $ U R                  R                  S:H  $ )z
Whether or not this process is the global main process (when training in a distributed fashion on several
machines, this is only going to be `True` for one process).
r   )r   rt  r  r   r  r  s    r   r  Trainer.is_world_process_zero  s2     #$$88:?"99**a//r   r   re  c                    Uc  U R                   R                  n[        5       (       a  U R                  U5        GO[	        5       (       a  [
        R                  " USS9  U R                  R                  5       nU R                   R                  (       a  U R                  XS9  [        (       a7  [        [
        R                  R                  US5      5      R                  5         GOXU R                   (       a  S[#        U R$                  R&                  R(                  R*                  5      ;   a  [,        R.                  " [0        5      [,        R.                  " S5      :  aO  U R$                  R3                  U R4                  5      nU R                   R                  (       a  U R                  XS9  OU R6                  (       aQ   U R$                  R3                  U R8                  5      nU R                   R                  (       a  U R                  XS9  O,U R                   R                  (       a  U R                  U5        U R                   RH                  (       a  U(       d  U RI                  S	S
9  ggg! [:         a    [<        R?                  S5        U R                   R                  (       a  U R                  U0 S9  [A        U R                   R                  U[B        [D        /5        U R                  RG                  U5         Nf = f)zm
Will save the model, so you can reload it using `from_pretrained()`.

Will only save from the main process.
NTr  )rl  r  FULL_STATE_DICTz0.24.1z| stage3_gather_16bit_weights_on_model_save=false. Saving the full checkpoint instead, use zero_to_fp32.py to recover weightsz
Model save)commit_message)%r   r   r   	_save_tpur   rg  rh  rS  rl  rf  _savers  r   rf  r  touchrO  r  rT  ru  r.  state_dict_typer   r   accelerate_versionget_state_dictr   rH  r(  r  r  rA  rN   rq   ro   rJ  rd  )r  r   re  rl  s       r   rh  Trainer.save_model  s    --J!##NN:&$&&KK
T2++668Jyy$$

:
=((RWW\\*.?@AGGI!!!S)9)9)?)?)K)K)[)[%\\01GMM(4KK!--<<TZZH
99((JJzJA&&?!--<<T^^L
99((JJzJA YY""JJz" 99  L9 *8   	?: 99((JJzbJ9'		(=(=zLZkKlm""22:>	?s   AI4 4BLLc           
      "	   Ub  UOU R                   R                  n[        R                  SU 35        U R                  n[
        R                  " 5         [
        R                  " SS9(       aX  [        R                  " USS9  [        R                  " U R                   [        R                  R                  U[        5      5        [        4n[
        R                   " S5        U R"                  (       Ga  UR%                  5       UR'                  5       S.n[        R                  R                  USU R                   R(                   S	U R                   R*                   S
[,         35      n[
        R                  " XESS9  [
        R                   " S5        U R                   R.                  (       a  SSKJn  U" [        R                  R                  US5      S[,         3SS9u  pxUR4                  R4                  nU R6                  R9                  U5      n	[;        X5      (       a6  U	R=                  UU[
        R                  U R                   R>                  S9  GO[        R                  S5        [
        R                  " U[        R                  R                  U[,        5      5        GO[;        X#5      (       Gd"  [;        U R6                  R9                  U5      U5      (       a  U R6                  R9                  U5      R=                  UU R                   R.                  [
        R@                  " UR%                  5       5      [
        R                  U R                   R>                  S9  O[        R                  S5        [
        R@                  " UR%                  5       5      n
[
        R                  " U
[        R                  R                  U[,        5      5        OkUR=                  UU R                   R.                  [
        R                  U R                   R>                  [
        R@                  " UR%                  5       5      S9  U RB                  b8  U R                   R.                  (       a  U RB                  R=                  U5        g g g )NSaving model checkpoint to F)localTr  saving_checkpoint)r   r<  r  r=  ro  r>  save_full_checkpointsr   )%consolidate_sharded_model_checkpointsr  zrank*-of-*-)ckpt_prefixckpt_suffixrh  )rl  save_functionsafe_serializationETrainer.model is not a `PreTrainedModel`, only saving its state dict.)is_main_processrl  r  r  )r  r  r  rl  )"r   r   r  r  r   r  r  is_master_ordinalrg  rh  r   rk  rf  r  TRAINING_ARGS_NAMErt   rl  r  rl  rE  r  r  rq   rf  r  r  rQ  rT  r+   r   save_pretrainedr  _maybe_convert_to_cpur   )r  r   r   supported_classesckpt	ckpt_pathr  full_state_dictrn  r  rl  s              r   r  Trainer._save_tpuM  s=   #-#9Ztyy?S?S
1*>?


e,KK
T2JJtyy"'',,z;M"NO ,-
)*&&&))+"'":":"<D d499#:#:";4		@T@T?UUVWcVdeI GGD7MM12yy$$\%J "Z <"-l^ <$&"
 ++"&"2"2"?"?"FoAA#33"#2&(gg+/99+E+E	 4  KK ghGGORWW\\*l-STE55$**77>@QRR  --e4DD$(II$9$9!778H8H8JK"$'''+yy'A'A E  cd55e6F6F6HI

BGGLL\$JK!! $		 5 5 gg#'99#=#=33E4D4D4FG "    ,1F1F!!11*= 2G,r   c                    Ub  UOU R                   R                  n[        R                  " USS9  [        R                  SU 35        [        5       (       d  [        4O[        [        4n[        U R                  U5      (       GdE  Uc  U R                  R                  5       n[        U R                  R                  U R                  SS9U5      (       aG  U R                  R                  U R                  SS9R                  XU R                   R                  S9  O[        R                  S5        U R                   R                  (       aD  [         R"                  R%                  U[        R&                  R)                  U[*        5      SS	0S
9  Oh["        R,                  " U[        R&                  R)                  U[.        5      5        O.U R                  R                  XU R                   R                  S9  U R0                  b  U R0                  R                  U5        OyU R2                  bl  [5        U R2                  S5      (       aQ  U R2                  R6                  b:  [        R                  S5        U R2                  R6                  R                  U5        ["        R,                  " U R                   [        R&                  R)                  U[8        5      5        g )NTr  r  Fr  )rl  r  r  r  pt)r   r   zWSaving Trainer.data_collator.tokenizer by default as Trainer.processing_class is `None`)r   r   rg  rh  r  r  r   r)   r   r   r   rl  rT  r+   r  r  r  r   	save_filerf  r  ro   rk  rq   r   r   r@  r   r  )r  r   rl  r  s       r   r  Trainer._save  s   #-#9Ztyy?S?S

J.1*>?6G6I6I_.P_ajOk $**&788!!ZZ224
$**77

W\7]_pqq  --djjU-Scc$))JdJd d  cd99--%%//"BGGLL=N$O[ceiZj 0  JJz277<<
L+QRJJ&&diiF`F` '    ,!!11*=***K88"",,8KKqr((88D 	

499bggll:7IJKr   c                    U R                   R                  [        R                  :X  aj  U R                  =R
                  [        U R                  /U R                   R                  S9R                  5       R                  5       -  sl        SU l        g U R                  =R
                  U R                  -  sl        SU l        g )Nr  r   )r   rI  rh   rJ  ru  r"  rC   r}  r=  rC  r  r  s    r   ro  Trainer.store_flos  s    99""l&>&>>JJ!!-t/@/@.A$))JZJZ[__affh! !"DJJ!!T%6%66! !Dr   c                 V   / n[        U5      R                  U S35       Vs/ s H4  n[        R                  R	                  U5      (       d  M)  [        U5      PM6     nnU H  nU(       a2  UR                  [        R                  R                  U5      U45        M<  [        R                  " SU S3U5      nUc  M\  UR                  5       c  Mo  UR                  [        UR                  5       S   5      U45        M     [        U5      n	U(       aL  [        U5      S:  a=  U	S   S   U	S   S   -
  n
U
S:  a&  [        R                  " S5        U R!                  S	XS
9$ U	 Vs/ s H  oS   PM	     n	nU R"                  R$                  b  [        [        U R"                  R$                  5      5      U	;   ai  U	R'                  [        [        U R"                  R$                  5      5      5      n[)        U[        U	5      S-
  5       H  nXS-      X   sX'   XS-   '   M     U	$ s  snf s  snf )N-*z.*z	-([0-9]+)r   r   r  r  zPmtime may not be reliable on this filesystem, falling back to numerical orderingF)r%  r   checkpoint_prefixr  )r   r_  rg  rf  r  r  r  getmtimerematchgroupsr  sortedr<  r3  r4  rr  ru  rk  indexr  )r  r   r  r%  ordering_and_checkpoint_pathxglob_checkpointsrf  regex_matchr  
mtime_diffrO  best_model_indexr  s                 r   rr  Trainer._sorted_checkpoints  s    (*$,0,<,A,AEVDWWYBZ,[p,[q_a_f_f_l_lmn_oFCF,[p$D,33RWW5E5Ed5KT4RS hh,=+>i'H$O*{/A/A/C/O077[=O=O=QRS=T9UW[8\] % $$@A 9:Q>+B/25G5J15MMJCpq//#
 0   ?QQ>P
m>PQ JJ,,8D99:;?QQ177DAaAa<b8cd+S1C-Dq-HICUZ[V[C\^p^s@"%'9a%'@ J!!= q( Rs   (H!H!#H&c                 B   U R                   R                  b  U R                   R                  S::  a  g U R                  XS9n[        U5      U R                   R                  ::  a  g U R                   R                  nU R                  R
                  b9  U R                   R                  S:X  a  US   U R                  R
                  :w  a  Sn[        S[        U5      U-
  5      nUS U nU H1  n[        R                  SU S35        [        R                  " USS	9  M3     g )
Nr   r$  r   r  r  r&  r'  Tr(  )r   rs  rr  r<  ru  rk  r  r  r  ru  rv  )r  r%  r   r  rs  number_of_checkpoints_to_deletecheckpoints_to_be_deletedrO  s           r   r,  Trainer._rotate_checkpoints  s    99%%-1K1Kq1P "55	5a!"dii&@&@@  9955JJ,,8		**a/"2&$***J*JJ *-a5G1HK[1[*\'$67W8W$X!3JKK5j\A_`aMM*D9 4r   r  metric_key_prefixc                    USLnU(       a  UOU R                   n[        U[        5      (       aM  0 nUR                  5        H5  u  pgU R	                  U(       a  UOUUU SU 3S9nUR                  U5        M7     U$ U R                  R                  5         U R                  U5      n	U R                  (       a  [        U	5      n	[        R                  " 5       n
U R                  R                  (       a  U R                  OU R                  nU" U	SU R                   c  SOSUUS9nU R                  R"                  U R                  R$                  -  nU S3UR&                  ;   a  XR&                  U S3   -  n
U S3UR&                  ;   a  XR&                  U S3   -  n
UR&                  R                  [)        UU
UR*                  [,        R.                  " UR*                  U-  5      S	95        U R1                  UR&                  5        [2        R4                  U R                  R6                  ;   a)  [8        R:                  " [<        R>                  " 5       5        U R@                  RC                  U R                  U RD                  U RF                  UR&                  5      U l#        U R                  RI                  UR&                  5        UR&                  $ )
a  
Run evaluation and returns metrics.

The calling script will be responsible for providing a method to compute metrics, as they are task-dependent
(pass it to the init `compute_metrics` argument).

You can also subclass and override this method to inject custom behavior.

Args:
    eval_dataset (Union[`Dataset`, Dict[str, `Dataset`]), *optional*):
        Pass a dataset if you wish to override `self.eval_dataset`. If it is a [`~datasets.Dataset`], columns
        not accepted by the `model.forward()` method are automatically removed. If it is a dictionary, it will
        evaluate on each dataset, prepending the dictionary key to the metric name. Datasets must implement the
        `__len__` method.

        <Tip>

        If you pass a dictionary with names of datasets as keys and datasets as values, evaluate will run
        separate evaluations on each dataset. This can be useful to monitor how training affects other
        datasets or simply to get a more fine-grained evaluation.
        When used with `load_best_model_at_end`, make sure `metric_for_best_model` references exactly one
        of the datasets. If you, for example, pass in `{"data1": data1, "data2": data2}` for two datasets
        `data1` and `data2`, you could specify `metric_for_best_model="eval_data1_loss"` for using the
        loss on `data1` and `metric_for_best_model="eval_data2_loss"` for the loss on `data2`.

        </Tip>

    ignore_keys (`List[str]`, *optional*):
        A list of keys in the output of your model (if it is a dictionary) that should be ignored when
        gathering predictions.
    metric_key_prefix (`str`, *optional*, defaults to `"eval"`):
        An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named
        "eval_bleu" if the prefix is "eval" (default)

Returns:
    A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The
    dictionary also contains the epoch number which comes from the training state.
Nrn  )r   r  r  r  T)r  prediction_loss_onlyr  r  _jit_compilation_time_model_preparation_timer   r!  )%r   r   r  r<  r  r  r,  r-  r  r  r'   r  r   r  prediction_loopevaluation_loopr   r  r  rJ  rf   r   mathceilrp  r   rf  rG  r  rg  rh  ri  r^  on_evaluateru  r|  r  )r  r   r  r  overriderJ  eval_dataset_name_eval_datasetdataset_metricseval_dataloaderr  	eval_loopr  total_batch_sizes                 r   r  Trainer.evaluate	  sk   Z  t+'/|T5F5FlD))G4@4F4F4H0!"&--2:@Q +):(;1=N<O&P #0 #
 / 5I N 	""$22<@&&1/BOYY[
,0II,P,PD((VZVjVj	$ *.)=)=)E4#/
  9944tyy7K7KK  56&..H..,=+>>S)TUUJ  78FNNJ..,=+>>U)VWWJ!"..))F$6$69I$IJ		
 	 ((DIIOO;OOC..01,,88DJJPTP\P\^d^l^lm44V^^D~~r   c                    U R                   R                  5         U R                  U5      n[        R                  " 5       nU R                  R
                  (       a  U R                  OU R                  nU" USX#S9nU R                  R                  U R                  R                  -  nU S3UR                  ;   a  XWR                  U S3   -  nU S3UR                  ;   a  XWR                  U S3   -  nUR                  R                  [        UUUR                  [        R                  " UR                  U-  5      S95        U R                   R#                  U R                  U R$                  U R&                  UR                  5      U l        U R                   R)                  UR                  5        [+        UR,                  UR.                  UR                  S9$ )a  
Run prediction and returns predictions and potential metrics.

Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method
will also return metrics, like in `evaluate()`.

Args:
    test_dataset (`Dataset`):
        Dataset to run the predictions on. If it is an `datasets.Dataset`, columns not accepted by the
        `model.forward()` method are automatically removed. Has to implement the method `__len__`
    ignore_keys (`List[str]`, *optional*):
        A list of keys in the output of your model (if it is a dictionary) that should be ignored when
        gathering predictions.
    metric_key_prefix (`str`, *optional*, defaults to `"test"`):
        An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named
        "test_bleu" if the prefix is "test" (default)

<Tip>

If your predictions or labels have different sequence length (for instance because you're doing dynamic padding
in a token classification task) the predictions will be padded (on the right) to allow for concatenation into
one array. The padding index is -100.

</Tip>

Returns: *NamedTuple* A namedtuple with the following keys:

    - predictions (`np.ndarray`): The predictions on `test_dataset`.
    - label_ids (`np.ndarray`, *optional*): The labels (if the dataset contained some).
    - metrics (`Dict[str, float]`, *optional*): The potential dictionary of metrics (if the dataset contained
      labels).

Prediction)r  r  r  r  r  r  )predictionsr  rJ  )r,  r-  r   r  r   r  r  r  r  r  rJ  r  rf   r   r  r  r^  
on_predictru  r|  r  rV   r
  r  )	r  r  r  r  test_dataloaderr  r  r  r  s	            r   predictTrainer.predictq  s   H 	""$22<@YY[
,0II,P,PD((VZVjVj	;
  9944tyy7K7KK  56&..H..,=+>>S)TUUJ  78FNNJ..,=+>>U)VWWJ!"..))F$6$69I$IJ		
 ,,77		4::t||]c]k]kl44V^^DF,>,>&JZJZdjdrdrssr   r  c           	         U R                   nUb  UOUR                  nU R                  (       a  U R                  c  [	        U SSS9u    nU R                  U R                  SUS9n[        U R                  R                  5      S:X  Ga$  XR                  L Ga  [        R                  " 5       n	U R                  (       dF  U R                  (       aP  U R                  R                  S:w  a6  U R                   R                  (       d  U R                  R                  U5      OU R                  R                  USS9n[!        [        R                  " 5       U	-
  S	5      U l        U R                  (       a  Xl        XR                  La  Xl        U R                  (       a  U R$                  U l        U R&                  (       ds  UR(                  (       a)  UR+                  [,        R.                  UR0                  S
9nO9UR2                  (       a(  UR+                  [,        R4                  UR0                  S
9nU R                   R6                  n
[8        R;                  SU S35        [=        U5      (       a(  [8        R;                  SU R?                  U5       35        O[8        R;                  S5        [8        R;                  SU
 35        URA                  5         [C        U RD                  S5      (       a>  [G        U RD                  R@                  5      (       a  U RD                  RA                  5         XRH                  l%        [M        USS5      nURN                  S:  a  SU l(        [S        U R                   RT                  SS9n[S        U R                   RT                  SS9n[S        U R                   RT                  SS9n[S        U R                   RT                  SS9nSn0 nSn[W        U5       GH  u  nn[Y        U5      nUb
  UU-  nU
c  Un
U R[                  UUX4S9u  nnn[M        U R                  SS5      nSUR\                  ;   a  U R_                  UU   5      OSn[a        5       (       a  [b        Rd                  " 5         Ub1  U Rg                  URi                  U
5      5      nURk                  U5        Ub^  U R                  Rm                  USSS9nU Rg                  U5      nU R                   Rn                  (       a  US:X  a  URk                  U5        Ub  U R                  Rm                  USSS9nUb}  U R                  Rm                  USSS9nU Rp                  b  U Rq                  UU5      nU Rg                  U5      nU R                   Rn                  (       a  US:X  a  URk                  U5        UbC  U Rg                  U5      nU R                   Rn                  (       a  US:X  a  URk                  U5        U RH                  Rs                  X`Rt                  U Rv                  5      U l;        U R                   Rn                  (       a  U Rx                  br  Ubo  Ubl  U R                  Rz                  R|                  n0 nSUR\                  ;   a  UOSUS'   SUR\                  ;   a  UOSUS'   U Ry                  [        S(UUS.UD6US9nAAAA[,        R                  R                  5         GM  UR                  c  GM  US-   UR                  -  S:X  d  GM+  UR                  5         UR                  5         UR                  5         UR                  5         AAAA[,        R                  R                  5         GM     U R                  R                  U l3        URN                  (       a  [C        U S5      (       a  [        U S5        UR                  5       nUR                  5       nUR                  5       nUR                  5       n[=        U5      (       a  [        U5      nOW[        U[        5      (       a  [M        US S5      S:  a  UR>                  nO$[=        U5      (       a  U R?                  U5      nOUnUS:X  a  US:  a  UnU Rx                  bl  Ubi  Ubf  U R                   Rn                  (       dK  SUR\                  ;   a  UOSUS'   SUR\                  ;   a  UOSUS'   U Ry                  [        S(XS.UD65      nOUc  0 n[        U5      n[        U[        5      (       a@  U(       a9  [        R                  " U5      R                  5       R                  5       UU S!3'   OC[        U[        R                  5      (       a$  UR                  5       R                  5       UU S!3'   [C        U S"5      (       a  U R                  UU S#3'   [C        U S$5      (       a  U R"                  UU S%3'   [        UR                  5       5       H7  nUR                  U S&35      (       a  M  UR                  U5      UU S&U 3'   M9     [        XUUS'9$ ))y
Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`.

Works both with or without labels.
Nr   Tr"  	inferenceFr  r  r  evaluation_moder  r   r=  
***** Running  *****r  z  Num examples: Unknown  Batch size = r  r  padding_indexr  r  r(  r  r   )dim	pad_indexr	  r  lossesr
  r  r   r  r$  _lossr  r  model_preparation_timer  rn  r
  r  rJ  r   r   )Ur   r  rH  r(  r$   r  r   r<  rT  _modelsr  rO  r4  torch_compiler  prepare_modelr  r#  rS  r)  rL  r  r   float16r=  rM  rx  r  r  r  ra   r$  r  r@  rY  ri  r^  r  r8  rB  r  r=   eval_do_concat_batchesrF  rE   prediction_stepinclude_for_metricsr  r   r  r  gather_functionrepeatr  pad_across_processesr  r   on_prediction_stepru  r|  r   rG  end_of_dataloaderrS   r  r  eval_accumulation_stepsto_cpu_and_numpygather_for_metricsrj  
get_arraysr   r>   r]   r   r   concatenater  r  r   r  r  r  r=  rR   )r  r  r  r  r  r  r   rn  r   r  r  r   
all_losses	all_preds
all_labels
all_inputsrJ  eval_set_kwargsobserved_num_examplesrt  r  observed_batch_sizer  r  r  r  inputs_decodeis_last_stepbatch_kwargsr   r  s                                  r   r  Trainer.evaluation_loop  s    yy7K7W3]a]v]v $$)?!$1MDAq  e
 St''(A-%::2EJ ,,((T-=-=-M-MQV-V_c_h_h_v_v   ((/ %%33E43P	  +0		j0H!*LD'##"
 JJ&%*" ((!%!3!3 ""u}}T[[I$$u~~dkkJYY..
&{m6:;j!!KK+D,=,=j,I+JKLKK12oj\23

4>>6**x8K8K/L/LNN!0:-z9d;??aDJ 'tyy'G'GW[\
%dii&F&FVZ[	&tyy'G'GW[\
&tyy'G'GW[\
 !" &j1LD&"1&"9".%)<<%%!4J &*%9%9%I]%9%w"FFF%djj2C[QO@HDLdLd@d##F?$;<jn  &'' !--fmmJ.GHv&( $ 0 0 E EmYZfj E k $ 4 4] Cyy33{l7RNN=1!))>>v1X\>]!))>>v1X\>]55A!??OF--f5yy33{l7RMM&)!--f5yy33{l7RNN6*00CCD**VZVbVbcDLyy++''38JvOa#'#3#3#B#B#T#TL#%L7=AYAY7YV_cL*7?4C[C[7[VaeL*"22&\6V\|\'3 3 G
 FFF

&&( --9tax4KgKg>gkl>l++-**,++-++-FFF

&&(G 2L  $//BB??wtW55D'"  **,
((*	**,
**,
 l##l+K &:;;Vdfg@hkl@l&33K*%%"//
;3! 5 9/K   ,%&II006<@X@X6X
^bOH%6>$BZBZ6Z
`dOH%**^9^o^G _G (0j$''J35>>*3M3R3R3T3Y3Y3[G()/0
BJJ//3=??3D3I3I3KG()/04/00CGC\C\G())>?@4122EIE`E`G())@AB 'C>>%6$7q"9::8?C8H,-Qse45 ( )SZhsttr   c                 v   Uc  g[        5       (       a  Uc  Sn[        X5      nU$ [        5       (       a  [        U5      nU$ U R                  R
                  b$  U R                  R
                  R                  S:w  d1  U R                  R
                  c%  U R                  R                  S:w  a  [        U5      nU$ )
Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before
concatenating them to `gathered`
Nnested_gatherNOr  )	r   rL   r   r   r   distributed_staterO  
local_rankrD   r  tensorsnames      r   r  Trainer._nested_gather  s    
 ?!##|&,W;G  %&& )G
 	 ii))5$)):U:U:f:fjn:nII''/DII4H4HB4N(1Gr   c                   ^^ [        U R                  5      S:X  a  SO[        U4S jU R                   5       5      nTR                  SS5      nUc  U R                  n[        U R                  5      S:X  a	  U(       a  SOSnU R                  T5      mTc@  [        U R                  S5      (       a#  [        U R                  R                  SS	/5      mO/ mU(       d  U(       a=  [        [        U4S
 jU R                   5       5      5      n[        U5      S:X  a  US   nOSn[        R                  " 5          [        5       (       a  [        UT5      n	U(       d  U(       a  [!        U	["        5      (       a)  U	S   n
[        U4S jU	R%                  5        5       5      nO
U	S   n
U	SS nU
R'                  5       R)                  5       R+                  5       n[-        U5      nGOySn[!        U	["        5      (       a$  [        U4S jU	R%                  5        5       5      nOU	n[-        U5      nGO/U(       d  U(       a  U R/                  5          U R1                  UTSS9u  pSSS5        WR)                  5       R3                  5       n[!        W["        5      (       a$  [        U4S jUR%                  5        5       5      nOUSS nOSnU R/                  5          U" S0 TD6nSSS5        [!        W["        5      (       a$  [        U4S jUR%                  5        5       5      nOUnU R4                  R6                  S:  a   XR4                  R6                  S-
     U l        SSS5        U(       a  WSS4$ [        W5      n[        U5      S:X  a  US   nWX4$ ! , (       d  f       GN;= f! , (       d  f       N= f! , (       d  f       N`= f)av  
Perform an evaluation step on `model` using `inputs`.

Subclass and override to inject custom behavior.

Args:
    model (`nn.Module`):
        The model to evaluate.
    inputs (`Dict[str, Union[torch.Tensor, Any]]`):
        The inputs and targets of the model.

        The dictionary will be unpacked before being fed to the model. Most models expect the targets under the
        argument `labels`. Check your model's documentation for all accepted arguments.
    prediction_loss_only (`bool`):
        Whether or not to return the loss only.
    ignore_keys (`List[str]`, *optional*):
        A list of keys in the output of your model (if it is a dictionary) that should be ignored when
        gathering predictions.

Return:
    Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]: A tuple with the loss,
    logits and labels (each being optional).
r   Fc              3   J   >#    U  H  nTR                  U5      S Lv   M     g 7fr  r  )r  r  r  s     r   r	  *Trainer.prediction_step.<locals>.<genexpr>  s"     Aveu`a&**Q-W[B[eus    #return_lossNTr  keys_to_ignore_at_inferencepast_key_valuesc              3   F   >#    U  H  nTR                  U5      v   M     g 7fr  rM  )r  rI  r  s     r   r	  rN    s     (WFVdD)9)9FVr  r   r  c              3   D   >#    U  H  u  pUTS /-   ;  d  M  Uv   M     g7fr  Nr   r  r  rF  r  s      r   r	  rN    s(     )o8KqXcgmfnXnOn!!8K    	 c              3   <   >#    U  H  u  pUT;  d  M  Uv   M     g 7fr  r   rU  s      r   r	  rN    s     )d8KqXcOc!!8K   	)r  c              3   D   >#    U  H  u  pUTS /-   ;  d  M  Uv   M     g7frT  r   rU  s      r   r	  rN    s&     &h_TQQ\`f_gQgHgqq_rV  c              3   <   >#    U  H  u  pUT;  d  M  Uv   M     g 7fr  r   rU  s      r   r	  rN    s     &]_TQQ\H\qq_rX  r   )r<  r  allr  ru   r|  r@  r   r8  r  rJ   r  r   r  r   r   r   r  r<  r  r  r   r   r  r  r  r   rB  r  )r  r   r  r  r  
has_labelsrO  loss_without_labelsr  raw_outputsr  	logits_mbr  r  r  s     ` `          r   r*  Trainer.prediction_step  s   < "$"2"23q8UcAveieueuAv>v
 jj5..K&)$*:*:&;q&@[dV[%%f-tzz8,,%djj&7&79VYjXkl  ,"5(WdFVFV(W#WXF6{aF]]_&((.uf=!4!+t44"-f"5$))o8I8I8K)o$o	"-a.$/O	"..0779==?D.y9FD!+t44$))d8I8I8K)d$d	$/	.y9F!4::<(,(9(9%X\(9(] =;;=--/D!'400!&&hW]]_&h!h!(D::<"'/&/ =!'400!&&]W]]_&]!]!(yy++q0%,YY-A-AA-E%F
Q T  $%%v&v;!AYFf%%7 =< =<A _s?   8DN6NA7N6	N%A=N6
N"	N6%
N3	/N66
Oc                 p    [        U R                  S5      (       a  U R                  R                  U5      $ g)a  
For models that inherit from [`PreTrainedModel`], uses that method to compute the number of floating point
operations for every backward + forward pass. If using another model, either implement such a method in the
model or subclass and override this method.

Args:
    inputs (`Dict[str, Union[torch.Tensor, Any]]`):
        The inputs and targets of the model.

Returns:
    `int`: The number of floating-point operations.
rV  r   )r@  r   rV  r  s     r   rV  Trainer.floating_point_ops  s.     4::344::0088r   tokenc                    U R                  5       (       d  gU R                  R                  c8  [        U R                  R                  5      R                  5       R                  nOU R                  R                  nUb  UOU R                  R                  n[        X!U R                  R                  SS9nUR                  U l        SU l        g)z5
Initializes a git repo in `self.args.hub_model_id`.
NT)rc  privater  )r  r   rc  r   r   absoluterI  	hub_tokenr   hub_private_reporepo_idpush_in_progress)r  rc  	repo_namerepo_urls       r   re  Trainer.init_hf_repo  s    
 ))++99!!)TYY112;;=BBI		..I*		0C0Cytyy?Y?Ydhi$,, $r   languagelicensetagsr  finetuned_fromtasksdataset_tagsdataset_argsc
                    U R                  5       (       d  g[        R                  R                  U R                  R
                  S5      n
Sn[        R                  R                  U
5      (       a  [        R                  " U
5      R                  R                  S5      nUS:H  n[        R                  " U
5      R                  R                  nUb<  Ub9  [        U[        5      (       a  U/nU H  nX;  d  M
  UR                  U5        M     [        R                   " U UUUUUUUUU	S9
nUR#                  5       n[%        U
S5       nUR'                  U5        SSS5        U(       aI  U R(                  R+                  U R,                  5      R/                  U R                  R
                  5        gg! , (       d  f       N_= f)aM  
Creates a draft of a model card using the information available to the `Trainer`.

Args:
    language (`str`, *optional*):
        The language of the model (if applicable)
    license (`str`, *optional*):
        The license of the model. Will default to the license of the pretrained model used, if the original
        model given to the `Trainer` comes from a repo on the Hub.
    tags (`str` or `List[str]`, *optional*):
        Some tags to be included in the metadata of the model card.
    model_name (`str`, *optional*):
        The name of the model.
    finetuned_from (`str`, *optional*):
        The name of the model used to fine-tune this one (if applicable). Will default to the name of the repo
        of the original model given to the `Trainer` (if it comes from the Hub).
    tasks (`str` or `List[str]`, *optional*):
        One or several task identifiers, to be included in the metadata of the model card.
    dataset_tags (`str` or `List[str]`, *optional*):
        One or several dataset tags, to be included in the metadata of the model card.
    dataset (`str` or `List[str]`, *optional*):
        One or several dataset identifiers, to be included in the metadata of the model card.
    dataset_args (`str` or `List[str]`, *optional*):
       One or several dataset arguments, to be included in the metadata of the model card.
Nz	README.mdFlibrary_namer   )	rn  ro  rp  r  rq  rr  rs  r  rt  w)r  rg  rf  r  r   r   r  r   r  rm  r  rp  r   r  r  r(   from_trainerto_model_cardopenwriterT  r+   r   create_or_update_model_card)r  rn  ro  rp  r  rq  rr  rs  r  rt  model_card_filepathis_peft_libraryrv  existing_tagsr  training_summary
model_cardr  s                     r   create_model_cardTrainer.create_model_card(  sr   J ))++ ggll499+?+?M77>>-..$>>*=>CCGGWL*f4O &NN+>?DDIIMM$=dC(( 6D(CC( ) +77!)%%
 &335
%s+qGGJ , ))$**5QQRVR[R[RfRfg  ,+s   F22
G c           
      	   U R                  5       (       a(  U R                  R                  [        R                  :X  a  g U R                  R
                  (       d-  U R                  b   U R                  R                  5       (       d  g U R                  R                  n[        [        [        /n[        [        4 H  n[        R                  R!                  X5      n[        R                  R#                  U5      (       d  MH  UR%                  U5        ['        U5       n[(        R*                  " UR-                  5       5      nS S S 5        [/        [1        WS   R3                  5       5      5      nUR5                  U5        M     [7        5       (       a   UR5                  [8        [:        [<        /5        U H  n	[        R                  R#                  [        R                  R!                  X5      5      (       d  MF  [>        R@                  " [        R                  R!                  X5      [        R                  R!                  X)5      5        M     U RB                  b  U RB                  RE                  U5        [F        RH                  " U R                  [        R                  R!                  U[J        5      5        U R                  RL                  [N        RP                  :X  a  SU RR                  RT                   3n
O"S[W        U RR                  RX                  5       3n
[[        U R\                  UU
U R                  R^                  SS[`         S3/S9nU/nU R                  R                  [        Rb                  [        Rd                  4;   a  U R                  R                  [        Rb                  :X  a  SO[g        U5      Rh                  n[[        U R\                  UUU
S	-   U R                  R^                  SS
9nUR%                  U5        U R                  b  U R                  R                  5       (       a  [k        U5      U l        g U R                  Rl                  R5                  U5        g ! , (       d  f       GN6= f)N
weight_mapzTraining in progress, step zTraining in progress, epoch TrS  r  )ri  folder_pathr  rc  run_as_futureignore_patternszlast-checkpointz, checkpoint)ri  r  path_in_repor  rc  r  )7r  r   hub_strategyrU   ENDhub_always_pushrj  is_doner   rm   rq   ro   rp   rn   rg  rf  r  r8  r  rz  jsonloadsreadr   r:  r;  extendr   rj   rl   rk   ru  rP  r   r  r   rk  r  r!  rX   r   ru  rg  r  r7  r   rc  rg  rP   
CHECKPOINTALL_CHECKPOINTSr   rI  rs   jobs)r  r-  r   modeling_files
index_file
index_pathr  r  shard_filesmodeling_filer  model_push_job	push_jobsr  checkpoint_pushs                  r   r+  Trainer._push_from_checkpointr  s9   ))++tyy/E/E/Xyy((T-B-B-NW[WlWlWtWtWvWvYY))
%|5FG-/FGJ&7DJww~~j))%%j1*% JJqvvx0E &"3u\':'A'A'C#DE%%k2 H !!#68LNg"hi+Mww~~bggll+<LMMBGGLL):JBGGLLYcLst ,   ,!!11*=

499bggll:7IJK99""l&8&88:4::;Q;Q:RSN;C

@P@P<Q;RSN&%%")))%%!&;%<B#?@
 $$	99!!k&<&<k>Y>Y%ZZ%)YY%;%;{?U?U%U![_`q[r[w[w  ,))-)->ii))"O _-  (D,A,A,I,I,K,K$29$=D!!!&&--i8a &%s   %Q22
R	c                     [        U S5      (       d  g U R                  bP  U R                  R                  5       (       d0  [        R	                  S5        U R                  R                  5         g g g )Nrj  z\Waiting for the current checkpoint push to be finished, this might take a couple of minutes.)r@  rj  r  r  r  wait_until_doner  s    r   rw  Trainer._finish_current_push  s[    t/00  ,T5J5J5R5R5T5TKKvw!!113 6U,r   r  blockingrevisionc           
         UR                  SS5      nUc  U R                  R                  (       ai  U R                  R                  c*  [	        U R                  R
                  5      R                  nO(U R                  R                  R                  S5      S   nUb  UOU R                  R                  nU R                  c  U R                  US9  U R                  SS9  U R                  5       (       d  g[        U R                  SS5      bg  S	U;  a  / US	'   [        US	   [        5      (       a	  US	   /US	'   U R                  R                    H!  nXuS	   ;  d  M  US	   R#                  U5        M#     U R$                  " SSU0UD6  U R'                  5         [)        U R                  U R                  R
                  UUU(       + S
[*         S3/US9$ )u  
Upload `self.model` and `self.processing_class` to the 🤗 model hub on the repo `self.args.hub_model_id`.

Parameters:
    commit_message (`str`, *optional*, defaults to `"End of training"`):
        Message to commit while pushing.
    blocking (`bool`, *optional*, defaults to `True`):
        Whether the function should return only when the `git push` has finished.
    token (`str`, *optional*, defaults to `None`):
        Token with write permission to overwrite Trainer's original args.
    revision (`str`, *optional*):
        The git revision to commit from. Defaults to the head of the "main" branch.
    kwargs (`Dict[str, Any]`, *optional*):
        Additional keyword arguments passed along to [`~Trainer.create_model_card`].

Returns:
    The URL of the repository where the model was pushed if `blocking=False`, or a `Future` object tracking the
    progress of the commit if `blocking=True`.
r  N/r  )rc  Trd  
model_tagsrp  rS  r  )ri  r  r  rc  r  r  r  r   )r=  r   rf  rc  r   r   rI  r  rg  re  rh  r  r8  r   r   r  r  r  r  rw  r   rP   )r  r  r  rc  r  r  r  	model_tags           r   rd  Trainer.push_to_hub  s   6 ZZd3
$))"7"7yy%%-!$))"6"67<<
!YY3399#>rB
*		0C0C $E* 	t, ))++
 4::|T2>V#!#v &.#.."(.!1v!ZZ22	6N26N)))4 3 	?*?? 	!!#%%		,,)&,!&;%<B#?@
 	
r   c           	         U R                   n[        U5      (       d  [        S5      eUb  UOUR                  nU R                  (       a  U R
                  c  [        U SSS9u    nU R                  U R                  SUS9n[        U R                  R                  5      S:X  a  XR                  L a  U R                  (       d  U R                  (       a  U R                  R                  U5      OU R                  R                  USS9nU R                  (       a  Xl        XR                  La  Xl        U R                  (       a  U R                  U l        U R                   (       ds  UR"                  (       a)  UR%                  [&        R(                  UR*                  S	9nO9UR,                  (       a(  UR%                  [&        R.                  UR*                  S	9n[1        US
S5      (       a  UR2                  OUR4                  n	U	c  [        S5      eU R7                  U5      n
[8        R;                  SU S35        [8        R;                  SU
 35        [8        R;                  SU	 35        SnSnSnSnSn0 n[=        SUR>                  5      n[A        UXS9nU(       di  Sn[C        US5      (       a5  [E        URF                  [H        5      (       a  URF                  R4                  n[A        UU
US9n[A        UU
US9n[A        UU
US9nURK                  5         [C        U RL                  S5      (       a>  [O        U RL                  RJ                  5      (       a  U RL                  RK                  5         URP                  S:  a  SU l)        XRT                  l+        [Y        U5       GH  u  nnU R[                  UUX4S9u  nnn[1        U R                  SS5      nSUR\                  ;   a  U R_                  UU   5      OSnUb-  URa                  U	5      nUc  UO[&        Rb                  " UU4SS9nUb  Uc  UO
[e        UUSS9nUb  Uc  UO
[e        UUSS9nUb  Uc  UO
[e        UUSS9nU RT                  Rg                  X`Rh                  U Rj                  5      U l5        U R                   Rl                  (       a~  U Rn                  bq  Ubn  Ubk  U R                  Rp                  Rr                  n0 n SUR\                  ;   a  UOSU S'   SUR\                  ;   a  UOSU S'   U Ro                  [u        S(XS.U D6US9nU R                   Rl                  (       d)  URv                  c  GM  US-   URv                  -  S:X  d  GM  URy                  U R{                  US5      5        U(       dc  WRy                  U R{                  US 5      5        WRy                  U R{                  US!5      5        WRy                  U R{                  US"5      5        AAAA[&        R|                  R                  5         S#u  ppGM     URP                  (       a  [C        U S$5      (       a  [        U S$5        URy                  U R{                  US5      5        U(       dc  WRy                  U R{                  US 5      5        WRy                  U R{                  US!5      5        WRy                  U R{                  US"5      5        UR                  5       n!U(       d  WR                  5       OSn"U(       d  WR                  5       OSn#U(       d  WR                  5       OSn$U Rn                  bm  U"bj  U#bg  U R                   Rl                  (       dL  SUR\                  ;   a  U!OSUS'   SUR\                  ;   a  U$OSUS'   U Ro                  [u        S(U"U#S.UD65      nOUc  0 n[        U5      nU!b#  U!R                  5       R                  5       X S%3'   [        UR                  5       5       H6  n%U%R                  U S&35      (       a  M  UR                  U%5      X S&U% 3'   M8     [        U"U#XS'9$ ))r  z+dataloader must implement a working __len__Nr   Tr  Fr  r  r  _is_accelerate_preparedz\Batch size cannot be None. Ensure the dataloader has a valid batch_size or total_batch_size.r  r  r  r  r   )make_multiple_ofr  r  r  r  r(  r  )r  r  r  r  r  r   r!  eval_losses
eval_predseval_label_idseval_inputs_ids)NNNNr  r"  rn  r$  r   )Jr   ra   r  r  rH  r(  r$   r  r   r<  rT  r%  rO  r  r'  rS  r)  rL  r  r   r(  r=  rM  rx  r8  r  r  r$  r  r  r  r  r<   r@  r   r  rB   r  rY  ri  rB  r  r^  r  rF  r*  r+  r  r-  catrI   r/  ru  r|  r  r   rG  r0  rS   r1  
add_arrays_gather_and_numpifyr  r  rj  finalizer]   r  r  r   r  r  r=  rR   )&r  r  r  r  r  r  r   rn  r   r  r$  losses_host
preds_hostlabels_hostinputs_hostrJ  r:  r  eval_losses_gathererr  preds_gathererlabels_gathererinputs_gathererrt  r  r  r  r  r  r=  r  r>  r?  	eval_losspredsr  
inputs_idsr  s&                                         r   r  Trainer.prediction_loop  s    yy*%%JKK7K7W3]a]v]v $$)?!$1MDAq  e
 St''(A-%::2E ,,0D0D   ((/%%33E43P  ##"
 JJ&%*" ((!%!3!3 ""u}}T[[I$$u~~dkkJ z#<eDD ''&& 	 n  ((4&{m6:;'~67oj\23.2DH
EIEI"& "DOO,
8\o#  $z9--*Z=O=OQm2n2n#-#5#5#@#@ 6z<brsN7
LcstO7
LcstO

4>>6**x8K8K/L/LNN!??aDJ0:-%j1LD&#'#7#7vG[#7#u D&&%djj2C[QO@HDLdLd@d##F?$;<jn  Z0(3(;fKY_K`fgAh!'1'9V}ZY_os?t
!(3(;f{\brvAw( #* "&{MQUV 
  00CCD**VZVbVbcDLyy++''3
8NS^Sj#'#3#3#B#B#T#TL#%L<BdF^F^<^[dhL*<DH`H`<`[fjL*"22&e:eXde'3 3 G
 yy++,,8dQh$JfJf=fjk=k %//0H0HVc0de+"--d.F.FzS_.`a#..t/G/GUe/fg#..t/G/GUf/gh  [+

&&(DZAk] 2` ??wtW55D'" 	''(@(@m(\]#%%d&>&>z<&XY&&t'?'?M]'^_&&t'?'?M^'_`(113	1E'')46JO,,.PT	7K_--/QU
   ,!%II005;t?W?W5W	]aOH%6>$BZBZ6Z
`dOH%**>+teW`+tds+tuG_G (0 3<>>3C3H3H3JG)/0 'C>>%6$7q"9::8?C8H-Qse45 ( %9gppr   c                     Uc  g[        5       (       a  [        X5      nON[        5       (       a  [        U5      nO3U R                  R
                  [        R                  :X  a  [        U5      n[        U5      $ )rB  N)
r   rL   r   r   r   rI  rh   rJ  rD   rK   rG  s      r   r  Trainer._gather_and_numpify  s_    
 ?!##,W;G$&& )GYY$$(@(@@(1Gg&&r   c                 >   U R                  5       (       d  gSS/n[        R                  R                  [        R                  R	                  U R
                  R                  S5      5      (       aW  [        [        R                  R	                  U R
                  R                  S5      5       nUR                  5       nSSS5        OSnWnU H.  nXT;  d  M
  UR                  S5      (       a  XE-  nM&  USU 3-  nM0     XC:w  ap  [        [        R                  R	                  U R
                  R                  S5      S5       n[        R                  SU 35        UR                  U5        SSS5        U R
                  R                  S5        [        R                  " S	5        U R
                  R!                  5       (       d6  U R
                  R#                  S
5        U R
                  R%                  5         gg! , (       d  f       GNA= f! , (       d  f       N= f)z8Add SageMaker Checkpointing patterns to .gitignore file.Nz*.sagemaker-uploadingz*.sagemaker-uploadedz
.gitignorer  
rw  z"Writing .gitignore file. Content: g      ?z'Add *.sagemaker patterns to .gitignore.)r  rg  rf  r  r  repo	local_dirrz  r  ry  r  rG  r{  git_addr  sleepis_repo_clean
git_commitgit_push)r  patternsr  current_contentcontentpatterns         r   _add_sm_patterns_to_gitignore%Trainer._add_sm_patterns_to_gitignore  s    ))+++-CD 77>>"'',,tyy':':LIJJbggll499#6#6EF!"#&&( GF !O "G%##D))&GG9~-G   %bggll499#6#6EsKqA'KL  L 			,' 	

3yy&&((II  !JKII  )3 GF  LKs   .G<*H<
H
Hc                    0 n[        S5      (       aA  U R                  R                  R                  b   U R                  R                  R                  nSU;   a9  U R                  R                  S:  a  [        S5      eUS   U R                  l        U R                  R                  R                  5       n[        S5      (       aZ  / SQn[        S!0 U Vs0 s H  oDUR                  U5      _M     snD6n[        S5      (       a  U R                  R                  Ul	        UR                  S5      n[        S5      (       d  U(       a  [        S	5      eO>U(       a0  U R                  R                  (       d  [        R                  S
5        UWl        UR                  S5        SU R                  R                  0n[        S5      (       a  WUS'   OUR!                  U5        [#        U R$                  S5      (       a  U R$                  R&                  b  U R$                  R&                  S:  ae  SU l        [*        R,                  " [.        5      [*        R,                  " S5      :  a!  [1        U R$                  R&                  S9US'   O[        S5      e[3        S!0 UD6U l        U R4                  R6                  U l        S[:        R<                  " U R8                  5      R>                  RA                  5       ;   a8  [B        RD                  " U R8                  U R                  RF                  S9U l        [I        U R4                  RJ                  SS 5      S LU l&        [I        U R4                  RJ                  SS 5      S LU l'        [I        U R4                  RJ                  SS 5      S LU l        U RN                  (       a  U R4                  RJ                  RP                  nS H<  n[S        XU R                  RT                  RW                  U[I        X5      5      5        M>     URX                  (       a&  U R                  RZ                  (       a  [        S5      eU RL                  (       a(  [I        U R                  SS 5      c  U R]                  5         U R                  R^                  (       a`  U RL                  (       d  U RN                  (       a>  U R                  R`                  (       a#  U RL                  (       a  SOSn	[        U	 S35      eU RL                  (       aT  U R4                  RJ                  R                  Rb                  S:X  a&  U R                  Rd                  (       a  [        S5      eU R                  R^                  (       aU  U RN                  (       aC  S[g        U R4                  RJ                  RP                  Rh                  5      ;   a  [        S 5      eg g g s  snf )"Nr   r!  r   zThe `AcceleratorConfig`'s `num_steps` is set but `gradient_accumulation_steps` is greater than 1 in the passed `TrainingArguments`If using the passed `AcceleratorConfig` is desired, do not set the `TrainingArguments` `gradient_accumulation_steps`.)split_batchesdispatch_batcheseven_batchesuse_seedable_samplerz1.1.0non_blockingr  zp`non_blocking` is only supported in accelerate v0.30.0 and above. Please upgrade accelerate to use this feature.zx`non_blocking` is enabled but `dataloader_pin_memory` is not. For the best performance, it's recommended to enable both.gradient_accumulation_kwargsrD  dataloader_configtp_sizeTr   )r  torch_tp_pluginz4Requires accelerate>1.3.0 to use Tensor Parallelism.use_gather_object)r  r.  )limit_all_gathersactivation_checkpointingzThe activation_checkpointing in FSDP config and the gradient_checkpointing in training arg can't be set to True simultaneously. Please use FSDP's activation_checkpointing logic when using FSDP.rB  	DeepSpeedr  zJ can't be used with `save_only_model` along with `load_best_model_at_end`.   zo`auto_find_batch_size` isn't supported yet with DeepSpeed Zero-3. Please consider using Zero-2, Zero-1, or FSDPSHARDED_STATE_DICTzWsave_only_model option is not compatible with FSDP state dict type 'SHARDED_STATE_DICT'r   )5rx   r   accelerator_configr  r  r  to_dictr   r=  	data_seedrB  r  r  rA  r  rD  r  r@  r   r  is_tp_enabledr   r   r  r   r   rT  r3  r,  r   r   r   r  r  r   eval_use_gather_objectr8  ru  rH  rO  r.  r>  rF  r  r  r1  r*  r'  r#  
zero_stager  r  r  )
r  grad_acc_kwargsr  r  r  r  r  r   r.  wrappers
             r   r*  *Trainer.create_accelerator_and_postprocess  s   "8,,1M1M1j1j1v"ii::WWO /)yy44q8 L 
 9H8T		5!YY99AAC"8,, m 7 !EVWEVE,0077EVW! 'w//.2ii.A.A!+)--n=&x00! G  
 DII$C$C O .:*=> 		 : :
 #8,,(9D$%KK*+ 4::y))djj.@.@.LQUQ[Q[QcQcfgQg!%D}}/07==3II*CDJJL^L^*_&' !WXX '..#//BB'"3"3D4H4H"I"T"T"Y"Y"[[#,#4#4$$		8X8X$D 
 %,D,<,<,B,BDVX\$]ei$i!&t'7'7'='=}dS[__$T%5%5%;%;=NPTU]aa**00<<KJDII,A,A,E,EeWU`Mh,ij K33		8X8X '  $$<QSW)X)`,,. II%%**d.B.B		00%)%>%>kFGy(rstt %%  &&77BBaG		.. B  II%%$$$D,<,<,B,B,N,N,^,^(__vww ` % &i Xs   Wc                    SSK Jn  U R                  R                  R                  nU" UR
                  R                  5      Ul        UR
                  R                  Ul        UR
                  R                  U R                  U5        g)z?
Sets values in the deepspeed plugin based on the Trainer args
r   r3  N)
rA  r4  rT  ru  rD  r5  r  deepspeed_configrC  r   )r  r  r4  	ds_plugins       r   r*  #Trainer.propagate_args_to_deepspeedm  sg     	Q$$**;;	!9):P:P:W:W!X	%.%;%;%B%B	"55diiAUVr   c                    U R                   (       Gap  [        U R                  5      (       GaT  SSKJn  SSKJn  [        U R                  R                  U5      (       a5  U" U R                  5      U R                  R                  R                  l        [        U R                  SS 5      [        R                  :X  a  U R                  R                   R"                  R$                  R&                  (       a  [(        R*                  " [,        5      [(        R*                  " S5      :  aW  U R                  R                  R                  R/                  U R                  R                   R"                  R$                  SS9  g g g g g g )Nr   )
PeftConfig)fsdp_auto_wrap_policyr   z0.27.0T)r   )rO  r   r   r   r  peft.utils.otherr  r   active_peft_configrT  ru  r.  r  r8  r   rP  r   rD  bnb_4bit_quant_storager  r   r   r  set_mixed_precision)r  r  r  s      r   r3  "Trainer._fsdp_qlora_plugin_updatesy  s   N4::$>$>'>$**77DDF[\`\f\fFg  &&22C

$94@DVDeDeeJJ++??VVhhMM"45h8OO  &&22FFJJ++??VVae G  P i f %?r   c                 :   / nS n[        U5       H  n UR                  [        U5      5        M      [	        U5      S:  =(       a0    SUS   ;   =(       a!    U R
                  =(       d    U R                  S LnU(       a<   [        U Vs/ s H$  oS   R                  S5      R                  5       PM&     sn5      nUb  U R                  R                  (       a)  U R                  R                  U5      R                  5       n[        R                   " U5      (       aP  UR#                  U5      nU R                  R$                  S:  a%  UR'                  5       S:X  a  UR)                  S5      nXE4$ ! [         a       GML  f = fs  snf ! [        [        4 a     Nf = f)Nr   r  r  r   )r  r  rz  StopIterationr<  rV  r   rC  ner"  r!  r   r  rT  rL  r   	is_tensorr  r  r  	unsqueeze)	r  r  r  r=  r  r  rn  count_num_items_in_batchr+  s	            r   rE  Trainer.get_batch_samples  s   !{#A$$T.%9: $ " M!,,
 .. 6 ))5 	! $%(Xe)fXeu?+=+=d+C*H*H*JXe)f%g" )yy66%)%5%5%<%<=O%P%T%T%V"122%7%:%:6%B"99??Q&+=+A+A+Cq+H);)E)Ea)H&00I ! * *g~. s5   E/?	F +F3F /
E?>E?F FFry  c                    UR                   nUS:  n[        U5      (       a  [        U5      OSnUb]  [        XaR                  -  [        XaR                  -  S:  5      -   S5      nU(       a#  [        R                  " UR                  U-  5      nU(       a{  U R                  U5      nUR                   S:  a  UW-  [        XG-  S:  5      -   n	XC-  n
O[        R                  " UR                  5      n	U R                  U5      UR                  -  n
OXUR                   S:  a0  [        R                  n	UnX1R                   -  nUR                   U-  n
O[        SUR                    35      eU	WUU
UUU4$ )z
Calculates and returns the following values:
- `num_train_epochs`
- `num_update_steps_per_epoch`
- `num_examples`
- `num_train_samples`
- `epoch_based`
- `len_dataloader`
- `max_steps`
r   Nr   zYargs.max_steps must be set to a positive value if dataloader does not have a length, was )rj  ra   r<  r  r  r  r  r  rk  r$  sysmaxsizer  )r  r   r  ry  rj  r|  r}  rz  r$  rk  r{  s              r   r+  #Trainer.set_initial_training_values  s    NN	!m,6z,B,BZ %),"B"BBn'G'GG!KLM*&  IId&;&;>X&XY	 ,,Z8L~~!#,0J#JS:Q>N $ 
 %.$F!#'99T-B-B#C $($5$5j$ADDYDY$Y!^^a"{{)2&1NNBL $1G GNN#% 
 &
 	
r   ):r  r  r>  rb  r,  r  ro  r=  r  r6  rT  ry  r   r^  ru   r   r   rQ  r|  r}  r   r(  r   r,  r'  r~  r8  rc  rH  rO  rG  r  r  r)  r9  r  r  r  r{  rZ  r   rV  r   r#  rS  r  rX  rN  rY  r   rK  r   r   rj  ru  r   rp  rq  )NNNNNNNNNNr   NN)r  Nr  )NFN)F)TN)NNN)NNNNN)NN   minimizeNNr  )FN)NF)NNr  )Nr  )	NNNNNNNNN)zEnd of trainingTNN)r7  
__module____qualname____firstlineno____doc__trainer_pt_utilsr   r   r   r   r   r   r   r)   r   Moduleri   r
   r   r   r   r  r  r3   r#   r    r0   r	   rS   r   r9   r  r   r>  	OptimizerrZ  LambdaLRr   r   r  r  propertyr   setterr  r  r_  r  r  rQ  r  r  r  rl  rm  Samplerr  r  r  r   r  r
  r  r  r   r'  r.  r$  rV  r]  	parameterr  r`  staticmethodr<  r%  r$  r-  rH  r  ra  r[  r1  r  r  r  r  r  r\  r  rq  r  rn  r  rA  ra  rD  r  r  r*  r(  r5  r)  r6  r9  rT   rQ   r  rp  r  r|  r  r  rR  r  r  r  rh  r  r  ro  rP   rr  r,  r  rV   r  rR   r  r  r*  rV  re  r  r+  rw  rd  r  r  r  r*  r*  r3  rE  r+  __static_attributes__r   r   r   r   r   >  sC   \~ lk[+=wdhi :>"&04W[Y] >B04FJ59jvaehl!Ic_bii56Ic  Ic  -	Ic
  g@R&R STIc uWd3<.@BT%TUVIc #)+=?UWeef
Ic Xb/&9:;Ic $H-Ic "(N+;T+A"BCIc D12Ic (5;;#8#898EKKD\D\DeDe;ffgIc #+5ekk6K6K1LdSVX[S[n1\+]"^Ic  (0%,,9UW\WcWc9c0d'e!Ic jIcV %8$;< % % 1 1&<"	5< 	8 \;.@ ;xX[} ;B EI'%'4<SM'	'$00A 0XV[VaVaVfVfVnVnMo 0D OS!(,-4-4 -4 	-4
 Xwi1A1A1I1I&IJK-4 -4 !-4 
-4^
j 
(+g +(5;;CSCSC[C[:\ +Z%
sG|9L0M %
Yc %
N
 
J 
$Z Z 	 $s) 	 AFRFJ%UXX=O=O=Y=Y8Y2Z)[ J  DHw/w/(0(Aw/	sCxw/ w/r!3 !5;;CXCX !&Kz Kc K Z HSM S  62eNDcN,J&K 62pA%S#X0N*O AWZ Aeijmotjteu A0aC a!F 38u}} .-8Z| >B=A48	o (sDy)9 :o ^T#s(^T9:o 'tCy1	od imcHJ(X=tzx, hl'^R)_V$"L1If0id?1Bq5f1(56%9R LPKO+5;?=AR8^$4d3:6F$FGHR $Hd3:.>-?-F$GHR 	R
 d3i(R % 678R (N#3S#89:R 
wW%	&Rh_S%Z( _huo _QU _.5s):#; ellTWFW@X $d3ellC6G0H+H&I dSVX]^c^j^jlo^oXpSpNq  5HTN   aeN!YYN!(,S%c8I2J-J(KN!	N!`2;h2t 2
0t 
01:Xc] 1:4 1:fF>HSM F>P)L )LV	" 1FRW#"	c#"J:6 FJ+/!'	fuWd3<.@%@ABf d3i(f 	f
 
c5j	fR hn>t#>t2:492E>tad>t	>tH 04+/!'UuUu Uu 'tn	Uu
 d3i(Uu Uu 
Uun0 ,0g&yyg& S%c 1223g& #	g&
 d3i(g& 
x%x'=x?UU	Vg&Rc5s9J3K.K)L $%(3- %( #'!%,0$((,-148/348Hh3-Hh #Hh CcD()	Hh
 SMHh !Hh S$s)T)*Hh CcD01Hh sDIt+,Hh CcD01HhT@9D4 ):#"&J
 J
 J
 }	J

 3-J
 
J
h 04+/!'xqxq xq 'tn	xq
 d3i(xq xq 
xqt' %!Noxb
W +1Z>
%>
3=>
WZ>
r   r   (  r  r   rP  r  r_  importlib.metadatar   r   r  r  rg  r  r  ru  r  rY  r  r3  collections.abcr   r   pathlibr   typingr   r   r	   r
   r   integrationsr   huggingface_hub.utilsrl  r  r  r   r   torch.distributeddistributedrm  huggingface_hubr   r   r   	packagingr   r   torch.utils.datar   r   r   r   r   r  r   configuration_utilsr   data.data_collatorr   r   r   debug_utilsr   r   !feature_extraction_sequence_utilsr   feature_extraction_utilsr    r  r!   r"   image_processing_utilsr#   integrations.deepspeedr$   r%   r&   integrations.tpur'   	modelcardr(   modeling_utilsr)   r*   r+   models.auto.modeling_autor,   r-   optimizationr.   r/   processing_utilsr0   pytorch_utilsr1   r2   tokenization_utils_baser3   trainer_callbackr4   r5   r6   r7   r8   r9   r:   r;   r  r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   trainer_utilsrP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   r  rg   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r{   r|   r}   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   utils.deprecationr   utils.import_utilsr   utils.quantization_configr   r\  ra  utils.notebookr   r  r   r  torch_xla.core.xla_modelr   	xla_modelr  torch_xla.debug.metricsrG  rJ  rh  torch_xla.runtimeruntimer  	torch_xlaXLA_VERSIONr   r  torch_xla.distributed.spmdspmdr  !smdistributed.modelparallel.torchmodelparallelrt  smdistributed.modelparallelSMP_VERSIONrs  r   r   r   r   safetensors.torchr  r   r   r   r   r   r  accelerate.stater   r@  r   r   r   r   r   r   r   DATA_SAMPLERSr   accelerate.data_loaderr   r   r   r   r   r   rR  
get_loggerr7  r  r  rj  rm  ri  rU  rn  r  r   r   r   r   <module>rB     sB           	  	  
    #   @ @
 -     A A   c c  1 \ \ < G < ` 6 e e 1 & R R 3 , =	 	 	     ,      2 K J* * * * * * * * * * *V / ( 9 )) , 8 8))))"4$]];77==I_;``//" 33F 'k :gmmF>S Sgg %  :<1   #OM}}'(7==+AA>}}'(7==+BB@@/00>8$$8	7& 			H	% ) ) $ & 
pN
 pN
pN
r   