o
    hn                    @   s  d Z ddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlmZmZ ddlmZ ddlmZ ddlmZmZmZmZmZmZ ddlZddlZddlmZm Z  dd	lm!Z" dd
l#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z* e*+e,Z-e) rddl.Z.dZ/z'ej0"dZ1dZ2ej"3e1ej"3e/kZ4ddl5Z5e5j67ddurdZ8ndZ8W n ej0j9e:e;e<e=e>fy   dZ1dZ2dZ4dZ8Y nw ej?@ddupej?@dduZAereArzej0"dZBe-CdeB d W n, ej0j9y   zej0"dZBe-CdeB d W n ej0j9y   dZAY nw Y nw ddlmDZD ddlEmFZFmGZG ddlHmIZImJZJmKZK ddlLmMZM ddl#mNZNmOZO dd ZPdd ZQdd ZRd d! ZSd"d# ZTd$d% ZUd&d' ZVd(d) ZWd*d+ ZXd,d- ZYd.d/ ZZd0d1 Z[d2d3 Z\d4d5 Z]d6d7 Z^d8d9 Z_d:d; Z`d<d= Zad>ebd?ecd@eJfdAdBZdd>ebd?ecd@eJfdCdDZed>ebd?ecd@eJfdEdFZfd>ebd?ecd@eJfdGdHZgdIdJ ZhdKdL ZiG dMdN dNeGZjdOedPecfdQdRZkG dSdT dTeceZlG dUdV dVeGZmG dWdX dXeGZnG dYdZ dZeGZoG d[d\ d\eGZpG d]d^ d^epZqG d_d` d`erZsG dadb dbeGZtG dcdd ddeGZuG dedf dfeGZvG dgdh dheGZwG didj djeGZxG dkdl dleGZyeoenepetejemeueveqewexeydmZzdndo Z{dS )pz+
Integrations with other Python libraries.
    N)asdictfields)Enum)Path)TYPE_CHECKINGAnyDictLiteralOptionalUnion   )PreTrainedModelTFPreTrainedModel)__version__)PushToHubMixinflatten_dictis_datasets_availableis_pandas_availableis_tf_availableis_torch_availableloggingz3.43.2comet_mlTzcomet.api_keyFneptunezneptune-clientzNeptune version z available.zNeptune-client version )	modelcard)ProgressCallbackTrainerCallback)PREFIX_CHECKPOINT_DIRBestRunIntervalStrategy)ParallelMode)ENV_VARS_TRUE_VALUESis_torch_xla_availablec                   C   s2   t dd tv rtd dS tjdd uS )NWANDB_DISABLED zUsing the `WANDB_DISABLED` environment variable is deprecated and will be removed in v5. Use the --report_to flag to control the integrations used for logging result (for instance --report_to none).Fwandb)	osgetenvupperr    loggerwarning	importlibutil	find_spec r-   r-   /var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/transformers/integrations/integration_utils.pyis_wandb_availablea   s   r/   c                   C      t jdd uS )Nclearmlr*   r+   r,   r-   r-   r-   r.   is_clearml_availablel      r3   c                   C   sd   t dd dkrtd dS tdu rdS tdu r%tdttt dS t	du r0td dS dS )	N
COMET_MODEr#   DISABLEDzUsing the `COMET_MODE=DISABLED` environment variable is deprecated and will be removed in v5. Use the --report_to flag to control the integrations used for logging result (for instance --report_to none).Fzcomet_ml version %s is installed, but version %s or higher is required. Please update comet_ml to the latest version to enable Comet logging with pip install 'comet-ml>=%s'.a#  comet_ml is installed but the Comet API Key is not configured. Please set the `COMET_API_KEY` environment variable to enable Comet logging. Check out the documentation for other ways of configuring it: https://www.comet.com/docs/v2/guides/experiment-management/configure-sdk/#set-the-api-keyT)
r%   r&   r'   r(   r)   _is_comet_installed_is_comet_recent_enough_comet_version_MIN_COMET_VERSION_is_comet_configuredr-   r-   r-   r.   is_comet_availablep   s*   r<   c                   C   s    t jdd upt jdd uS )NtensorboardtensorboardXr2   r-   r-   r-   r.   is_tensorboard_available   s    r?   c                   C   r0   )Noptunar2   r-   r-   r-   r.   is_optuna_available   r4   rA   c                   C   r0   )Nrayr2   r-   r-   r-   r.   is_ray_available   r4   rC   c                   C      t  sdS tjdd uS )NFzray.tune)rC   r*   r+   r,   r-   r-   r-   r.   is_ray_tune_available      rE   c                   C   r0   )Nsigoptr2   r-   r-   r-   r.   is_sigopt_available   r4   rH   c                   C   s8   t jdd u r
dS t jdd u rdS t jdd uS )NazuremlFzazureml.corezazureml.core.runr2   r-   r-   r-   r.   is_azureml_available   s
   rJ   c                   C   s(   t dd dkrdS tjdd uS )NDISABLE_MLFLOW_INTEGRATIONFALSETRUEFmlflow)r%   r&   r'   r*   r+   r,   r-   r-   r-   r.   is_mlflow_available   s   rO   c                   C   s   d t jdt jdfvS )NdagshubrN   r2   r-   r-   r-   r.   is_dagshub_available   s   rQ   c                   C   s   t S N)_has_neptuner-   r-   r-   r.   is_neptune_available   s   rT   c                   C   r0   )N
codecarbonr2   r-   r-   r-   r.   is_codecarbon_available   r4   rV   c                   C   r0   )Nflytekitr2   r-   r-   r-   r.   is_flytekit_available   r4   rX   c                   C   rD   )NFzflytekitplugins.deck)rX   r*   r+   r,   r-   r-   r-   r.    is_flyte_deck_standard_available   rF   rY   c                   C   r0   )Ndvcliver2   r-   r-   r-   r.   is_dvclive_available   r4   r[   c                   C   r0   )Nswanlabr2   r-   r-   r-   r.   is_swanlab_available   r4   r]   c                 C   sn   t  rdd l}t| |jjr| jS t rt| tr| S t r%t| tr%| S t	 r/t| tr/| S t
d| j )Nr   zUnknown type for trial )rA   r@   
isinstancetrial	BaseTrialparamsrE   dictrH   r/   RuntimeError	__class__)r_   r@   r-   r-   r.   	hp_params   s   


re   n_trials	directionreturnc                    s\  dd l  ddlm jjdkrqdd jf fdd}|dd }|dd}|d	d
}t|tr6|nd }|d ur>d n|} j	d||d|}	|	j
|||||d |	 sg|	j}
tt|
j|
j|
jS |	j}dd |D S t|D ]6}d _d g}jjtjkrtdtjj|dd jd |d d tdd d u r }|_qud S )Nr   )release_memoryr_   c                    s   d }|rt |D ]}|trt j||}q	d _jjdkrMjj	t
jkr,td|   j| j| j}|g}tjj|dd j|| d nj|| d tdd d u rf }|_jj\__j  jS )N   Conly support DDP optuna HPO for ParallelMode.DISTRIBUTED currently.r   srcresume_from_checkpointr_   	objective)r%   listdir
startswithr   pathjoinrp   args
world_sizeparallel_moder   DISTRIBUTEDrc   hp_spacer_   
FixedTrialra   numbertorchdistributedbroadcast_object_listtraingetattrevaluatecompute_objectivemodel_wrappedmodelacceleratorclear)r_   checkpoint_dir
checkpointsubdirfixed_trialtrial_main_rank_listmetricsr@   ri   trainerr-   r.   
_objective   s,   


z(run_hp_search_optuna.<locals>._objectivetimeoutn_jobsrj   gc_after_trialF)rg   
directions)rf   r   r   r   c                 S   s"   g | ]}t t|j|j|jqS r-   )r   strr{   valuesra   ).0bestr-   r-   r.   
<listcomp>  s   " z(run_hp_search_optuna.<locals>.<listcomp>rk   rl   rn   rp   rR   r-   ) r@   accelerate.utils.memoryri   ru   process_indexTrialpopr^   listcreate_studyoptimize_is_multi_objective
best_trialr   r   r{   valuera   best_trialsrangerp   rw   r   rx   rc   r|   r}   r~   r   r   r   r   )r   rf   rg   kwargsr   r   r   r   r   studyr   r   ir   r   r-   r   r.   run_hp_search_optuna   s8   r   c                    s  dd l  dd l dtf fdd}| jjs&ddlm} td |dd	| _| 	t
}d | _d
|vrYddi|d
< | jjdkrDd|d
 d< d| jjdkrMdnd }td| d |d
 dd}|| j_d|vrwddlm}	 |	dgd|d< d|v rddlm}
m}m}m} t|d |
|||fr| jjr| jjtjkrtdjt|d j d j!j"|| dt#$fdd}t%drƈj&|_& j!j'|f| (d |d|}|j)d|d d  | jj*d!}t+|j,|j-d |j.|}|d ur| /| |S )"Nr   r_   c                    sD  zddl m} ||r|t W n	 ty   Y nw d |_ j }|rSd|_|	 }t
t|t d }|j|| d W d    n1 sMw   Y  n|j| d t|dd d u r| }|||_||jdd t }|j|d	  jj|} jj||d
 W d    d S 1 sw   Y  d S d S )Nr   )NotebookProgressCallbackrp   *rn   )r_   T)rp   done)r   )r   )transformers.utils.notebookr   pop_callbackadd_callbackr   ModuleNotFoundErrorrp   r   get_checkpointas_directorynextr   globr   as_posixr   r   r   updatetempfileTemporaryDirectory_tune_save_checkpoint
Checkpointfrom_directoryreport)r_   local_trainerr   r   r   checkpoint_pathr   temp_checkpoint_dir)rB   r-   r.   r   *  s8   




"z%run_hp_search_ray.<locals>._objectiver   )TrainerMemoryTrackerzMemory tracking for your Trainer is currently enabled. Automatically disabling the memory tracker since the memory tracker is not serializable.T)skip_memory_metricsresources_per_trialcpurj   gpuz1 CPUz
 and 1 GPUr#   zgNo `resources_per_trial` arg was passed into `hyperparameter_search`. Setting it to a default value of z for each trial.progress_reporter)CLIReporterrp   )metric_columns	scheduler)ASHASchedulerHyperBandForBOHBMedianStoppingRulePopulationBasedTraininga  You are using {cls} as a scheduler but you haven't enabled evaluation during training. This means your trials will not report intermediate results to Ray Tune, and can thus not be stopped early or used to exploit other trials parameters. If this is what you want, do not use {cls}. If you would like to use {cls}, make sure you pass `do_eval=True` and `eval_strategy='steps'` in the Trainer `args`.)cls)r   c                     sb   t  r*ddl}tj|j d}tj	d|}tj
|}|tj|j< |j|  | i |S )a"  
        Wrapper around `tune.with_parameters` to ensure datasets_modules are loaded on each Actor.

        Without this, an ImportError will be thrown. See https://github.com/huggingface/transformers/issues/11565.

        Assumes that `_objective`, defined above, is a function.
        r   Nz__init__.pydatasets_modules)r   datasets.loadr%   rs   rt   loadinit_dynamic_modulesr*   r+   spec_from_file_locationmodule_from_specsysmodulesnameloaderexec_module)ru   r   datasetsdynamic_modules_pathspecr   )	trainabler-   r.    dynamic_modules_import_trainable  s   	z;run_hp_search_ray.<locals>.dynamic_modules_import_trainable
__mixins__)confignum_samples   )metricmodescope)0rB   	ray.trainrb   _memory_trackerr   trainer_utilsr   r(   r)   r   TensorBoardCallbackr   ru   n_gpuinfoget_n_gpuray.tuner   ray.tune.schedulersr   r   r   r   r^   do_evaleval_strategyr   NOrc   formattype__name__tunewith_parameters	functoolswrapshasattrr   runry   get_best_trial	ray_scoper   trial_idlast_resultr   r   )r   rf   rg   r   r   r   
_tb_writerresource_msggpus_per_trialr   r   r   r   r   r   analysisr   best_runr-   )rB   r   r.   run_hp_search_ray&  sr   &
	

r  c              	   K   s  dd l }| jjdkrtjddkr|d |jdd| d d|dd	gd
|d}t	
d|j  | D ]b}|V d | _| jjd
krj| jjtjkrQtd| |j tjjt| jdd | jd d n| jd |jd t| dd d u r|  }| || _|d| j W d    n1 sw   Y  q8t|  d }t!|j|j"d j#|j$}	|	S ddl m%}
 |
 }|&dd }|d ur|'| |( j)d| d d|dd	gd
|dd}t	
d|j  |j*j+|j,k rs|(|j- ) }d | _| jjd
kr'| jjtjkrtd| | tjjt| jdd | jd d n| jd |d t| dd d u rA|  }| || _d| jdg}|(|j. j)|j|d}t	
d|j d|j d |(|j/ }|j*j+|j,k st|(|j0 / 1 d }t!|j|j#|j$}	|	S t2|D ]Z}d | _tt| j}| jjtjkrtdtjj|dd t3t4|}t5|6 D ]\}}|dkrt7| j|| q| jd d t| dd d u r|  }| || _qd S )Nr   rG   z8.0.0huggingfacezhuggingface-tuneofflinerp   r   )r   rp   strategyrj   )r   r   
parametersr   parallel_bandwidthbudgetz6created experiment: https://app.sigopt.com/experiment/zConly support DDP Sigopt HPO for ParallelMode.DISTRIBUTED currently.rl   )ro   rn   )
Connectionproxies)r   r  r   r  observation_budgetprojectr   r   )
suggestionr   z"[suggestion_id, observation_id]: [, ]
local_rank)8rG   ru   r   r*   metadataversionset_projectcreate_experimentry   r(   r   idlooprp   rv   rw   r   rx   rc   _hp_search_setupr   r|   r}   r~   pickledumpsr   r   r   r   
log_metricr   get_best_runsr   r   r   assignmentsr
  r   set_proxiesexperimentscreateprogressobservation_countr  suggestionsobservationsfetchbest_assignmentsiterate_pagesr   loadsbytesr   itemssetattr)r   rf   rg   r   rG   
experimentr   r   r   r  r
  connr  r  r   obsr   args_main_rankru   keyr   r-   r-   r.   run_hp_search_sigopt  s   
	*

 
r2  c                    s^  ddl m} | stddd ld}jjD ]}t|tr"d} nq|s+t  dgj	_
d d d d |d	d }|d
d }|dd }	|dd }
|ddd }|d d< |d d< |	rk|	|d<  fdd}|sj|||
d}ndd l|
rj|
 j| td|  j|||d t d  d  d |S )Nr   )r/   z8This function needs wandb installed: `pip install wandb`r   FTr$   )run_idrp   hyperparameterssweep_idr  r   entityr   z	eval/lossgoalc                     s  j rj n } | jj_| ji d j}d _jd t	|d d t
dd d u rP }|_t|}|vrPtd d|   d} d d urod	krdj d k }nd
kroj d k}|sw d d u r| j d< j d< t| d< jS )N)r  r   _itemsrn   rp   zProvided metric zU not found. This might result in unexpected sweeps charts. The available metrics are Fr3  minimizemaximizer4  )r   initr   state
trial_namer   r   rp   r   varsr   r   r   rewrite_logsr(   r)   keysr  rb   )r   r   r   format_metrics
best_scorer   rg   r   r   r$   r-   r.   r   +  s6   


z'run_hp_search_wandb.<locals>._objective)r  r6  zwandb sweep id - )functioncountr3  rp   r4  )integrationsr/   ImportErrorr$   callback_handler	callbacksr^   WandbCallbackr   ru   	report_tor   ry   sweep	wandb.envenv
set_entityr  r(   r   agentr   )r   rf   rg   r   r/   reporting_to_wandbcallbackr5  r  r   r6  sweep_configr   r-   rC  r.   run_hp_search_wandb  sD   


!rT  c                  C   s   g } t  rt s| d t r| d t r| d t r%| d t r-| d t r5| d t r=| d t rE| d t	 rM| d	 t
 rU| d
 t r]| d | S )Nazure_mlr   rP   rZ   rN   r   r=   r$   rU   r1   r\   )rJ   rO   appendr<   rQ   r[   rT   r?   r/   rV   r3   r]   )rF  r-   r-   r.   $get_available_reporting_integrations[  s0   










rW  c                 C   s~   i }d}t |}d}t |}|  D ]*\}}||r&||d||d   < q||r6||d||d   < q||d| < q|S )Neval_test_eval/ztest/ztrain/)lenr+  rr   )dnew_deval_prefixeval_prefix_lentest_prefixtest_prefix_lenkvr-   r-   r.   r?  v  s   

r?  c                   @   s>   e Zd ZdZdddZdddZdd Zdd	d
Zdd ZdS )r   z
    A [`TrainerCallback`] that sends the logs to [TensorBoard](https://www.tensorflow.org/tensorboard).

    Args:
        tb_writer (`SummaryWriter`, *optional*):
            The writer to use. Will instantiate one if not set.
    Nc                 C   s   t  }|s	td|r8zddlm} || _W n$ ty7   zddlm} || _W n ty4   d | _Y nw Y nw d | _|| _d S )NzuTensorBoardCallback requires tensorboard to be installed. Either update your PyTorch version or install tensorboardX.r   )SummaryWriter)r?   rc   torch.utils.tensorboardrd  _SummaryWriterrG  r>   	tb_writer)selfrg  has_tensorboardrd  r-   r-   r.   __init__  s(   



zTensorBoardCallback.__init__c                 C   s*   |p|j }| jd ur| j|d| _d S d S )N)log_dir)logging_dirrf  rg  )rh  ru   rk  r-   r-   r.   _init_summary_writer  s   

z(TensorBoardCallback._init_summary_writerc           	      K   s   |j sd S d }|jr|j}|d urtj|j|}| jd u r$| || | jd urR| j	d|
  d|v rT|d }t|drV|jd urX|j
 }| j	d| d S d S d S d S d S )Nru   r   r   model_config)is_world_process_zerois_hyper_param_searchr=  r%   rs   rt   rl  rg  rm  add_textto_json_stringr   r   )	rh  ru   r<  controlr   rk  r=  r   model_config_jsonr-   r-   r.   on_train_begin  s&   


z"TensorBoardCallback.on_train_beginc              
   K   s   |j sd S | jd u r| | | jd urYt|}| D ]5\}}t|ttfr1| j|||j	 qt|t
r@| j|||j	 qtd| dt| d| d q| j  d S d S )N)Trainer is attempting to log a value of "
" of type 
 for key "zn" as a scalar. This invocation of Tensorboard's writer.add_scalar() is incorrect so we dropped this attribute.)ro  rg  rm  r?  r+  r^   intfloat
add_scalarglobal_stepr   rq  r(   r)   r   flushrh  ru   r<  rs  logsr   rb  rc  r-   r-   r.   on_log  s,   



zTensorBoardCallback.on_logc                 K   s   | j r| j   d | _ d S d S rR   )rg  closerh  ru   r<  rs  r   r-   r-   r.   on_train_end     

z TensorBoardCallback.on_train_endrR   )	r   
__module____qualname____doc__rj  rm  ru  r  r  r-   r-   r-   r.   r     s    


r   r   
output_dirc                    s   t | ddi t| trt|  d n4t r*t| tr* fdd}| j|d n/t rQt| tj	j
tfrat| drit|  d W d    d S W d    d S W d    d S W d    d S W d    d S W d    d S 1 stw   Y  d S )Nz/model_architecture.txtzw+filec                    s   t |  d d S )Nr  )print)sfr-   r.   print_to_file  r4   z6save_model_architecture_to_file.<locals>.print_to_file)print_fn
base_model)openr^   r   r  r   r   summaryr   r|   nnModuler   r   )r   r  r  r-   r  r.   save_model_architecture_to_file  s.   
			"r  c                   @   sD   e Zd ZdZdZdZdZedefddZ	e
dedd fd	d
ZdS )WandbLogModelz)Enum of possible log model values in W&B.r   endfalserh   c                 C   s   | t jt jfv S )zYCheck if the value corresponds to a state where the `WANDB_LOG_MODEL` setting is enabled.)r  
CHECKPOINTENDrh  r-   r-   r.   
is_enabled  s   zWandbLogModel.is_enabledr   c                 C   sV   t |tstdt| | tv rtdtd dt	d| d tjS )	Nz>Expecting to have a string `WANDB_LOG_MODEL` setting, but got zSetting `WANDB_LOG_MODEL` as WANDB_LOG_MODELzn is deprecated and will be removed in version 5 of transformers. Use one of `'end'` or `'checkpoint'` instead.zSetting `WANDB_LOG_MODEL` from z to `end` insteadz6Received unrecognized `WANDB_LOG_MODEL` setting value=z ; so disabling `WANDB_LOG_MODEL`)r^   r   
ValueErrorr   r'   r    DeprecationWarningr%   r&   r(   r   r  r  r)   rL   )r   r   r-   r-   r.   	_missing_  s   

zWandbLogModel._missing_N)r   r  r  r  r  r  rL   propertyboolr  classmethodr   r  r-   r-   r-   r.   r    s    r  c                   @   N   e Zd ZdZdd Zdd ZdddZdd	d
ZdddZdd Z	dd Z
dS )rJ  z{
    A [`TrainerCallback`] that logs metrics, media, model checkpoints to [Weight and Biases](https://www.wandb.com/).
    c                 C   s@   t  }|s	td|rdd l}|| _d| _ttdd| _d S )NzFWandbCallback requires wandb to be installed. Run `pip install wandb`.r   Fr  r  )	r/   rc   r$   _wandb_initializedr  r%   r&   
_log_model)rh  	has_wandbr$   r-   r-   r.   rj    s   zWandbCallback.__init__c              
   K   sN  | j du rdS d| _ddlm} |jrtd i | }t|dr=|j	dur=t
|j	tr2|j	n|j	 }i ||}t|drR|jdurR|j}i d|i|}|j}	i }
|	dure|	|
d< |j|
d	< n|jdur}|j|
d< |j|jkr}| j jd
dd | j jdu r| j jd*dtddi|
 | j j	j|dd t| j ddr| j d | j jdddd tdd}t s|dv r| j j||td|jd | j jjdd z
| | j j	d< W n ty   td Y n |y   td Y nw | j j!rt"# }|jdu s|j|jkrd| j jj$ nd| j jj% }| j j&|d t|dr0|j	 nd| j j	'ddd!d"}t(|| t)|*dD ](}|+ rp|j,|j%d#d$}|-|.  W d   n	1 skw   Y  qI| j jj/|d%gd& d'| j j0  d(}t1 j2d)| 7  _2W d   dS 1 sw   Y  dS dS dS )+u  
        Setup the optional Weights & Biases (*wandb*) integration.

        One can subclass and override this method to customize the setup if needed. Find more information
        [here](https://docs.wandb.ai/guides/integrations/huggingface). You can also override the following environment
        variables:

        Environment:
        - **WANDB_LOG_MODEL** (`str`, *optional*, defaults to `"false"`):
            Whether to log model and checkpoints during training. Can be `"end"`, `"checkpoint"` or `"false"`. If set
            to `"end"`, the model will be uploaded at the end of training. If set to `"checkpoint"`, the checkpoint
            will be uploaded every `args.save_steps` . If set to `"false"`, the model will not be uploaded. Use along
            with [`~transformers.TrainingArguments.load_best_model_at_end`] to upload best model.

            <Deprecated version="5.0">

            Setting `WANDB_LOG_MODEL` as `bool` will be deprecated in version 5 of 🤗 Transformers.

            </Deprecated>
        - **WANDB_WATCH** (`str`, *optional* defaults to `"false"`):
            Can be `"gradients"`, `"all"`, `"parameters"`, or `"false"`. Set to `"all"` to log gradients and
            parameters.
        - **WANDB_PROJECT** (`str`, *optional*, defaults to `"huggingface"`):
            Set this to a custom string to store results in a different project.
        - **WANDB_DISABLED** (`bool`, *optional*, defaults to `False`):
            Whether to disable wandb entirely. Set `WANDB_DISABLED=true` to disable.
        NTr   )ConfigErrorz`Automatic Weights & Biases logging enabled, to disable set os.environ["WANDB_DISABLED"] = "true"r   peft_configr   groupzThe `run_name` is currently set to the same value as `TrainingArguments.output_dir`. If this was not intended, please specify a different run name by setting the `TrainingArguments.run_name` parameter.F)repeatr  WANDB_PROJECTr  )allow_val_changedefine_metrictrain/global_stepr   )step_metric	step_syncWANDB_WATCHr  )allr  	gradientsd   )loglog_freqtransformers_trainer)codemodel/num_parameterszZCould not log the number of model parameters in Weights & Biases due to an AttributeError.zbA ConfigError was raised whilst setting the number of model parameters in Weights & Biases config.model-r   )rn  num_parametersinitial_modelr   r   r  wbr   r  aliasesz[<img src="https://raw.githubusercontent.com/wandb/assets/main/wandb-github-badge-28.svg" alt="Visualize in Weights & Biases" width="200" height="32"/>]()
r-   )3r  r  wandb.sdk.lib.config_utilr  ro  r(   r   to_dictr   r   r^   rb   r  r=  run_namer  termwarnr   r;  r%   r&   r   r   r  r!   watchmaxlogging_steps_labelr  AttributeErrorr)   r  r  r   r   r  r   Artifactr   r  r   r   is_filenew_filewrite
read_byteslog_artifactget_urlr   AUTOGENERATED_TRAINER_COMMENT)rh  ru   r<  r   r   WandbConfigErrorcombined_dictrn  r  r=  	init_args_watch_modeltemp_dir
model_namemodel_artifactr  fabadge_markdownr-   r-   r.   setup  s   










$:zWandbCallback.setupNc                 K   sR   | j d u rd S |j}|r| j   d| _d |_| js'| j|||fi | d S d S NF)r  rp  finishr  r  r  )rh  ru   r<  rs  r   r   	hp_searchr-   r-   r.   ru    s   

zWandbCallback.on_train_beginc              
   K   s  | j d u rd S | jjr| jr|jrddlm} ||||dgd}t }	|	|	 |j
s:dd t| j j D nd|j |jd|jd	| j jd	i}
d
|
d< td |jd u sa|j|jkrid| j jj nd| j jj }t||	 | j j|d|
d}t|	dD ]%}| r|j|jdd}| |!  W d    n1 sw   Y  q| j jj"|dgd W d    d S 1 sw   Y  d S d S d S d S )Nr   Trainerfakeru   r   processing_classeval_datasetc                 S   ,   i | ]\}}t |tjr|d s||qS _r^   numbersNumberrr   r   rb  rc  r-   r-   r.   
<dictcomp>      
z.WandbCallback.on_train_end.<locals>.<dictcomp>rZ  ztrain/total_flossr  Tfinal_modelzLogging model artifacts. ...r  r   r  r   r  r  r  )#r  r  r  r  ro  r   r  r   r   
save_modelload_best_model_at_endrb   r  r+  metric_for_best_modelbest_metric
total_flosr   r   r(   r   r  r  r   r  r   r  r  r   r   r  r  r  r  r  )rh  ru   r<  rs  r   r  r   r  fake_trainerr  r  r  artifactr  r  r-   r-   r.   r    sB   




"zWandbCallback.on_train_endc           
         s   g d | j d u rd S | js| ||| |jrJ| D ]\}}| v r+|| j jj|< q fdd| D }	t|	}	| j i |	d|j	i d S d S )Ntrain_runtimetrain_samples_per_secondtrain_steps_per_second
train_lossr  c                       i | ]\}}| vr||qS r-   r-   r  single_value_scalarsr-   r.   r        z(WandbCallback.on_log.<locals>.<dictcomp>r  )
r  r  r  ro  r+  r   r  r?  r  r|  
rh  ru   r<  rs  r   r  r   rb  rc  non_scalar_logsr-   r  r.   r    s   
zWandbCallback.on_logc           
      K   s   | j tjkry| jr{|jr}dd t| jj D }| jj	
d|d< d|j }tj|j|}td| d |jd u sD|j|jkrLd| jjj nd| jjj }| jj|d|d	}	|	| | jj|	d
t|jd d|j gd d S d S d S d S )Nc                 S   r  r  r  r  r-   r-   r.   r    r  z)WandbCallback.on_save.<locals>.<dictcomp>r  checkpoint- Logging checkpoint artifacts in z. ...r  r   r  epoch_r   checkpoint_global_step_r  )r  r  r  r  ro  rb   r  r  r+  r   r   r|  r%   rs   rt   r  r(   r   r  r   r  r   r  add_dirr  roundepoch)
rh  ru   r<  rs  r   checkpoint_metadatackpt_dirartifact_pathcheckpoint_namer  r-   r-   r.   on_save  s$   

zWandbCallback.on_savec                 K   sJ   | j d u rd S | js| j||fi | |jr#t|}| j | d S d S rR   )r  r  r  ro  r?  r  rh  ru   r<  rs  r   r   r-   r-   r.   
on_predict  s   
zWandbCallback.on_predictrR   NNr   r  r  r  rj  r  ru  r  r  r  r  r-   r-   r-   r.   rJ    s    
~

'rJ  c                   @   sD   e Zd ZdZdd Zdd ZdddZdd	d
Zdd Zdd Z	dS )CometCallbackz_
    A [`TrainerCallback`] that sends the logs to [Comet ML](https://www.comet.com/site/).
    c                 C   s<   t du stdu rtdt dt dd| _d| _d | _d S )NFz!CometCallback requires comet-ml>=z- to be installed. Run `pip install comet-ml>=z`.)r7   r8   rc   r:   r  _log_assets_experimentr  r-   r-   r.   rj    s   
zCometCallback.__init__c                 C   s  d| _ tdd }|dv rd| _|jrtd}d}d}|durE| }|dkr-d}n|dkr4d	}n|d
v r;|}n
|rEtd| dS |j	rT|durRtd| d}ddl
}|jdurk|j|jkrk|j|jd}	n| }	|j|||	d| _| jj|dd d| i}
t|dr|jdur|j }||
d< t|dr|jdur|j}||
d< | jj|
dddd |j	rt|dd}t|dd}| jj||d dS dS dS )a  
        Setup the optional Comet integration.

        Environment:
        - **COMET_MODE** (`str`, *optional*, default to `get_or_create`):
            Control whether to create and log to a new Comet experiment or append to an existing experiment.
            It accepts the following values:
                * `get_or_create`: Decides automatically depending if
                  `COMET_EXPERIMENT_KEY` is set and whether an Experiment
                  with that key already exists or not.
                * `create`: Always create a new Comet Experiment.
                * `get`: Always try to append to an Existing Comet Experiment.
                  Requires `COMET_EXPERIMENT_KEY` to be set.
                * `ONLINE`: **deprecated**, used to create an online
                  Experiment. Use `COMET_START_ONLINE=1` instead.
                * `OFFLINE`: **deprecated**, used to created an offline
                  Experiment. Use `COMET_START_ONLINE=0` instead.
                * `DISABLED`: **deprecated**, used to disable Comet logging.
                  Use the `--report_to` flag to control the integrations used
                  for logging result instead.
        - **COMET_PROJECT_NAME** (`str`, *optional*):
            Comet project name for experiments.
        - **COMET_LOG_ASSETS** (`str`, *optional*, defaults to `TRUE`):
            Whether or not to log training assets (tf event logs, checkpoints, etc), to Comet. Can be `TRUE`, or
            `FALSE`.

        For a number of configurable items in the environment, see
        [here](https://www.comet.com/docs/v2/guides/experiment-management/configure-sdk/#explore-comet-configuration-options).
        TCOMET_LOG_ASSETSrL   >   1rM   r5   Nonliner  F)r   get_or_creater!  z:Invalid COMET_MODE env value %r, Comet logging is disabledzjHyperparameter Search is enabled, forcing the creation of new experimetns, COMET_MODE value %r  is ignoredr!  r   )r   )r  r   experiment_configtransformers)	frameworkru   r   r  manual)r   sourceflatten_nestedr=  trial_params)optimization_idr  )r  r%   r&   r'   r  ro  lowerr(   r)   rp  r   r  r  ExperimentConfigstartr  !__internal_api__set_model_graph__r  r   r   r   __internal_api__log_parameters__r   log_optimization)rh  ru   r<  r   
log_assetscomet_old_moder   r  r   r  ra   rn  r  r%  optimization_paramsr-   r-   r.   r    s`   

4zCometCallback.setupNc                 K      | j s| ||| d S d S rR   r  r  rh  ru   r<  rs  r   r   r-   r-   r.   ru  k     zCometCallback.on_train_beginc                 K   sP   | j s
| ||| |jr$| jd ur&t|}| jj||j|jdd d S d S d S )Nr  stepr  r   r  r  ro  r  r?  __internal_api__log_metrics__r|  r  )rh  ru   r<  rs  r   r  r   rewritten_logsr-   r-   r.   r  o  s   

zCometCallback.on_logc                 K   sh   | j r.|jr0| jd ur!| jdu r!td | jj|jdd|jd |j	r2| j
  d| _ d S d S d S d S )NTz(Logging checkpoints. This may take time.)	recursivelog_file_namer4  F)r  ro  r  r  r(   r   log_asset_folderr  r|  rp  cleanr  r-   r-   r.   r  y  s   




	zCometCallback.on_train_endc                 K   sR   | j s| j||d d |jr%| jd ur't|}| jj||j|jdd d S d S d S )N)r   r  r3  r5  )rh  ru   r<  rs  r   r   rewritten_metricsr-   r-   r.   r    s   
zCometCallback.on_predictrR   r  )
r   r  r  r  rj  r  ru  r  r  r  r-   r-   r-   r.   r    s    	
\

r  c                   @   s,   e Zd ZdZd	ddZdd Zd	ddZdS )
AzureMLCallbackzh
    A [`TrainerCallback`] that sends the logs to [AzureML](https://pypi.org/project/azureml-sdk/).
    Nc                 C   s   t  std|| _d S )NzPAzureMLCallback requires azureml to be installed. Run `pip install azureml-sdk`.)rJ   rc   azureml_run)rh  r>  r-   r-   r.   rj    s   
zAzureMLCallback.__init__c                 K   s2   ddl m} | jd u r|jr| | _d S d S d S )Nr   Run)azureml.core.runr@  r>  ro  get_context)rh  ru   r<  rs  r   r@  r-   r-   r.   on_init_end  s   zAzureMLCallback.on_init_endc                 K   sJ   | j r|jr!| D ]\}}t|ttfr| j j|||d q
d S d S d S )N)description)r>  ro  r+  r^   ry  rz  r  r~  r-   r-   r.   r    s   zAzureMLCallback.on_logrR   )r   r  r  r  rj  rC  r  r-   r-   r-   r.   r=    s
    
r=  c                   @   sL   e Zd ZdZdd Zdd ZdddZdd	d
Zdd Zdd Z	dd Z
dS )MLflowCallbackz
    A [`TrainerCallback`] that sends the logs to [MLflow](https://www.mlflow.org/). Can be disabled by setting
    environment variable `DISABLE_MLFLOW_INTEGRATION = TRUE`.
    c                 C   sJ   t  stddd l}|jjj| _|jjj| _d| _	d| _
d| _|| _d S )NzIMLflowCallback requires mlflow to be installed. Run `pip install mlflow`.r   F)rO   rc   rN   utils
validationMAX_PARAM_VAL_LENGTH_MAX_PARAM_VAL_LENGTHMAX_PARAMS_TAGS_PER_BATCH_MAX_PARAMS_TAGS_PER_BATCHr  _auto_end_run_log_artifacts_ml_flow)rh  rN   r-   r-   r.   rj    s   
zMLflowCallback.__init__c              
   C   s  t dd tv | _t dd tv | _t dd| _t dd| _t dd tv | _t dd| _	t d	d| _
tj| jjtjd
k| _td| j d|j d| j d| j  |jr}| j s| jr~| j| j td| j  ntd ntd| j   | j du s| js| j	r| jr| j| j | jj|j| jd td| j jj  d| _| }t|dr|j dur|j  }i ||}| jrt!|n|}t"|# D ]\}}t$t%|| j&krt'd| d| d ||= qt"|# }| j
r6| j
( r6t)| j
}	|	t$|k r6tdt$| d|	 d |d|	 }t*dt$|| j+D ])}
| jrX| jj,t-||
|
| j+  dd q?| j,t-||
|
| j+   q?t dd}|r}t./|}| j0| d| _1dS )a  
        Setup the optional MLflow integration.

        Environment:
        - **HF_MLFLOW_LOG_ARTIFACTS** (`str`, *optional*):
            Whether to use MLflow `.log_artifact()` facility to log artifacts. This only makes sense if logging to a
            remote server, e.g. s3 or GCS. If set to `True` or *1*, will copy each saved checkpoint on each save in
            [`TrainingArguments`]'s `output_dir` to the local or remote artifact storage. Using it without a remote
            storage will just copy the files to your artifact location.
        - **MLFLOW_TRACKING_URI** (`str`, *optional*):
            Whether to store runs at a specific path or remote server. Unset by default, which skips setting the
            tracking URI entirely.
        - **MLFLOW_EXPERIMENT_NAME** (`str`, *optional*, defaults to `None`):
            Whether to use an MLflow experiment_name under which to launch the run. Default to `None` which will point
            to the `Default` experiment in MLflow. Otherwise, it is a case sensitive name of the experiment to be
            activated. If an experiment with this name does not exist, a new experiment with this name is created.
        - **MLFLOW_TAGS** (`str`, *optional*):
            A string dump of a dictionary of key/value pair to be added to the MLflow run as tags. Example:
            `os.environ['MLFLOW_TAGS']='{"release.candidate": "RC1", "release.version": "2.2.0"}'`.
        - **MLFLOW_NESTED_RUN** (`str`, *optional*):
            Whether to use MLflow nested runs. If set to `True` or *1*, will create a nested run inside the current
            run.
        - **MLFLOW_RUN_ID** (`str`, *optional*):
            Allow to reattach to an existing run which can be useful when resuming training from a checkpoint. When
            `MLFLOW_RUN_ID` environment variable is set, `start_run` attempts to resume a run with the specified run ID
            and other parameters are ignored.
        - **MLFLOW_FLATTEN_PARAMS** (`str`, *optional*, defaults to `False`):
            Whether to flatten the parameters dictionary before logging.
        - **MLFLOW_MAX_LOG_PARAMS** (`int`, *optional*):
            Set the maximum number of parameters to log in the run.
        HF_MLFLOW_LOG_ARTIFACTSrL   MLFLOW_NESTED_RUNMLFLOW_TRACKING_URINMLFLOW_EXPERIMENT_NAMEMLFLOW_FLATTEN_PARAMSMLFLOW_RUN_IDMLFLOW_MAX_LOG_PARAMSz2.8.0zMLflow experiment_name=z, run_name=z	, nested=z, tracking_uri=zMLflow tracking URI is set to zdEnvironment variable `MLFLOW_TRACKING_URI` is not provided and therefore will not be explicitly set.)r  nestedzMLflow run started with run_id=Tr   rv  z" for key "z" as a parameter. MLflow's log_param() only accepts values no longer than 250 characters so we dropped this attribute. You can use `MLFLOW_FLATTEN_PARAMS` environment variable to flatten the parameters and avoid this message.z.Reducing the number of parameters to log from z to .r   F)synchronousMLFLOW_TAGS)2r%   r&   r'   r    rM  _nested_run_tracking_uri_experiment_name_flatten_params_run_id_max_log_params	packagingr  parserN  r   
_async_logr(   debugr  ro  is_tracking_uri_setset_tracking_uriget_tracking_uri
active_runset_experiment	start_runr   r3  rL  r  r   r   r   r   r+  r[  r   rI  r)   isdigitry  r   rK  
log_paramsrb   jsonr)  set_tagsr  )rh  ru   r<  r   r  rn  r   r   combined_dict_itemsmax_log_paramsr   mlflow_tagsr-   r-   r.   r    sv    



"

zMLflowCallback.setupNc                 K   r/  rR   r0  r1  r-   r-   r.   ru  &  r2  zMLflowCallback.on_train_beginc           
   
   K   s   | j s
| ||| |jrbi }| D ]4\}}	t|	ttfr#|	||< qt|	tjr6|		 dkr6|	
 ||< qtd|	 dt|	 d| d q| jrW| jj||jdd d S | jj||jd d S d S )	Nrj   rv  rw  rx  zc" as a metric. MLflow's log_metric() only accepts float and int types so we dropped this attribute.F)r   r4  rX  )r   r4  )r  r  ro  r+  r^   ry  rz  r|   Tensornumelitemr(   r)   r   rb  rN  log_metricsr|  )
rh  ru   r<  rs  r  r   r   r   rb  rc  r-   r-   r.   r  *  s    
zMLflowCallback.on_logc                 K   s:   | j r|jr| jr| j r| j  d S d S d S d S d S rR   )r  ro  rL  rN  rg  end_runr  r-   r-   r.   r  ?  s
   zMLflowCallback.on_train_endc                 K   sp   | j r2|jr4| jr6d|j }tj|j|}t	d| d | j
jj|d|i| j
j d d S d S d S d S )Nr  r  z. This may take time.
model_path)	artifactspython_model)r  ro  rM  r|  r%   rs   rt   r  r(   r   rN  pyfunc	log_modelPythonModelrh  ru   r<  rs  r   r  r  r-   r-   r.   r  D  s   

zMLflowCallback.on_savec                 C   s@   | j rtt| jdd r| j d ur| j  d S d S d S d S )Nrg  )rL  callabler   rN  rg  ru  r  r-   r-   r.   __del__O  s   zMLflowCallback.__del__rR   )r   r  r  r  rj  r  ru  r  r  r  r~  r-   r-   r-   r.   rE    s    
k
rE  c                       s4   e Zd ZdZ fddZ fddZdd Z  ZS )DagsHubCallbackzh
    A [`TrainerCallback`] that logs to [DagsHub](https://dagshub.com/). Extends [`MLflowCallback`]
    c                    s.   t    t stdddlm} || _d S )NzLDagsHubCallback requires dagshub to be installed. Run `pip install dagshub`.r   )Repo)superrj  rQ   rG  dagshub.uploadr  )rh  r  rd   r-   r.   rj  _  s
   

zDagsHubCallback.__init__c                    s   t dd tv | _t dpd| _t d| _| j| jt j	d | jt j	d dd	 t d
p6dd| _
td| _| jdu rHtdt j|i | dS )z
        Setup the DagsHub's Logging integration.

        Environment:
        - **HF_DAGSHUB_LOG_ARTIFACTS** (`str`, *optional*):
                Whether to save the data and model artifacts for the experiment. Default to `False`.
        HF_DAGSHUB_LOG_ARTIFACTSrL   HF_DAGSHUB_MODEL_NAMEmainrQ  rW  r   BRANCH)ownerr   branchrw  NzpDagsHubCallback requires the `MLFLOW_TRACKING_URI` environment variable to be set. Did you run `dagshub.init()`?)r%   r&   r'   r    log_artifactsr   remoter  splitseprepor   rs   rc   r  r  )rh  ru   r   r  r-   r.   r  h  s   	

zDagsHubCallback.setupc                 K   sP   | j r&t| dd rt| jjtj|j	d | j
t| j|j	 d S d S )Ntrain_dataloaderz
dataset.pt)r  r   r|   saver  datasetr%   rs   rt   r  r  	directoryr   r  r  r-   r-   r.   r    s
   zDagsHubCallback.on_train_end)r   r  r  r  rj  r  r  __classcell__r-   r-   r  r.   r  Z  s
    	r  c                       s   e Zd Z fddZ  ZS )NeptuneMissingConfigurationc                    s   t  d d S )NaA  
        ------ Unsupported ---- We were not able to create new runs. You provided a custom Neptune run to
        `NeptuneCallback` with the `run` argument. For the integration to work fully, provide your `api_token` and
        `project` by saving them as environment variables or passing them to the callback.
        )r  rj  r  r  r-   r.   rj    s   z$NeptuneMissingConfiguration.__init__)r   r  r  rj  r  r-   r-   r  r.   r    s    r  c                   @   s<  e Zd ZdZdZdZdZdZdZdhZ	dddd	dd
ddde
e de
e de
e dedede
e fddZdd Zdd Zdd Zdd Zdd Zedd Zed d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*ed+efd,d-Zd.d/ Zd?d0d1Zd2d3 Zd4d5 Zd6d7 Zd?d8d9Z e!d:d; Z"d?d<e
e#ee$f  fd=d>Z%dS )@NeptuneCallbacka  TrainerCallback that sends the logs to [Neptune](https://app.neptune.ai).

    Args:
        api_token (`str`, *optional*): Neptune API token obtained upon registration.
            You can leave this argument out if you have saved your token to the `NEPTUNE_API_TOKEN` environment
            variable (strongly recommended). See full setup instructions in the
            [docs](https://docs.neptune.ai/setup/installation).
        project (`str`, *optional*): Name of an existing Neptune project, in the form "workspace-name/project-name".
            You can find and copy the name in Neptune from the project settings -> Properties. If None (default), the
            value of the `NEPTUNE_PROJECT` environment variable is used.
        name (`str`, *optional*): Custom name for the run.
        base_namespace (`str`, *optional*, defaults to "finetuning"): In the Neptune run, the root namespace
            that will contain all of the metadata logged by the callback.
        log_parameters (`bool`, *optional*, defaults to `True`):
            If True, logs all Trainer arguments and model parameters provided by the Trainer.
        log_checkpoints (`str`, *optional*): If "same", uploads checkpoints whenever they are saved by the Trainer.
            If "last", uploads only the most recently saved checkpoint. If "best", uploads the best checkpoint (among
            the ones saved by the Trainer). If `None`, does not upload checkpoints.
        run (`Run`, *optional*): Pass a Neptune run object if you want to continue logging to an existing run.
            Read more about resuming runs in the [docs](https://docs.neptune.ai/logging/to_existing_object).
        **neptune_run_kwargs (*optional*):
            Additional keyword arguments to be passed directly to the
            [`neptune.init_run()`](https://docs.neptune.ai/api/neptune#init_run) function when a new run is created.

    For instructions and examples, see the [Transformers integration
    guide](https://docs.neptune.ai/integrations/transformers) in the Neptune documentation.
    z%source_code/integrations/transformersmodel_parametersr_   r$  trainer_parametersztrain/epochN
finetuningT)	api_tokenr  r   base_namespacer   log_parameterslog_checkpointsr  r  r   r  r  r  c                K   s^  t  stdzddlm}	 ddlm}
 W n ty*   ddlm}
 ddlm}	 Y nw |
d|t	t
d f |
d|t	t
d f |
d|t	t
d f |
d|t	 |
d	||	t
d f |
d
|t |
d|t	t
d f || _|| _|| _|| _d | _d| _d | _d| _|||d|| _d | _| jd u| _d | _| jdv rd| j | _d| _d S d| _d| _d S )NzwNeptuneCallback requires the Neptune client library to be installed. To install the library, run `pip install neptune`.r   r?  )verify_typer  r  r   r  r   r  r  F)r  r  r   >   r   lastzcheckpoints/Tcheckpoints)rT   r  r   r@  neptune.internal.utilsr  rG  neptune.new.internal.utils#neptune.new.metadata_containers.runr   r   r  _base_namespace_path_log_parameters_log_checkpoints_initial_run_run_is_monitoring_runr^  _force_reset_monitoring_run_init_run_kwargs_volatile_checkpoints_dir_should_upload_checkpoint_recent_checkpoint_path_target_checkpoints_namespace*_should_clean_recently_uploaded_checkpoint)rh  r  r  r   r  r   r  r  neptune_run_kwargsr@  r  r-   r-   r.   rj    sF   


zNeptuneCallback.__init__c                 C   s"   | j r| j   | ` d | _ d S d S rR   )r  stopr  r-   r-   r.   _stop_run_if_exists  s
   

z#NeptuneCallback._stop_run_if_existsc              
   K   s   zddl m} ddlm}m} W n ty'   ddlm} ddlm}m} Y nw |   z|	 }|
| j |di || _| jd  | _W d S  ||fy[ } zt |d }~ww )Nr   )init_run)NeptuneMissingApiTokenException"NeptuneMissingProjectNameExceptionsys/idr-   )r   r  neptune.exceptionsr  r  rG  neptune.newneptune.new.exceptionsr  copyr   r  r  r&  r^  r  )rh  additional_neptune_kwargsr  r  r  
run_paramser-   r-   r.   _initialize_run  s"   zNeptuneCallback._initialize_runc                 C   s(   | j | _d| _| jd  | _d | _ d S )NTr  )r  r  r  r&  r^  r  r-   r-   r.   _use_initial_run	  s   
z NeptuneCallback._use_initial_runc                 C   sb   | j d ur|   d S | js| jrd S | jr(| js(| js(| j| jd d| _d S |   d| _d S )N)with_idTF)r  r  r  r  r  r  r^  r  r-   r-   r.   _ensure_run_with_monitoring  s   


z+NeptuneCallback._ensure_run_with_monitoringc                 C   s@   | j d ur|   d S | js| j| jddddd d| _d S d S )NF)r  capture_stdoutcapture_stderrcapture_hardware_metricscapture_traceback)r  r  r  r  r^  r  r  r-   r-   r.   '_ensure_at_least_run_without_monitoring  s   

z7NeptuneCallback._ensure_at_least_run_without_monitoringc                 C   s   | j d u r	|   | j S rR   )r  r  r  r-   r-   r.   r   +  s   
zNeptuneCallback.runc                 C   s   | j | j S rR   )r   r  r  r-   r-   r.   _metadata_namespace1  s   z#NeptuneCallback._metadata_namespacec                 C   s   t | jtj< d S rR   )r  r   r  integration_version_keyr  r-   r-   r.   _log_integration_version5  r4   z(NeptuneCallback._log_integration_versionc                 C   s   |  | jtj< d S rR   )to_sanitized_dictr  r  trainer_parameters_key)rh  ru   r-   r-   r.   _log_trainer_parameters8  s   z'NeptuneCallback._log_trainer_parametersc                 C   sJ   ddl m} |rt|dr!|jd ur#||j | jtj< d S d S d S d S )Nr   )stringify_unsupportedr   )neptune.utilsr  r   r   r  r  r  model_parameters_key)rh  r   r  r-   r-   r.   _log_model_parameters;  s   z%NeptuneCallback._log_model_parametersc                 C   sR   |rt |dr|j| jtj< |r#t |dr%|jd ur'|j| jtj< d S d S d S d S )Nr=  r$  )r   r=  r  r  trial_name_keyr$  trial_params_key)rh  r<  r-   r-   r.   "_log_hyper_param_search_parametersC  s
   z2NeptuneCallback._log_hyper_param_search_parameterssource_directoryr   c           	   
   C   s   t j|| }}| jd urMt j| j|}z|ddt jj}t j||}t|| |}W n t	yL } zt
d| W Y d }~nd }~ww | j| j | | jrh| jd urh| j| j | j || _d S )Nz..r#   zpNeptuneCallback was unable to made a copy of checkpoint due to I/O exception: '{}'. Could fail trying to upload.)r%   rs   rt   r  replacelstripr  shutilcopytreeIOErrorr(   r)   r   r  r  upload_filesr  r  delete_files)	rh  r  r   target_pathrelative_pathconsistent_checkpoint_path	cpkt_path	copy_pathr  r-   r-   r.   _log_model_checkpointJ  s&   

z%NeptuneCallback._log_model_checkpointc                 K   sH   d | _ | jr|js|jd urt j| _ | jdkr |js"tdd S d S )Nr   zWTo save the best model checkpoint, the load_best_model_at_end argument must be enabled.)	r  r  overwrite_output_dirsave_total_limitr   r   r   r  r  r  r-   r-   r.   rC  b  s   zNeptuneCallback.on_init_endc                 K   sR   |j sd S |   d| _|   | jr| | | | |jr'| | d S d S )NT)	ro  r  r  r  r  r  r  rp  r  r1  r-   r-   r.   ru  j  s   

zNeptuneCallback.on_train_beginc                 K   s   |    d S rR   )r  r  r-   r-   r.   r  y  s   zNeptuneCallback.on_train_endc                 C   s&   | j d urtj| j dd |   d S )NT)ignore_errors)r  r  rmtreer  r  r-   r-   r.   r~  |  s   
zNeptuneCallback.__del__c                 K   s$   | j r| |jd|j  d S d S )Nr  )r  r  r  r|  r  r-   r-   r.   r       zNeptuneCallback.on_savec           	      K   s`   | j dkr.|j}|dsd| }||}|jrtjntj}|jd u p*|||j| _	d S d S )Nr   rX  )
r  r  rr   r   greater_is_betternpgreaterlessr  r  )	rh  ru   r<  rs  r   r   best_metric_namemetric_valueoperatorr-   r-   r.   on_evaluate  s   



zNeptuneCallback.on_evaluatec                 C   s*   |j jD ]}t|| r|j  S qtd)Nz6The trainer doesn't have a NeptuneCallback configured.)rH  rI  r^   r   	Exception)r   r   rR  r-   r-   r.   get_run  s
   

zNeptuneCallback.get_runr  c                 K   sj   |j sd S |d ur1t| D ]#\}}t|ttfr0|tjv r%|| j|< q| j| j	||j
d qd S d S )Nr4  )ro  r?  r+  r^   ry  rz  r  flat_metricsr  r  r|  )rh  ru   r<  rs  r  r   r   r   r-   r-   r.   r    s   
zNeptuneCallback.on_logrR   )&r   r  r  r  r  r  r  r  r  r  r
   r   r  rj  r  r  r  r  r  r  r   r  r  r  r  r  r  rC  ru  r  r~  r  r  r  r  r   rz  r  r-   r-   r-   r.   r    sf    	
7




 r  c                   @   s2   e Zd ZdZdd Zdd ZdddZd	d
 ZdS )CodeCarbonCallbackzI
    A [`TrainerCallback`] that tracks the CO2 emission of training.
    c                 C   s6   t  stdtjjrtddd l}|| _d | _d S )NzWCodeCarbonCallback requires `codecarbon` to be installed. Run `pip install codecarbon`.aZ  CodeCarbonCallback requires `codecarbon` package, which is not compatible with AMD ROCm (https://github.com/mlco2/codecarbon/pull/490). When using the Trainer, please specify the `report_to` argument (https://huggingface.co/docs/transformers/v4.39.3/en/main_classes/trainer#transformers.TrainingArguments.report_to) to disable CodeCarbonCallback.r   )rV   rc   r|   r  hiprU   _codecarbontracker)rh  rU   r-   r-   r.   rj    s   
zCodeCarbonCallback.__init__c                 K   s.   | j d u r|jr| jj|jd| _ d S d S d S )N)r  )r  is_local_process_zeror  EmissionsTrackerr  r  r-   r-   r.   rC    s   zCodeCarbonCallback.on_init_endNc                 K   "   | j r|jr| j   d S d S d S rR   )r  r  r(  r1  r-   r-   r.   ru       z!CodeCarbonCallback.on_train_beginc                 K   r  rR   )r  r  r  r  r-   r-   r.   r    r  zCodeCarbonCallback.on_train_endrR   )r   r  r  r  rj  rC  ru  r  r-   r-   r-   r.   r    s    
r  c                   @   sx   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd	Zd
ZdZdd Zdd ZdddZdd ZdddZdd Zdd ZdS )ClearMLCallbacka  
    A [`TrainerCallback`] that sends the logs to [ClearML](https://clear.ml/).

    Environment:
    - **CLEARML_PROJECT** (`str`, *optional*, defaults to `HuggingFace Transformers`):
        ClearML project name.
    - **CLEARML_TASK** (`str`, *optional*, defaults to `Trainer`):
        ClearML task name.
    - **CLEARML_LOG_MODEL** (`bool`, *optional*, defaults to `False`):
        Whether to log models as artifacts during training.
    r#   TransformerszModel Configuration_ignore_hparams_ui_overrides_"_ignore_model_config_ui_overrides_z%The configuration of model number {}.zNote that, when cloning this task and running it remotely, the configuration might be applied to another model instead of this one. To avoid this, initialize the task externally by calling `Task.init` before the `ClearMLCallback` is instantiated.r   FNc                 C   s:   t  rdd l}|| _ntdd| _d | _d| _g | _d S )Nr   zNClearMLCallback requires 'clearml' to be installed. Run `pip install clearml`.F)r3   r1   _clearmlrc   r  _clearml_taskr  _checkpoints_saved)rh  r1   r-   r-   r.   rj    s   
zClearMLCallback.__init__c           
      K   s  | j d u rd S | jrd S t jd7  _t jd7  _tjdkr!dndttj t_|jrat	d | j
d u rtjd u rO| j j rH| j j rLdt_ndt_| j j r|| j j r|| j j | _
tdtjsjdnd	 td	hv | _t	d
 n.| j jjtddtddddddd| _
tdd	 td	hv | _dt_t	d d| _tjtj }|d tj }| j j r| || | j
j|dtdd n| j
j|ddds| j
|| n
| |tjtj  t|dd d urc|d tj }tj !tj}	tjtjkr|	dtj" 7 }	| j j r4| j
j|dtdd | j
j#tj$tj |j%& |	d d S | j
j|dddsO|j%'| j
(tj$tj |_%d S | j
j#tj$tj |j%& |	d d S d S d S )Nrj   r#   r  z"Automatic ClearML logging enabled.FTCLEARML_LOG_MODELrL   rM   z)External ClearML Task has been connected.CLEARML_PROJECTzHuggingFace TransformersCLEARML_TASKr  )r=   pytorch)project_name	task_nameauto_connect_frameworks
output_uriz"ClearML Task has been initialized./zIf True, ignore Transformers hyperparameters overrides done in the UI/backend when running remotely. Otherwise, the overrides will be applied when running remotely)r   r   
value_typerD  )defaultcastr    zIf True, ignore Transformers model configuration overrides done in the UI/backend when running remotely. Otherwise, the overrides will be applied when running remotely)r   config_dictrD  ))r  r  r  _train_run_counter_model_connect_counterr   
log_suffixro  r(   r   r  _should_close_on_train_endTaskrunning_locallycurrent_taskr%   r&   _task_created_in_callbackr'   r    unionr  r;  _hparams_section_ignore_hparams_overrides_copy_training_args_as_hparamsset_parameterr  get_parameterconnectr   _ignoge_model_config_overrides_model_config_descriptionr   _model_config_description_noteset_configuration_object_model_config_sectionr   r  	from_dict get_configuration_object_as_dict)
rh  ru   r<  r   r  r   suffixed_hparams_sectionignore_hparams_config_sectionignore_model_config_section configuration_object_descriptionr-   r-   r.   r    s   






		





4zClearMLCallback.setupc                 K   sF   | j d u rd S g | _|jrd| _| js!| j||||fi | d S d S r  )r  r  rp  r  r  rh  ru   r<  rs  r   r  r   r-   r-   r.   ru  Y  s   
zClearMLCallback.on_train_beginc                 K   s   t jr| j  dt _d S d S )Nr   )r  r  r  r  r  r  r-   r-   r.   r  b  r  zClearMLCallback.on_train_endc              
   K   sJ  | j d u rd S | js| j||||fi | |jrd}t|}	d}
t|
}g d}| D ]u\}}t|ttfr||v rJ| j	
 j|tj |d q-||rd| j	
 jdtj ||	d  ||jd q-||
r~| j	
 jdtj ||d  ||jd q-| j	
 jdtj |||jd q-td	| d
t| d| d q-d S d S )NrX  rY  )r  r  r  r   r  r  r  eval)titleseriesr   	iterationtestr   rv  rw  rx  zn" as a scalar. This invocation of ClearML logger's  report_scalar() is incorrect so we dropped this attribute.)r  r  r  ro  r[  r+  r^   ry  rz  r  
get_loggerreport_single_valuer  r  rr   report_scalarr|  r(   r)   r   )rh  ru   r<  rs  r   r  r  r   r^  r_  r`  ra  r  rb  rc  r-   r-   r.   r  g  s^   









zClearMLCallback.on_logc           
   
   K   sH  | j r| jr|jrd|j }tj|j|}|tj	 }t
d| d | jj| j|d}|j| j|d |j|||jdd | j| |jr|jt| jk rz| jjjj| jd dddd	 W n  ty }	 zt
d
| jd j|	 W Y d }	~	d S d }	~	ww | jdd  | _|jr|jt| jk sQd S d S d S d S d S d S d S )Nr  zLogging checkpoint artifact `z`. This may take some time.)taskr   F)weights_pathtarget_filenamer0  auto_delete_filer   T)delete_weights_fileforceraise_on_errorszVCould not remove checkpoint `{}` after going over the `save_total_limit`. Error is: {}rj   )r  r  ro  r|  r%   rs   rt   r  r  r  r(   r   r  OutputModelr   update_weights_packager  rV  r  r[  r   Modelremover  r)   r   r   )
rh  ru   r<  rs  r   r  r  r   output_modelr  r-   r-   r.   r    sF   


zClearMLCallback.on_savec                    sJ    fddt  D }dd | jjj| D }| jjj||d d S )Nc                    s.   i | ]}|j r|jd s|jt |jqS )_token)r;  r   endswithr   )r   fieldtraining_argsr-   r.   r    s    
zBClearMLCallback._copy_training_args_as_hparams.<locals>.<dictcomp>c                 S   s   i | ]	\}}t ||qS r-   )r   r  r-   r-   r.   r    s    )prefix)	r   r  	utilitiesproxy_objectflatten_dictionaryr+  r  
_argumentscopy_from_dict)rh  rE  rF  as_dict	flat_dictr-   rD  r.   r    s
   
z.ClearMLCallback._copy_training_args_as_hparamsr  )NNN)r   r  r  r  r  r  r%  r  r!  r"  r#  r  r  r  r  rj  r  ru  r  r  r  r  r-   r-   r-   r.   r    s*    
c	
5 r  c                       s<   e Zd ZdZddedef fddZdd Zd	d
 Z  ZS )FlyteCallbacka^  A [`TrainerCallback`] that sends the logs to [Flyte](https://flyte.org/).
    NOTE: This callback only works within a Flyte task.

    Args:
        save_log_history (`bool`, *optional*, defaults to `True`):
            When set to True, the training logs are saved as a Flyte Deck.

        sync_checkpoints (`bool`, *optional*, defaults to `True`):
            When set to True, checkpoints are synced with Flyte and can be used to resume training in the case of an
            interruption.

    Example:

    ```python
    # Note: This example skips over some setup steps for brevity.
    from flytekit import current_context, task


    @task
    def train_hf_transformer():
        cp = current_context().checkpoint
        trainer = Trainer(..., callbacks=[FlyteCallback()])
        output = trainer.train(resume_from_checkpoint=cp.restore())
    ```
    Tsave_log_historysync_checkpointsc                    sX   t    t stdt rt std d}ddlm	} | j
| _|| _|| _d S )NzLFlyteCallback requires flytekit to be installed. Run `pip install flytekit`.zSyncing log history requires both flytekitplugins-deck-standard and pandas to be installed. Run `pip install flytekitplugins-deck-standard pandas` to enable this feature.Fr   )current_context)r  rj  rX   rG  rY   r   r(   r)   rW   rQ  r   cprO  rP  )rh  rO  rP  rQ  r  r-   r.   rj    s   


zFlyteCallback.__init__c                 K   sR   | j r%|jr'd|j }tj|j|}td| d | j	
| d S d S d S )Nr  zSyncing checkpoint in z to Flyte. This may take time.)rP  ro  r|  r%   rs   rt   r  r(   r   rR  r  r|  r-   r-   r.   r    s   zFlyteCallback.on_savec           	      K   sL   | j r$dd l}ddlm} ddlm} ||j}|d| | d S d S )Nr   )Deck)TableRendererzLog History)	rO  pandasrW   rS  flytekitplugins.deck.rendererrT  	DataFramelog_historyto_html)	rh  ru   r<  rs  r   pdrS  rT  log_history_dfr-   r-   r.   r    s   zFlyteCallback.on_train_end)TT)	r   r  r  r  r  rj  r  r  r  r-   r-   r  r.   rN    s
    rN  c                   @   sh   e Zd ZdZ		ddee deeed ef  fddZ	dd	 Z
dd
dZdddZdd Zdd ZdS )DVCLiveCallbackaW  
    A [`TrainerCallback`] that sends the logs to [DVCLive](https://www.dvc.org/doc/dvclive).

    Use the environment variables below in `setup` to configure the integration. To customize this callback beyond
    those environment variables, see [here](https://dvc.org/doc/dvclive/ml-frameworks/huggingface).

    Args:
        live (`dvclive.Live`, *optional*, defaults to `None`):
            Optional Live instance. If None, a new instance will be created using **kwargs.
        log_model (Union[Literal["all"], bool], *optional*, defaults to `None`):
            Whether to use `dvclive.Live.log_artifact()` to log checkpoints created by [`Trainer`]. If set to `True`,
            the final checkpoint is logged at the end of training. If set to `"all"`, the entire
            [`TrainingArguments`]'s `output_dir` is logged at each checkpoint.
    Nliverz  r  c                 K   s   t  stdddlm} d| _d | _t||r|| _n|d ur)td|j d|| _| jd u rMt	
dd}| tv rBd	| _d S | d
krOd
| _d S d S d S )NzLDVCLiveCallback requires dvclive to be installed. Run `pip install dvclive`.r   LiveFzFound class z  for live, expected dvclive.LiveHF_DVCLIVE_LOG_MODELrL   Tr  )r[   rc   rZ   r_  r  r]  r^   rd   r  r%   r&   r'   r    r&  )rh  r]  rz  r   r_  log_model_envr-   r-   r.   rj    s$   



zDVCLiveCallback.__init__c                 C   s>   ddl m} d| _|jr| js| | _| j|  dS dS )a@  
        Setup the optional DVCLive integration. To customize this callback beyond the environment variables below, see
        [here](https://dvc.org/doc/dvclive/ml-frameworks/huggingface).

        Environment:
        - **HF_DVCLIVE_LOG_MODEL** (`str`, *optional*):
            Whether to use `dvclive.Live.log_artifact()` to log checkpoints created by [`Trainer`]. If set to `True` or
            *1*, the final checkpoint is logged at the end of training. If set to `all`, the entire
            [`TrainingArguments`]'s `output_dir` is logged at each checkpoint.
        r   r^  TN)rZ   r_  r  ro  r]  rk  r  )rh  ru   r<  r   r_  r-   r-   r.   r  .  s   zDVCLiveCallback.setupc                 K   r/  rR   r0  r1  r-   r-   r.   ru  A  r2  zDVCLiveCallback.on_train_beginc              
   K   s   | j s
| ||| |jrJddlm} ddlm} | D ]%\}	}
||
r1| j	
||	d|
 qtd|
 dt|
 d|	 d q| j	  d S d S )	Nr   )Metric)standardize_metric_namezdvclive.huggingfacerv  rw  rx  zh" as a scalar. This invocation of DVCLive's Live.log_metric() is incorrect so we dropped this attribute.)r  r  ro  dvclive.plotsrb  dvclive.utilsrc  r+  	could_logr]  r  r(   r)   r   	next_step)rh  ru   r<  rs  r   r  r   rb  rc  r1  r   r-   r-   r.   r  E  s&   
zDVCLiveCallback.on_logc                 K   s4   | j dkr| jr|jr| j|j d S d S d S d S )Nr  )r  r  ro  r]  r  r  r  r-   r-   r.   r  X  s   zDVCLiveCallback.on_savec           	      K   s   | j rE|jrGddlm} | jdu r>|||d|ddgd}|jr%dnd	}tj	|j
|}|| | jj||ddd
 | j  d S d S d S )Nr   r  Tr   r  r  r  r   r  )r   r   r  )r  ro  transformers.trainerr  r  r   r  r%   rs   rt   r  r  r]  r  r  )	rh  ru   r<  rs  r   r  r  r   r  r-   r-   r.   r  \  s   

zDVCLiveCallback.on_train_endr  rR   )r   r  r  r  r
   r   r   r	   r  rj  r  ru  r  r  r  r-   r-   r-   r.   r\    s    


r\  c                   @   r  )SwanLabCallbackzn
    A [`TrainerCallback`] that logs metrics, media, model checkpoints to [SwanLab](https://swanlab.cn/).
    c                 C   s4   t  stddd l}|| _d| _tdd | _d S )NzLSwanLabCallback requires swanlab to be installed. Run `pip install swanlab`.r   FSWANLAB_LOG_MODEL)r]   rc   r\   _swanlabr  r%   r&   r  )rh  r\   r-   r-   r.   rj  s  s   zSwanLabCallback.__init__c                 K   s  d| _ |jrtd i | }t|dr/|jdur/t|jtr$|jn|j }i ||}t|drD|j	durD|j	}i d|i|}|j
}i }	|durX|j d| |	d< n
|jdurb|j|	d< tdd|	d	< | j du rz| jjdi |	 d
| jjd< | jj| z3| jjd| i t|jdkst|jdkr| \}
}| jjd|
i | jjd|i W n ty   td Y nw | jdurtd d| j jjj d}t jd| 7  _dS dS dS )a	  
        Setup the optional SwanLab (*swanlab*) integration.

        One can subclass and override this method to customize the setup if needed. Find more information
        [here](https://docs.swanlab.cn/guide_cloud/integration/integration-huggingface-transformers.html).

        You can also override the following environment variables. Find more information about environment
        variables [here](https://docs.swanlab.cn/en/api/environment-variable.html#environment-variables)

        Environment:
        - **SWANLAB_API_KEY** (`str`, *optional*, defaults to `None`):
            Cloud API Key. During login, this environment variable is checked first. If it doesn't exist, the system
            checks if the user is already logged in. If not, the login process is initiated.

                - If a string is passed to the login interface, this environment variable is ignored.
                - If the user is already logged in, this environment variable takes precedence over locally stored
                login information.

        - **SWANLAB_PROJECT** (`str`, *optional*, defaults to `None`):
            Set this to a custom string to store results in a different project. If not specified, the name of the current
            running directory is used.

        - **SWANLAB_LOG_DIR** (`str`, *optional*, defaults to `swanlog`):
            This environment variable specifies the storage path for log files when running in local mode.
            By default, logs are saved in a folder named swanlog under the working directory.

        - **SWANLAB_MODE** (`Literal["local", "cloud", "disabled"]`, *optional*, defaults to `cloud`):
            SwanLab's parsing mode, which involves callbacks registered by the operator. Currently, there are three modes:
            local, cloud, and disabled. Note: Case-sensitive. Find more information
            [here](https://docs.swanlab.cn/en/api/py-init.html#swanlab-init)

        - **SWANLAB_LOG_MODEL** (`str`, *optional*, defaults to `None`):
            SwanLab does not currently support the save mode functionality.This feature will be available in a future
            release

        - **SWANLAB_WEB_HOST** (`str`, *optional*, defaults to `None`):
            Web address for the SwanLab cloud environment for private version (its free)

        - **SWANLAB_API_HOST** (`str`, *optional*, defaults to `None`):
            API address for the SwanLab cloud environment for private version (its free)

        TzYAutomatic SwanLab logging enabled, to disable set os.environ["SWANLAB_MODE"] = "disabled"r   Nr  -experiment_nameSWANLAB_PROJECTr  u   🤗transformers	FRAMEWORKmodel_num_parameters	PeftModelPeftMixedModelpeft_model_trainable_paramspeft_model_all_paramzQCould not log the number of model parameters in SwanLab due to an AttributeError.sSwanLab does not currently support the save mode functionality. This feature will be available in a future release.z[<img src="https://raw.githubusercontent.com/SwanHubX/assets/main/badge1.svg" alt="Visualize in SwanLab" height="280" height="32"/>](r  r  r-   )r  ro  r(   r   r  r   r   r^   rb   r  r=  r  r%   r&   rk  r  r;  r   r  r   r   get_nb_trainable_parametersr  r  r)   publiccloudexp_urlr   r  )rh  ru   r<  r   r   r  rn  r  r=  r  trainable_params	all_paramr  r-   r-   r.   r  |  sX   +




'zSwanLabCallback.setupNc                 K   s$   | j s| j|||fi | d S d S rR   r0  r1  r-   r-   r.   ru    r  zSwanLabCallback.on_train_beginc                 K   0   | j d ur| jr|jrtd d S d S d S d S Nru  r  r  ro  r(   r)   r,  r-   r-   r.   r    
   zSwanLabCallback.on_train_endc           
         s   g d | j s| ||| |jrM| D ]\}}| v r+| jjd| |i|jd q fdd| D }	t|	}	| jji |	d|ji|jd d S d S )Nr  zsingle_value/r  c                    r  r-   r-   r  r  r-   r.   r    r  z*SwanLabCallback.on_log.<locals>.<dictcomp>r  )r  r  ro  r+  rk  r  r|  r?  r  r-   r  r.   r    s   $zSwanLabCallback.on_logc                 K   r|  r}  r~  r  r-   r-   r.   r    r  zSwanLabCallback.on_savec                 K   s<   | j s| j||fi | |jrt|}| j| d S d S rR   )r  r  ro  r?  rk  r  r  r-   r-   r.   r  	  s   zSwanLabCallback.on_predictrR   r  r  r-   r-   r-   r.   ri  n  s    	
a

ri  )rU  r   rN   r   r=   r$   rU   r1   rP   flyterZ   r\   c                 C   sv   | d u rg S t | trd| krg S d| krt } n| g} | D ]}|tvr3t| ddt  dqdd | D S )Nnoner  z is not supported, only r  z are supported.c                 S   s   g | ]}t | qS r-   )INTEGRATION_TO_CALLBACK)r   integrationr-   r-   r.   r   ,	  s    z7get_reporting_integration_callbacks.<locals>.<listcomp>)r^   r   rW  r  r  rt   r@  )rK  r  r-   r-   r.   #get_reporting_integration_callbacks	  s   
r  )|r  r   importlib.metadatar*   importlib.utilrl  r  r%   r  r  r   r   dataclassesr   r   enumr   pathlibr   typingr   r   r   r	   r
   r   numpyr  packaging.versionr`  r#   r   r   r   r  rF  r   r   r   r   r   r   r   r2  r   r(   r|   r:   r  r9   r7   ra  r8   r   r   
get_configr;   PackageNotFoundErrorrG  r  	TypeErrorr  KeyErrorr+   r,   rS   _neptune_versionr   r   trainer_callbackr   r   r   r   r   r   rE  r   r    r!   r/   r3   r<   r?   rA   rC   rE   rH   rJ   rO   rQ   rT   rV   rX   rY   r[   r]   re   ry  r   r   r  r2  rT  rW  r?  r   r  r  rJ  r  r=  rE  r  r  r  r  r  r  rN  r\  ri  r  r  r-   r-   r-   r.   <module>   s    $
!> bMX w  31  " ~?i 