
    &`iw                         d dl 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mZ d dlZd dlmZ d d	lmZ d d
lmZ  G d d          Z ed           G d de                      ZdS )    N)abstractmethod)contextmanager)Path)CallableDictListOptionalUnion)Booster)CallbackEnv)
Checkpoint)flatten_dict)	PublicAPIc                      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eeeeef         f         defdZdedef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dfdZdS )RayReportCallbackz	model.txtNr   Tmetricsfilename	frequencycheckpoint_at_endresults_postprocessing_fnc                 |    t          |t                    r|g}|| _        || _        || _        || _        || _        d S N)
isinstancestr_metrics	_filename
_frequency_checkpoint_at_end_results_postprocessing_fn)selfr   r   r   r   r   s         v/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/train/lightgbm/_lightgbm_utils.py__init__zRayReportCallback.__init__   sH     gs## 	 iG!#"3*C'''    
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.
        )
model_fileN)as_directoryr   r   as_posix)clsr$   r   checkpoint_paths       r!   	get_modelzRayReportCallback.get_model%   s     $$&& 	R/d?H&E&E&N&N&P&PQQQ	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	R 	Rs   0AAA	evals_logc                     t          |d          }| j        s|}nAi }| j        D ]7}t          | j        t                    r| j        |         }n|}||         ||<   8| j        r|                     |          }|S )N-)	delimiter)r   r   r   dictr   )r    r-   result_dictreport_dictkeymetrics         r!   _get_report_dictz"RayReportCallback._get_report_dict6   s    "9<<<} 		7%KKK} 7 7dmT22 !!]3/FF F#.v#6C  * 	G99+FFKr#   envc                     i }|j         D ]Y}|dd         \  }}}t          |          dk    r|d         }d}nd }d}||vri ||<   |||         ||z   <   ||||         |dz   <   Z|S )Nr         z-mean z-stdv)evaluation_result_listlen)	r    r7   eval_resultentry	data_name	eval_nameresultstdvsuffixs	            r!   _get_eval_resultz"RayReportCallback._get_eval_resultF   s    / 	C 	CE+01:(Iy&5zzA~~Qx ++)+I&9?K	"9v#56>BI&y7':;r#   modelc                     t           )z_Get checkpoint from model.

        This method needs to be implemented by subclasses.
        NotImplementedError)r    rF   s     r!   _get_checkpointz!RayReportCallback._get_checkpointW   
     "!r#   r3   c                     t           )zSave checkpoint and report metrics corresonding to this checkpoint.

        This method needs to be implemented by subclasses.
        rH   )r    r3   rF   s      r!   _save_and_report_checkpointz-RayReportCallback._save_and_report_checkpoint_   rK   r#   c                     t           )zTReport Metrics.

        This method needs to be implemented by subclasses.
        rH   r    r3   s     r!   _report_metricsz!RayReportCallback._report_metricsg   rK   r#   c                 D   |                      |          }|                     |          }|j        |j        dz
  k    }|o| j        }| j        dk    o|j        dz   | j        z  dk    }|p|}|r|                     ||j                   d S |                     |           d S )N   r   )	rE   r6   	iterationend_iterationr   r   rM   rF   rP   )r    r7   r>   r3   on_last_itershould_checkpoint_at_end should_checkpoint_with_frequencyshould_checkpoints           r!   __call__zRayReportCallback.__call__o   s    ++C00++K88
 }(9A(==#/#KD4K Oq Ocma&74?%Ja%O 	) 5X8X 	.,,[#)DDDDD  -----r#   )__name__
__module____qualname__CHECKPOINT_NAMEr	   r
   r   r   r   intboolr   floatr"   classmethodr   r   r,   listr1   r6   r   rE   r   rJ   rM   rP   rY    r#   r!   r   r      s       !O DH'"& D D%T#YS#X >?@D D 	D
  D $,d3eT%[&8 99:;T#u*=MMN$
D D D D$ 5DR R#R/2R	R R R [R $sDdO/C*D      K D    " "W "*1E " " " ^" "t "G " " " ^" "4 " " " ^".K .D . . . . . .r#   r   beta)	stabilityc                   Z    e Zd ZdZededee         fd            Zde	defdZ
de	fdZdS )	RayTrainReportCallbacka  Creates a callback that reports metrics and checkpoints model.

    Args:
        metrics: Metrics to report. If this is a list,
            each item should be a metric key reported by LightGBM,
            and it will be reported to Ray Train/Tune under the same name.
            This can also be a dict of {<key-to-report>: <lightgbm-metric-key>},
            which can be used to rename LightGBM default metrics.
        filename: Customize the saved checkpoint file type by passing
            a filename. Defaults to "model.txt".
        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.

    Examples
    --------

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

    .. testcode::
        :skipif: True

        import lightgbm

        from ray.train.lightgbm import RayTrainReportCallback

        config = {
            # ...
            "metric": ["binary_logloss", "binary_error"],
        }

        # Report only log loss to Tune after each validation epoch.
        bst = lightgbm.train(
            ...,
            callbacks=[
                RayTrainReportCallback(
                    metrics={"loss": "eval-binary_logloss"}, frequency=1
                )
            ],
        )

    Loading a model from a checkpoint reported by this callback.

    .. testcode::
        :skipif: True

        from ray.train.lightgbm import RayTrainReportCallback

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

    rF   r%   c              #   r  K   t           j                                                                        dv r~t	          j                    5 }|                    t          || j                  	                                           t          j        |          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   r)   r   from_directory)r    rF   temp_checkpoint_dirs      r!   rJ   z&RayTrainReportCallback._get_checkpoint   s     9  ""1133y@@,.. E2E  &94>!J!J!S!S!U!UVVV /0CDDDDDE E E E E E E E E E E E E E E E E E JJJJJs   AB&&B*-B*r3   c                     |                      |          5 }t          j                            ||           d d d            d S # 1 swxY w Y   d S )N)rF   )r$   )rJ   ri   rj   report)r    r3   rF   r$   s       r!   rM   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   )ri   rj   rs   rO   s     r!   rP   z&RayTrainReportCallback._report_metrics   s    	%%%%%r#   N)rZ   r[   r\   __doc__r   r   r	   r   rJ   r   rM   rP   rc   r#   r!   rg   rg      s        8 8t W *1E    ^At AG A A A A&4 & & & & & &r#   rg   )rm   abcr   
contextlibr   pathlibr   typingr   r   r   r	   r
   lightgbm.basicr   lightgbm.callbackr   	ray.trainri   r   ray.tune.utilsr   ray.util.annotationsr   r   rg   rc   r#   r!   <module>r      s^          % % % % % %       8 8 8 8 8 8 8 8 8 8 8 8 8 8 " " " " " " ) ) ) ) ) )                 ' ' ' ' ' ' * * * * * *p. p. p. p. p. p. p. p.f VI& I& I& I& I&. I& I& I& I& I&r#   