
    &`i"                     .   d dl Z d dlmZ d dlmZ d dlmZ d dlmZ d dl	m
Z
mZmZmZmZ d dlmZ d dlZd dlmZ d d	lmZ d d
lmZ 	 d dlmZ n# e$ r  G d d          ZY nw xY w G d de          Z ed           G d de                      ZdS )    N)abstractmethod)OrderedDict)contextmanager)Path)CallableDictListOptionalUnion)Booster)
Checkpoint)flatten_dict)	PublicAPI)TrainingCallbackc                       e Zd ZdS )r   N)__name__
__module____qualname__     t/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/train/xgboost/_xgboost_utils.pyr   r      s        r   r   c                      e Zd ZdZdedddfdeeeee         eeef         f                  dede	de
d	eeeeeeee         f         f         geeef         f                  f
d
Zeefdededefd            Zd Zededee         fd            Zededefd            Zedefd            Zdede	defdZdedefdZdS )RayReportCallbackz	model.ubjNr   Tmetricsfilename	frequencycheckpoint_at_endresults_postprocessing_fnc                     t          |t                    r|g}|| _        || _        || _        || _        || _        d | _        d | _        d S N)	
isinstancestr_metrics	_filename
_frequency_checkpoint_at_end_results_postprocessing_fn
_evals_log_last_checkpoint_iteration)selfr   r   r   r   r   s         r   __init__zRayReportCallback.__init__   s[     gs## 	 iG!#"3*C'
  +/'''r   
checkpointreturnc                     |                                 5 }t                      }|                    t          ||                                                     |cddd           S # 1 swxY w Y   dS )a  Retrieve the model stored in a checkpoint reported by this callback.

        Args:
            checkpoint: The checkpoint object returned by a training run.
                The checkpoint should be saved by an instance of this callback.
            filename: The filename to load the model from, which should match
                the filename used when creating the callback.

        Returns:
            The model loaded from the checkpoint.
        N)as_directoryr   
load_modelr   as_posix)clsr,   r   checkpoint_pathboosters        r   	get_modelzRayReportCallback.get_model4   s    " $$&& 	/iiGtOX>>GGIIJJJ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   AA''A+.A+c                    t          |t                    r5t          |d          }t          |          D ]}||         d         ||<   nt	          |          }| j        s|}nAi }| j        D ]7}t          | j        t                    r| j        |         }n|}||         ||<   8| j        r|                     |          }|S )N-)	delimiter)r!   r   r   listdictr#   r'   )r*   	evals_logresult_dictkreport_dictkeymetrics          r   _get_report_dictz"RayReportCallback._get_report_dictJ   s    i-- 	*&yC@@@K+&& 4 4!,Q!3A4 y//K} 		7%KKK} 7 7dmT22 !!]3/FF F#.v#6C  * 	G99+FFKr   modelc                     t           )z_Get checkpoint from model.

        This method needs to be implemented by subclasses.
        NotImplementedError)r*   rC   s     r   _get_checkpointz!RayReportCallback._get_checkpointc   
     "!r   r?   c                     t           )zSave checkpoint and report metrics corresonding to this checkpoint.

        This method needs to be implemented by subclasses.
        rE   )r*   r?   rC   s      r   _save_and_report_checkpointz-RayReportCallback._save_and_report_checkpointk   rH   r   c                     t           )zTReport Metrics.

        This method needs to be implemented by subclasses.
        rE   r*   r?   s     r   _report_metricsz!RayReportCallback._report_metricss   rH   r   epochr<   c                     || _         | j        dk    }| o|dz   | j        z  dk    }|                     |          }|r|| _        |                     ||           d S |                     |           d S )Nr      )r(   r%   rB   r)   rJ   rM   )r*   rC   rN   r<   checkpointing_disabledshould_checkpointr?   s          r   after_iterationz!RayReportCallback.after_iteration{   s    #!%A!5 '&MEAI+HA+M 	 ++I66 	..3D+,,[%@@@@@   -----r   c                     | j         s|S | j        "|                                dz
  | j        k    r|S | j        r|                     | j                  ni }|                     ||           |S )NrP   )r&   r)   num_boosted_roundsr(   rB   rJ   )r*   rC   r?   s      r   after_trainingz RayReportCallback.after_training   s    & 	L +7((**Q.$2QQQ L@DWd++DO<<<UW((e<<<r   )r   r   r   CHECKPOINT_NAMEr
   r   r"   r	   r   intboolr   floatr+   classmethodr   r   r5   rB   r   rG   rJ   rM   rS   rV   r   r   r   r   r      s       !O DH'"& / /%T#YS#X >?@/ / 	/
  / $,d3eT%[&8 99:;T#u*=MMN$
/ / / /4  (   
	   [*  2 "W "*1E " " " ^" "t "G " " " ^" "4 " " " ^".W .S .T . . . ."G       r   r   beta)	stabilityc                   *    e Zd ZdZdej        dddfdeeee	e         e
eef         f                  dededed	eee
eeee	e         f         f         ge
eef         f                  f
 fd
Zededee         fd            Zde
defdZde
fdZ xZS )RayTrainReportCallbackaa  XGBoost callback to save checkpoints and report metrics.

    Args:
        metrics: Metrics to report. If this is a list,
            each item describes the metric key reported to XGBoost,
            and it will be reported under the same name.
            This can also be a dict of {<key-to-report>: <xgboost-metric-key>},
            which can be used to rename xgboost default metrics.
        filename: Customize the saved checkpoint file type by passing
            a filename. Defaults to "model.ubj".
        frequency: How often to save checkpoints, in terms of iterations.
            Defaults to 0 (no checkpoints are saved during training).
        checkpoint_at_end: Whether or not to save a checkpoint at the end of training.
        results_postprocessing_fn: An optional Callable that takes in
            the metrics dict that will be reported (after it has been flattened)
            and returns a modified dict. For example, this can be used to
            average results across CV fold when using ``xgboost.cv``.

    Examples
    --------

    Reporting checkpoints and metrics to Ray Tune when running many
    independent xgboost trials (without data parallelism within a trial).

    .. testcode::
        :skipif: True

        import xgboost

        from ray.tune import Tuner
        from ray.train.xgboost import RayTrainReportCallback

        def train_fn(config):
            # Report log loss to Ray Tune after each validation epoch.
            bst = xgboost.train(
                ...,
                callbacks=[
                    RayTrainReportCallback(
                        metrics={"loss": "eval-logloss"}, frequency=1
                    )
                ],
            )

        tuner = Tuner(train_fn)
        results = tuner.fit()

    Loading a model from a checkpoint reported by this callback.

    .. testcode::
        :skipif: True

        from ray.train.xgboost import RayTrainReportCallback

        # Get a `Checkpoint` object that is saved by the callback during training.
        result = trainer.fit()
        booster = RayTrainReportCallback.get_model(result.checkpoint)

    Nr   Tr   r   r   r   r   c                 T    t                                          |||||           d S )N)r   r   r   r   r   )superr+   )r*   r   r   r   r   r   	__class__s         r   r+   zRayTrainReportCallback.__init__   s?     	/&? 	 	
 	
 	
 	
 	
r   rC   r-   c              #   h  K   t           j                                                                        dv ryt	          j                    5 }|                    t          || j                  	                                           t          |          V  d d d            d S # 1 swxY w Y   d S d V  d S )N)r   N)raytrainget_contextget_world_ranktempfileTemporaryDirectory
save_modelr   r$   r1   r   )r*   rC   temp_checkpoint_dirs      r   rG   z&RayTrainReportCallback._get_checkpoint   s       9  ""1133y@@,.. 62E  &94>!J!J!S!S!U!UVVV !4555556 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 JJJJJs   AB!!B%(B%r?   c                     |                      |          5 }t          j                            ||           d d d            d S # 1 swxY w Y   d S )N)rC   )r,   )rG   rd   re   report)r*   r?   rC   r,   s       r   rJ   z2RayTrainReportCallback._save_and_report_checkpoint   s    !!!.. 	A*I[Z@@@	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	As   "AA
A
c                 D    t           j                            |           d S r    )rd   re   rm   rL   s     r   rM   z&RayTrainReportCallback._report_metrics   s    	%%%%%r   )r   r   r   __doc__r   rW   r
   r   r"   r	   r   rX   rY   r   rZ   r+   r   r   r   rG   rJ   rM   __classcell__)rb   s   @r   r_   r_      s^       9 9z DH)9"& 
 
%T#YS#X >?@
 
 	

  
 $,d3eT%[&8 99:;T#u*=MMN$

 
 
 
 
 
$ W *1E    ^At AG A A A A&4 & & & & & & & &r   r_   )rh   abcr   collectionsr   
contextlibr   pathlibr   typingr   r   r	   r
   r   xgboost.corer   	ray.trainrd   r   ray.tune.utilsr   ray.util.annotationsr   xgboost.callbackr   ImportErrorr   r_   r   r   r   <module>r|      s          # # # # # # % % % % % %       8 8 8 8 8 8 8 8 8 8 8 8 8 8                             ' ' ' ' ' ' * * * * * *1111111            D D D D D( D D DN V]& ]& ]& ]& ]&. ]& ]& ]& ]& ]&s   A A$#A$