
    eThK                     z   S r SSKrSSKrSSKrSSKJr  SSKJrJr  SSKr	SSK
Jr  SSKJrJrJrJr  SSKJr  SS	KJr  \R*                  " \5      r\ " S
 S5      5       r " S S5      r\ " S S\5      5       r " S S5      r " S S\5      r " S S\5      r " S S\5      r " S S\5      r " S S\\5      r g)zJ
Callbacks to use with the Trainer class and customize the training loop.
    N)	dataclass)OptionalUnion)tqdm   )HPSearchBackendIntervalStrategySaveStrategy
has_length)TrainingArguments)loggingc                      \ rS rSr% SrSr\\   \S'   Sr	\
\S'   Sr\
\S'   Sr\
\S	'   Sr\
\S
'   Sr\
\S'   Sr\\
   \S'   Sr\
\S'   Sr\
\S'   Sr\\S'   Sr\\\\4      \S'   Sr\\   \S'   Sr\\
   \S'   Sr\\   \S'   Sr\\S'   Sr\\S'   Sr\\S'   Sr\\   \S'   Sr\\\ \\\
\4   4   \S'   Sr!\S   \S'   S r"S\4S jr#\$S\4S  j5       r%S! r&S" r'S#r(g)$TrainerState#   a  
A class containing the [`Trainer`] inner state that will be saved along the model and optimizer when checkpointing
and passed to the [`TrainerCallback`].

<Tip>

In all this class, one step is to be understood as one update step. When using gradient accumulation, one update
step may require several forward and backward passes: if you use `gradient_accumulation_steps=n`, then one update
step requires going through *n* batches.

</Tip>

Args:
    epoch (`float`, *optional*):
        Only set during training, will represent the epoch the training is at (the decimal part being the
        percentage of the current epoch completed).
    global_step (`int`, *optional*, defaults to 0):
        During training, represents the number of update steps completed.
    max_steps (`int`, *optional*, defaults to 0):
        The number of update steps to do during the current training.
    logging_steps (`int`, *optional*, defaults to 500):
        Log every X updates steps
    eval_steps (`int`, *optional*):
        Run an evaluation every X steps.
    save_steps (`int`, *optional*, defaults to 500):
        Save checkpoint every X updates steps.
    train_batch_size (`int`, *optional*):
        The batch size for the training dataloader. Only needed when
        `auto_find_batch_size` has been used.
    num_input_tokens_seen (`int`, *optional*, defaults to 0):
        When tracking the inputs tokens, the number of tokens seen during training (number of input tokens, not the
        number of prediction tokens).
    total_flos (`float`, *optional*, defaults to 0):
        The total number of floating operations done by the model since the beginning of training (stored as floats
        to avoid overflow).
    log_history (`List[Dict[str, float]]`, *optional*):
        The list of logs done since the beginning of training.
    best_metric (`float`, *optional*):
        When tracking the best model, the value of the best metric encountered so far.
    best_global_step (`int`, *optional*):
        When tracking the best model, the step at which the best metric was encountered.
        Used for setting `best_model_checkpoint`.
    best_model_checkpoint (`str`, *optional*):
        When tracking the best model, the value of the name of the checkpoint for the best model encountered so
        far.
    is_local_process_zero (`bool`, *optional*, defaults to `True`):
        Whether or not this process is the local (e.g., on one machine if training in a distributed fashion on
        several machines) main process.
    is_world_process_zero (`bool`, *optional*, defaults to `True`):
        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).
    is_hyper_param_search (`bool`, *optional*, defaults to `False`):
        Whether we are in the process of a hyper parameter search using Trainer.hyperparameter_search. This will
        impact the way data will be logged in TensorBoard.
    stateful_callbacks (`List[StatefulTrainerCallback]`, *optional*):
        Callbacks attached to the `Trainer` that should have their states be saved or restored.
        Relevant callbacks should implement a `state` and `from_state` function.
Nepochr   global_step	max_stepsi  logging_steps
eval_steps
save_stepstrain_batch_sizenum_train_epochsnum_input_tokens_seen
total_floslog_historybest_metricbest_global_stepbest_model_checkpointTis_local_process_zerois_world_process_zeroFis_hyper_param_search
trial_nametrial_paramsTrainerCallbackstateful_callbacksc                     U R                   c  / U l         U R                  c  0 U l        g [        U R                  [        5      (       a  g 0 nU R                   H  n[        U[        5      (       d  [        S[        U5       35      eUR                  R                  nX1;   aA  [        X   [        5      (       d  X   /X'   X   R                  UR                  5       5        M  UR                  5       X'   M     Xl        g )NzNAll callbacks passed to be saved must inherit `ExportableState`, but received )r   r%   
isinstancedictExportableState	TypeErrortype	__class____name__listappendstate)selfr%   callbacknames       U/var/www/auris/envauris/lib/python3.13/site-packages/transformers/trainer_callback.py__post_init__TrainerState.__post_init__u   s    #!D""*&(D#//66 "$ 33!(_>>#himnviwhxy   ))22- &&8&>EE4F4L3M*0&,33HNN4DE/7~~/?&, 4 '9#    	json_pathc                     [         R                  " [        R                  " U 5      SSS9S-   n[	        USSS9 nUR                  U5        SSS5        g! , (       d  f       g= f)	zDSave the content of this instance in JSON format inside `json_path`.   T)indent	sort_keys
wutf-8encodingN)jsondumpsdataclassesasdictopenwrite)r1   r8   json_stringfs       r4   save_to_jsonTrainerState.save_to_json   sK    jj!3!3D!9!tTW[[)S73qGGK  433s   A
A"c                     [        USS9 nUR                  5       nSSS5        U " S0 [        R                  " W5      D6$ ! , (       d  f       N*= f)z3Create an instance from the content of `json_path`.r?   r@   N )rF   readrB   loads)clsr8   rI   texts       r4   load_from_jsonTrainerState.load_from_json   s@     )g.!668D /&TZZ%&& /.s   A  
Ac                     S HC  n[        X S35      nUc  M  US:  a  [        R                  " X$-  5      n[        X S3U5        ME     g)zt
Calculates and stores the absolute value for logging,
eval, and save steps based on if it was a proportion
or not.
)r   evalsave_stepsNr   )getattrmathceilsetattr)r1   argsr   	step_kind	num_stepss        r4   compute_stepsTrainerState.compute_steps   sN     5I6&:;I$q= $		)*? @I62I> 5r7   c                 v   UR                   b-  UR                  b   UR                  UR                  5      U l        SU l        Ub?  SSKJn  UR                  [        R                  :X  a  UR                  OUnU" U5      U l        X l
        X0l        UR                  5       U l        UR                  5       U l        g)z9
Stores the initial training references needed in `self`
Nr   )	hp_params)hp_name_trialr"   r#   transformers.integrationsrb   hp_search_backendr   SIGOPTassignmentsr   r   r   r    )r1   trainerr   r   trialrb   rh   s          r4   init_training_references%TrainerState.init_training_references   s     ??&7>>+E &oognn=DO ;/6/H/HOLbLb/b%++hmK )+ 6D" 0%,%B%B%D"%,%B%B%D"r7   )r   r    r   r   r   r%   r"   r#   ))r-   
__module____qualname____firstlineno____doc__r   r   float__annotations__r   intr   r   r   r   r   r   r   r   r   r.   r(   strr   r   r   r   boolr    r!   r"   r#   r   r%   r5   rJ   classmethodrR   r_   rk   __static_attributes__rM   r7   r4   r   r   #   sV   9v "E8E?!KIsM3JJ&*hsm*c!"3"J*.Kd3:&'.#'K%'&*hsm*+/8C=/"&4&"&4&"'4' $J$<@L$sE#uc4"7889@26./696!c ! 's ' '?Er7   r   c                   6    \ rS rSrSrS\4S jr\S 5       rSr	g)r)      a  
A class for objects that include the ability to have its state
be saved during `Trainer._save_checkpoint` and loaded back in during
`Trainer._load_from_checkpoint`.

These must implement a `state` function that gets called during the respective
Trainer function call. It should only include parameters and attributes needed to
recreate the state at a particular time, to avoid utilizing pickle/maintain standard
file IO writing.

Example:

```python
class EarlyStoppingCallback(TrainerCallback, ExportableState):
    def __init__(self, early_stopping_patience: int = 1, early_stopping_threshold: Optional[float] = 0.0):
        self.early_stopping_patience = early_stopping_patience
        self.early_stopping_threshold = early_stopping_threshold
        # early_stopping_patience_counter denotes the number of times validation metrics failed to improve.
        self.early_stopping_patience_counter = 0

    def state(self) -> dict:
        return {
            "args": {
                "early_stopping_patience": self.early_stopping_patience,
                "early_stopping_threshold": self.early_stopping_threshold,
            },
            "attributes": {
                "early_stopping_patience_counter": self.early_stopping_patience_counter,
            }
        }
```returnc                     [        S5      e)Nz<You must implement a `state` function to utilize this class.)NotImplementedErrorr1   s    r4   r0   ExportableState.state   s    !"`aar7   c                 l    U " S0 US   D6nUS   R                  5        H  u  p4[        X#U5        M     U$ )Nr\   
attributesrM   )itemsr[   )rP   r0   instancekvs        r4   
from_stateExportableState.from_state   s<    'v','--/DAH# 0r7   rM   N)
r-   rm   rn   ro   rp   r(   r0   rv   r   rw   rM   r7   r4   r)   r)      s*    @bt b  r7   r)   c                       \ rS rSr% SrSr\\S'   Sr\\S'   Sr	\\S'   Sr
\\S'   Sr\\S'   S	 rS
 rS rS\4S jrSrg)TrainerControl   a  
A class that handles the [`Trainer`] control flow. This class is used by the [`TrainerCallback`] to activate some
switches in the training loop.

Args:
    should_training_stop (`bool`, *optional*, defaults to `False`):
        Whether or not the training should be interrupted.

        If `True`, this variable will not be set back to `False`. The training will just stop.
    should_epoch_stop (`bool`, *optional*, defaults to `False`):
        Whether or not the current epoch should be interrupted.

        If `True`, this variable will be set back to `False` at the beginning of the next epoch.
    should_save (`bool`, *optional*, defaults to `False`):
        Whether or not the model should be saved at this step.

        If `True`, this variable will be set back to `False` at the beginning of the next step.
    should_evaluate (`bool`, *optional*, defaults to `False`):
        Whether or not the model should be evaluated at this step.

        If `True`, this variable will be set back to `False` at the beginning of the next step.
    should_log (`bool`, *optional*, defaults to `False`):
        Whether or not the logs should be reported at this step.

        If `True`, this variable will be set back to `False` at the beginning of the next step.
Fshould_training_stopshould_epoch_stopshould_saveshould_evaluate
should_logc                     SU l         g)z<Internal method that resets the variable for a new training.FN)r   r}   s    r4   _new_trainingTrainerControl._new_training  s
    $)!r7   c                     SU l         g)z9Internal method that resets the variable for a new epoch.FN)r   r}   s    r4   
_new_epochTrainerControl._new_epoch  s
    !&r7   c                 .    SU l         SU l        SU l        g)z8Internal method that resets the variable for a new step.FN)r   r   r   r}   s    r4   	_new_stepTrainerControl._new_step  s     $r7   rz   c                 |    U R                   U R                  U R                  U R                  U R                  S.0 S.$ )Nr   r   r   r   r   r\   r   r   r}   s    r4   r0   TrainerControl.state  sC     )-(A(A%)%;%;#//#'#7#7"oo 	
 		
r7   )r   r   r   r   r   N)r-   rm   rn   ro   rp   r   ru   rr   r   r   r   r   r   r   r   r(   r0   rw   rM   r7   r4   r   r      sX    6 "'$&#t#K!OT!J*' 

t 

r7   r   c                   b   \ rS rSrSrS\S\S\4S jrS\S\S\4S jr	S\S\S\4S jr
S\S\S\4S	 jrS\S\S\4S
 jrS\S\S\4S jrS\S\S\4S jrS\S\S\4S jrS\S\S\4S jrS\S\S\4S jrS\S\S\4S jrS\S\S\4S jrS\S\S\4S jrS\S\S\4S jrS\S\S\4S jrSrg)r$   i)  a	  
A class for objects that will inspect the state of the training loop at some events and take some decisions. At
each of those events the following arguments are available:

Args:
    args ([`TrainingArguments`]):
        The training arguments used to instantiate the [`Trainer`].
    state ([`TrainerState`]):
        The current state of the [`Trainer`].
    control ([`TrainerControl`]):
        The object that is returned to the [`Trainer`] and can be used to make some decisions.
    model ([`PreTrainedModel`] or `torch.nn.Module`):
        The model being trained.
    tokenizer ([`PreTrainedTokenizer`]):
        The tokenizer used for encoding the data. This is deprecated in favour of `processing_class`.
    processing_class ([`PreTrainedTokenizer` or `BaseImageProcessor` or `ProcessorMixin` or `FeatureExtractionMixin`]):
        The processing class used for encoding the data. Can be a tokenizer, a processor, an image processor or a feature extractor.
    optimizer (`torch.optim.Optimizer`):
        The optimizer used for the training steps.
    lr_scheduler (`torch.optim.lr_scheduler.LambdaLR`):
        The scheduler used for setting the learning rate.
    train_dataloader (`torch.utils.data.DataLoader`, *optional*):
        The current dataloader used for training.
    eval_dataloader (`torch.utils.data.DataLoader`, *optional*):
        The current dataloader used for evaluation.
    metrics (`Dict[str, float]`):
        The metrics computed by the last evaluation phase.

        Those are only accessible in the event `on_evaluate`.
    logs  (`Dict[str, float]`):
        The values to log.

        Those are only accessible in the event `on_log`.

The `control` object is the only one that can be changed by the callback, in which case the event that changes it
should return the modified version.

The argument `args`, `state` and `control` are positionals for all events, all the others are grouped in `kwargs`.
You can unpack the ones you need in the signature of the event using them. As an example, see the code of the
simple [`~transformers.PrinterCallback`].

Example:

```python
class PrinterCallback(TrainerCallback):
    def on_log(self, args, state, control, logs=None, **kwargs):
        _ = logs.pop("total_flos", None)
        if state.is_local_process_zero:
            print(logs)
```r\   r0   controlc                     g)zC
Event called at the end of the initialization of the [`Trainer`].
NrM   r1   r\   r0   r   kwargss        r4   on_init_endTrainerCallback.on_init_end^       	r7   c                     g)z,
Event called at the beginning of training.
NrM   r   s        r4   on_train_beginTrainerCallback.on_train_begind  r   r7   c                     g)z&
Event called at the end of training.
NrM   r   s        r4   on_train_endTrainerCallback.on_train_endj  r   r7   c                     g)z,
Event called at the beginning of an epoch.
NrM   r   s        r4   on_epoch_beginTrainerCallback.on_epoch_beginp  r   r7   c                     g)z&
Event called at the end of an epoch.
NrM   r   s        r4   on_epoch_endTrainerCallback.on_epoch_endv  r   r7   c                     g)z
Event called at the beginning of a training step. If using gradient accumulation, one training step might take
several inputs.
NrM   r   s        r4   on_step_beginTrainerCallback.on_step_begin|      
 	r7   c                     g)zf
Event called before the optimizer step but after gradient clipping. Useful for monitoring gradients.
NrM   r   s        r4   on_pre_optimizer_step%TrainerCallback.on_pre_optimizer_step  r   r7   c                     g)zm
Event called after the optimizer step but before gradients are zeroed out. Useful for monitoring gradients.
NrM   r   s        r4   on_optimizer_step!TrainerCallback.on_optimizer_step  r   r7   c                     g)zE
Event called at the end of an substep during gradient accumulation.
NrM   r   s        r4   on_substep_endTrainerCallback.on_substep_end  r   r7   c                     g)zz
Event called at the end of a training step. If using gradient accumulation, one training step might take
several inputs.
NrM   r   s        r4   on_step_endTrainerCallback.on_step_end  r   r7   c                     g)z)
Event called after an evaluation phase.
NrM   r   s        r4   on_evaluateTrainerCallback.on_evaluate  r   r7   c                     g)z-
Event called after a successful prediction.
NrM   )r1   r\   r0   r   metricsr   s         r4   
on_predictTrainerCallback.on_predict  r   r7   c                     g)z'
Event called after a checkpoint save.
NrM   r   s        r4   on_saveTrainerCallback.on_save  r   r7   c                     g)z+
Event called after logging the last logs.
NrM   r   s        r4   on_logTrainerCallback.on_log  r   r7   c                     g)z'
Event called after a prediction step.
NrM   r   s        r4   on_prediction_step"TrainerCallback.on_prediction_step  r   r7   rM   N)r-   rm   rn   ro   rp   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rw   rM   r7   r4   r$   r$   )  s   1f 1 , Q_ #4 \ Tb !2 < R` #4 \ Tb !2 < R` "3 L Sa *; L [i &7  We #4 \ Tb  1 , Q_  1 , Q_ 0  P^ - l ^ , \ N '8  Xf r7   r$   c                      \ rS rSrSrS rS rS rS r\	S 5       r
S\S	\S
\4S jrS\S	\S
\4S jrS\S	\S
\4S jrS\S	\S
\4S jrS\S	\S
\4S jrS\S	\S
\4S jrS\S	\S
\4S jrS\S	\S
\4S jrS\S	\S
\4S jrS\S	\S
\4S jrS\S	\S
\4S jrS\S	\S
\4S jrS\S	\S
\4S jrS\S	\S
\4S jrS\S	\S
\4S jrS rSrg)CallbackHandleri  z>Internal class that just calls the list of callbacks in order.c                    / U l         U H  nU R                  U5        M     X l        X0l        X@l        XPl        S U l        S U l        [        S U R                    5       5      (       d#  [        R                  SU R                  -   5        g g )Nc              3   B   #    U  H  n[        U[        5      v   M     g 7fN)r'   DefaultFlowCallback.0cbs     r4   	<genexpr>+CallbackHandler.__init__.<locals>.<genexpr>  s     P2:b"566s   zThe Trainer will not work properly if you don't have a `DefaultFlowCallback` in its callbacks. You
should add one before training with `trainer.add_callback(DefaultFlowCallback). The current list ofcallbacks is
:)	callbacksadd_callbackmodelprocessing_class	optimizerlr_schedulertrain_dataloadereval_dataloaderanyloggerwarningcallback_list)r1   r   r   r   r   r   r   s          r4   __init__CallbackHandler.__init__  s    Bb! 
 0"( $#PPPPNN$ $$% Qr7   c                 j   [        U[        5      (       a  U" 5       OUn[        U[        5      (       a  UOUR                  nX0R                   Vs/ s H  oDR                  PM     sn;   a)  [        R                  SU S3S-   U R                  -   5        U R                  R                  U5        g s  snf )NzYou are adding a zH to the callbacks of this Trainer, but there is already one. The currentzlist of callbacks is
:)r'   r+   r,   r   r   r   r   r/   )r1   r2   r   cb_classcs        r4   r   CallbackHandler.add_callback  s    %h55XZ8)(D998x?Q?Q^^<^^<<NN#H:-uv+,$$%
 	b! =s   B0c                 "   [        U[        5      (       aC  U R                   H2  n[        X!5      (       d  M  U R                  R                  U5        Us  $    g U R                   H'  nX!:X  d  M
  U R                  R                  U5        Us  $    g r   r'   r+   r   remover1   r2   r   s      r4   pop_callbackCallbackHandler.pop_callback  sk    h%%nnb++NN))"-I %
 nn>NN))"-I %r7   c                     [        U[        5      (       aA  U R                   H0  n[        X!5      (       d  M  U R                  R                  U5          g    g U R                  R                  U5        g r   r   r   s      r4   remove_callbackCallbackHandler.remove_callback  sQ    h%%nnb++NN))"- %
 NN!!(+r7   c                 F    SR                  S U R                   5       5      $ )Nr=   c              3   L   #    U  H  oR                   R                  v   M     g 7fr   )r,   r-   r   s     r4   r   0CallbackHandler.callback_list.<locals>.<genexpr>  s     H2..s   "$)joinr   r}   s    r4   r   CallbackHandler.callback_list  s    yyHHHHr7   r\   r0   r   c                 (    U R                  SXU5      $ )Nr   
call_eventr1   r\   r0   r   s       r4   r   CallbackHandler.on_init_end      }d7CCr7   c                 6    SUl         U R                  SXU5      $ )NFr   )r   r   r   s       r4   r   CallbackHandler.on_train_begin  s    ',$/gFFr7   c                 (    U R                  SXU5      $ )Nr   r   r   s       r4   r   CallbackHandler.on_train_end      ~tGDDr7   c                 6    SUl         U R                  SXU5      $ )NFr   )r   r   r   s       r4   r   CallbackHandler.on_epoch_begin  s    $)!/gFFr7   c                 (    U R                  SXU5      $ )Nr   r   r   s       r4   r   CallbackHandler.on_epoch_end  r  r7   c                 R    SUl         SUl        SUl        U R                  SXU5      $ )NFr   )r   r   r   r   r   s       r4   r   CallbackHandler.on_step_begin  s-    ""'#WEEr7   c                 (    U R                  SXU5      $ )Nr   r   r   s       r4   r   %CallbackHandler.on_pre_optimizer_step  s    6WMMr7   c                 (    U R                  SXU5      $ )Nr   r   r   s       r4   r   !CallbackHandler.on_optimizer_step  s    2DIIr7   c                 (    U R                  SXU5      $ )Nr   r   r   s       r4   r   CallbackHandler.on_substep_end  s    /gFFr7   c                 (    U R                  SXU5      $ )Nr   r   r   s       r4   r   CallbackHandler.on_step_end  r   r7   c                 2    SUl         U R                  SXX4S9$ )NFr   r   )r   r   r1   r\   r0   r   r   s        r4   r   CallbackHandler.on_evaluate  s    "'}d7TTr7   c                 $    U R                  SXX4S9$ )Nr   r  r   r  s        r4   r   CallbackHandler.on_predict  s    |T'SSr7   c                 6    SUl         U R                  SXU5      $ )NFr   )r   r   r   s       r4   r   CallbackHandler.on_save  s    #y$w??r7   c                 2    SUl         U R                  SXX4S9$ )NFr   )logs)r   r   )r1   r\   r0   r   r  s        r4   r   CallbackHandler.on_log#  s    "xgIIr7   c                 (    U R                  SXU5      $ )Nr   r   r   s       r4   r   "CallbackHandler.on_prediction_step'  s    3T'JJr7   c                     U R                    Ha  n[        Xa5      " UUU4U R                  U R                  U R                  U R
                  U R                  U R                  S.UD6nUc  M_  UnMc     U$ )N)r   r   r   r   r   r   )r   rX   r   r   r   r   r   r   )r1   eventr\   r0   r   r   r2   results           r4   r   CallbackHandler.call_event*  s    HX- jj!%!6!6..!..!%!6!6 $ 4 4 F !  '  r7   )r   r   r   r   r   r   r   N)r-   rm   rn   ro   rp   r   r   r   r   propertyr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rw   rM   r7   r4   r   r     s   H&	"
, I ID 1 D, DQ_ DG#4 G\ GTb GE!2 E< ER` EG#4 G\ GTb GE!2 E< ER` EF"3 FL FSa FN*; NL N[i NJ&7 J JWe JG#4 G\ GTb GD 1 D, DQ_ DU 1 U, UQ_ UT0 T TP^ T@- @l @^ @J, J\ JN JK'8 K KXf Kr7   r   c                   D    \ rS rSrSrS\S\S\4S jrS\S\S\4S jr	Sr
g	)
r   i>  zp
A [`TrainerCallback`] that handles the default flow of the training loop for logs, evaluation and checkpoints.
r\   r0   r   c                    UR                   S:X  a  UR                  (       a  SUl        UR                  [        R
                  :X  a$  UR                   UR                  -  S:X  a  SUl        UR                  [        R
                  :X  a>  UR                   UR                  -  S:X  a!  UR                  UR                   ::  a  SUl
        UR                  [        R
                  :X  a4  UR                  S:  a$  UR                   UR                  -  S:X  a  SUl        UR                   UR                  :  a,  SUl        UR                  [        R
                  :X  a  SUl        U$ )Nr   Tr   )r   logging_first_stepr   logging_strategyr	   STEPSr   eval_strategyr   
eval_delayr   save_strategyr
   r   r   r   r   r   s        r4   r   DefaultFlowCallback.on_step_endC  s#   !d&=&=!%G  $4$:$::u?P?PSXSfSf?fjk?k!%G "2"8"88!!E$4$4495#4#44&*G# ,"4"44  1$!!E$4$449"&G /+/G(!!\%7%77&*#r7   c                    UR                   [        R                  :X  a  SUl        UR                  [        R                  :X  a!  UR
                  UR                  ::  a  SUl        UR                  [        R                  :X  a  SUl
        U$ )NT)r)  r	   EPOCHr   r+  r,  r   r   r-  r
   r   r   s        r4   r    DefaultFlowCallback.on_epoch_endc  sp      $4$:$::!%G !1!7!77DOOu{{<Z&*G# !3!33"&Gr7   rM   N)r-   rm   rn   ro   rp   r   r   r   r   r   rw   rM   r7   r4   r   r   >  s@     1 , Q_ @!2 < R` r7   r   c                   \    \ rS rSrSrSS\4S jjrS rS rSS jr	S	 r
S
 rSS jrS rSrg)ProgressCallbackis  z
A [`TrainerCallback`] that displays the progress of training or evaluation.
You can modify `max_str_len` to control how long strings are truncated when logging.
max_str_lenc                 ,    SU l         SU l        Xl        g)z
Initialize the callback with optional max_str_len parameter to control string truncation length.

Args:
    max_str_len (`int`):
        Maximum length of strings to display in logs.
        Longer strings will be truncated with a message.
N)training_barprediction_barr4  )r1   r4  s     r4   r   ProgressCallback.__init__y  s     !"&r7   c                 f    UR                   (       a  [        UR                  SS9U l        SU l        g )NT)totaldynamic_ncolsr   )r    r   r   r6  current_stepr   s        r4   r   ProgressCallback.on_train_begin  s&    && $5??$ ODr7   c                     UR                   (       aD  U R                  R                  UR                  U R                  -
  5        UR                  U l        g g r   )r    r6  updater   r<  r   s        r4   r   ProgressCallback.on_step_end  sC    &&$$U%6%69J9J%JK % 1 1D 'r7   Nc                     UR                   (       a_  [        U5      (       aN  U R                  c%  [        [	        U5      U R
                  S L SS9U l        U R                  R                  S5        g g g )NT)r:  leaver;  r   )r    r   r7  r   lenr6  r?  )r1   r\   r0   r   r   r   s         r4   r   #ProgressCallback.on_prediction_step  se    &&:o+F+F""*&*o.d6G6G46O_c'# &&q) ,G&r7   c                     UR                   (       a/  U R                  b  U R                  R                  5         S U l        g g r   r    r7  closer   s        r4   r   ProgressCallback.on_evaluate  6    &&"".##))+"&D 'r7   c                     UR                   (       a/  U R                  b  U R                  R                  5         S U l        g g r   rF  r   s        r4   r   ProgressCallback.on_predict  rI  r7   c                    UR                   (       a  U R                  b  0 nUR                  5        HW  u  px[        U[        5      (       a9  [        U5      U R                  :  a   S[        U5       SU R                   S3Xg'   MS  XU'   MY     UR                  SS 5      n	SU;   a  [        US   S5      US'   U R                  R                  [	        U5      5        g g g )Nz%[String too long to display, length: z > z/. Consider increasing `max_str_len` if needed.]r   r   r:   )
r    r6  r   r'   rt   rC  r4  poproundrG   )
r1   r\   r0   r   r  r   shallow_logsr   r   _s
             r4   r   ProgressCallback.on_log  s    &&4+<+<+H L

a%%#a&43C3C*C?Axs4K[K[J\ ]H H !O
 '(O %   t4A,&(-l7.CQ(GW%##C$56! ,I&r7   c                 j    UR                   (       a"  U R                  R                  5         S U l        g g r   )r    r6  rG  r   s        r4   r   ProgressCallback.on_train_end  s*    &&##% $D 'r7   )r<  r4  r7  r6  )d   r   )r-   rm   rn   ro   rp   rs   r   r   r   r   r   r   r   r   rw   rM   r7   r4   r3  r3  s  s6    
'C '
2
*''7&%r7   r3  c                   "    \ rS rSrSrSS jrSrg)PrinterCallbacki  z7
A bare [`TrainerCallback`] that just prints the logs.
Nc                 b    UR                  SS 5      nUR                  (       a  [        U5        g g )Nr   )rM  r   print)r1   r\   r0   r   r  r   rP  s          r4   r   PrinterCallback.on_log  s'    HH\4(&&$K 'r7   rM   r   )r-   rm   rn   ro   rp   r   rw   rM   r7   r4   rV  rV    s    r7   rV  c                   T    \ rS rSrSrSS\S\\   4S jjrS r	S r
S rS	\4S
 jrSrg)EarlyStoppingCallbacki  a  
A [`TrainerCallback`] that handles early stopping.

Args:
    early_stopping_patience (`int`):
        Use with `metric_for_best_model` to stop training when the specified metric worsens for
        `early_stopping_patience` evaluation calls.
    early_stopping_threshold(`float`, *optional*):
        Use with TrainingArguments `metric_for_best_model` and `early_stopping_patience` to denote how much the
        specified metric must improve to satisfy early stopping conditions. `

This callback depends on [`TrainingArguments`] argument *load_best_model_at_end* functionality to set best_metric
in [`TrainerState`]. Note that if the [`TrainingArguments`] argument *save_steps* differs from *eval_steps*, the
early stopping will not occur until the next save step.
early_stopping_patienceearly_stopping_thresholdc                 *    Xl         X l        SU l        g )Nr   r\  r]  early_stopping_patience_counter)r1   r\  r]  s      r4   r   EarlyStoppingCallback.__init__  s    '>$(@%/0,r7   c                 2   UR                   (       a  [        R                  O[        R                  nUR                  b<  U" XBR                  5      (       a-  [        XBR                  -
  5      U R                  :  a  SU l        g U =R                  S-  sl        g )Nr   r   )greater_is_betternpgreaterlessr   absr]  r`  )r1   r\   r0   r   metric_valueoperators         r4   check_metric_value(EarlyStoppingCallback.check_metric_value  sk    !%!7!72::RWW$\#4#455L#4#4458U8UU34D000A50r7   c                     UR                   (       d  [        R                  S5        UR                  c   S5       eUR                  [
        R                  :w  d   S5       eg )NzUsing EarlyStoppingCallback without load_best_model_at_end=True. Once training is finished, the best model will not be loaded automatically.zBEarlyStoppingCallback requires metric_for_best_model to be definedzAEarlyStoppingCallback requires IntervalStrategy of steps or epoch)load_best_model_at_endr   r   metric_for_best_modelr+  r	   NOr   s        r4   r   $EarlyStoppingCallback.on_train_begin  sb    **NN^ ))5 	
P	
5 !!%5%8%88 	
O	
8r7   c                    UR                   nUR                  S5      (       d  SU 3nUR                  U5      nUc  [        R	                  SU S35        g U R                  XX75        U R                  U R                  :  a  SUl        g g )Neval_z@early stopping required metric_for_best_model, but did not find z so early stopping is disabledT)	rn  
startswithgetr   r   rj  r`  r\  r   )r1   r\   r0   r   r   r   metric_to_checkrh  s           r4   r   !EarlyStoppingCallback.on_evaluate  s    44))'22 %o%67O{{?3NNRSbRc d  WC//43O3OO+/G( Pr7   rz   c                 R    U R                   U R                  S.SU R                  0S.$ )N)r\  r]  r`  r   r_  r}   s    r4   r0   EarlyStoppingCallback.state  s7     ,0+G+G,0,I,I
 243W3W
 	
r7   )r\  r`  r]  N)r   g        )r-   rm   rn   ro   rp   rs   r   rq   r   rj  r   r   r(   r0   rw   rM   r7   r4   r[  r[    s<     1 1S[\aSb 1	6
0"	
t 	
r7   r[  )!rp   rD   rB   rY   r   typingr   r   numpyrd  	tqdm.autor   trainer_utilsr   r	   r
   r   training_argsr   utilsr   
get_loggerr-   r   r   r)   r   r$   r   r   r3  rV  r[  rM   r7   r4   <module>r     s       ! "   V V ,  
		H	% XE XE XEv) )X :
_ :
 :
zO Od@o @F2/ 2jG% G%To I
O_ I
r7   