o
    $i"                     @   s   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 zd dlmZ W n ey^   G dd dZY nw G dd deZeddG dd deZdS )    N)abstractmethod)OrderedDict)contextmanager)Path)CallableDictListOptionalUnion)Booster)
Checkpoint)flatten_dict)	PublicAPI)TrainingCallbackc                   @   s   e Zd ZdS )r   N)__name__
__module____qualname__ r   r   ]/home/ubuntu/veenaModal/venv/lib/python3.10/site-packages/ray/train/xgboost/_xgboost_utils.pyr      s    r   c                   @   s  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
dZeefdededefddZdd Zededee fddZededefddZedefddZdede	defddZdedefddZdS ) RayReportCallbackz	model.ubjNr   Tmetricsfilename	frequencycheckpoint_at_endresults_postprocessing_fnc                 C   s>   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   r   r   r   __init__   s   


zRayReportCallback.__init__
checkpointreturnc                 C   sJ   |  }t }|t||  |W  d   S 1 s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boosterr   r   r   	get_model4   s
   
$zRayReportCallback.get_modelc                 C   s   t |trt|dd}t|D ]
}|| d ||< qnt|}| js%|}ni }| jD ]}t | jtr8| j| }n|}|| ||< q*| jrI| |}|S )N-)	delimiter)r   r   r   listdictr   r"   )r&   	evals_logresult_dictkreport_dictkeymetricr   r   r   _get_report_dictJ   s"   


z"RayReportCallback._get_report_dictmodelc                 C      t )z_Get checkpoint from model.

        This method needs to be implemented by subclasses.
        NotImplementedError)r&   r=   r   r   r   _get_checkpointc      z!RayReportCallback._get_checkpointr9   c                 C   r>   )zSave checkpoint and report metrics corresonding to this checkpoint.

        This method needs to be implemented by subclasses.
        r?   )r&   r9   r=   r   r   r   _save_and_report_checkpointk   rB   z-RayReportCallback._save_and_report_checkpointc                 C   r>   )zTReport Metrics.

        This method needs to be implemented by subclasses.
        r?   r&   r9   r   r   r   _report_metricss   rB   z!RayReportCallback._report_metricsepochr6   c                 C   sZ   || _ | jdk}| o|d | j dk}| |}|r&|| _| || d S | | d S )Nr      )r#   r    r<   r$   rC   rE   )r&   r=   rF   r6   checkpointing_disabledshould_checkpointr9   r   r   r   after_iteration{   s   

z!RayReportCallback.after_iterationc                 C   sP   | j s|S | jd ur| d | jkr|S | jr| | jni }| || |S )NrG   )r!   r$   num_boosted_roundsr#   r<   rC   )r&   r=   r9   r   r   r   after_training   s   
z RayReportCallback.after_training)r   r   r   CHECKPOINT_NAMEr	   r
   r   r   r   intboolr   floatr'   classmethodr   r   r0   r<   r   rA   rC   rE   rJ   rL   r   r   r   r   r      sL    (
r   beta)	stabilityc                       s   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
dZededee fddZde
defddZde
fddZ  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                    s   t  j|||||d d S )N)r   r   r   r   r   )superr'   r%   	__class__r   r   r'      s   

zRayTrainReportCallback.__init__r=   r)   c                 c   sl    t j  dv r1t }|t|| j	  t
|V  W d    d S 1 s*w   Y  d S d V  d S )N)r   N)raytrainget_contextget_world_ranktempfileTemporaryDirectory
save_modelr   r   r,   r   )r&   r=   temp_checkpoint_dirr   r   r   rA      s   
"
z&RayTrainReportCallback._get_checkpointr9   c                 C   sB   | j |d}tjj||d W d    d S 1 sw   Y  d S )N)r=   )r(   )rA   rX   rY   report)r&   r9   r=   r(   r   r   r   rC      s   "z2RayTrainReportCallback._save_and_report_checkpointc                 C   s   t j| d S r   )rX   rY   r`   rD   r   r   r   rE      s   z&RayTrainReportCallback._report_metrics)r   r   r   __doc__r   rM   r	   r
   r   r   r   rN   rO   r   rP   r'   r   r   r   rA   rC   rE   __classcell__r   r   rV   r   rT      s0    =(	rT   )r\   abcr   collectionsr   
contextlibr   pathlibr   typingr   r   r   r	   r
   xgboost.corer   	ray.trainrX   r   ray.tune.utilsr   ray.util.annotationsr   xgboost.callbackr   ImportErrorr   rT   r   r   r   r   <module>   s(     