
    &`iB                        d dl Z d dl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mZmZ d dlmZmZ erd dlmZ d dlmZ  G d	 d
e          Z ed           G d de                      Ze G d de                      ZdS )    N)ABCMeta)Path)TYPE_CHECKINGAnyDictListOptionalTuple)_atomic_save_load_newest_checkpoint)DeveloperAPI	PublicAPI)Trial)Stopperc                       e Zd ZdZdedee         deeef         def fdZ	e
dededee         deeef         def
d            Ze
dededee         deeef         dd	f
d
            Ze
dededefd            Z xZS )_CallbackMetazA helper metaclass to ensure container classes (e.g. CallbackList) have
    implemented all the callback methods (e.g. `on_*`).
    namebasesattrsreturnc                     t                                          | |||          }|                     ||||          r|                     ||||           |S N)super__new__
need_checkcheck)mcsr   r   r   cls	__class__s        e/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/tune/callback.pyr   z_CallbackMeta.__new__   sU    ggooc466>>#tUE22 	/IIc4...
    r   c                 .    |                     dd          S )NIS_CALLBACK_CONTAINERF)get)r   r   r   r   r   s        r    r   z_CallbackMeta.need_check   s     yy0%888r!   Nc           	      b    t                      }|D ]B}|                     fdt          |                                          D                        C fd|                                D             }|                    |          }|r#t          d| d|j         d|j         d          d S )Nc              3   N   K   | ]\  }}                     ||          |V   d S r   need_override_by_subclass.0	attr_nameattrr   s      r    	<genexpr>z&_CallbackMeta.check.<locals>.<genexpr>)   sQ        #It00DAA     r!   c                 F    h | ]\  }}                     ||          |S  r'   r)   s      r    	<setcomp>z&_CallbackMeta.check.<locals>.<setcomp>.   sC     
 
 
	4,,Y==

 
 
r!   zFound missing callback method: z
 in class .)setupdatevarsitems
difference	TypeError
__module____qualname__)	r   r   r   r   r   methodsbase
overriddenmissings	   `        r    r   z_CallbackMeta.check#   s    %% 	 	DNN    '+Dzz'7'7'9'9      

 
 
 
#(;;==
 
 


 $$Z00 	A' A ANA A-0-=A A A  	 	r!   r+   r,   c                     |                     d          o|                     d           p|dk    ot          |          S )Non_on_trainer_initsetup)
startswithcallable)r   r+   r,   s      r    r(   z'_CallbackMeta.need_override_by_subclass:   sT     $$U++ @!,,->???$ G# tnn	r!   )__name__r8   r9   __doc__strr
   typer   r   r   classmethodboolr   r   r(   __classcell__)r   s   @r    r   r      sL        3 uT{ 4S> d       99!9*/+9>B38n9	9 9 9 [9
 !*/+>B38n	   [, # S T    [    r!   r   beta)	stabilityc                      e Zd ZdZg Z	 	 	 dded         dee         dee         fdZded	ed
         fdZ	ded	ed
         fdZ
ded	ed
         dd
fdZded	ed
         dd
fdZded	ed
         dd
fdZded	ed
         dd
defdZded	ed
         dd
fdZded	ed
         dd
fdZded	ed
         dd
fdZded	ed
         dd
ddfdZd	ed
         fdZdee         fdZdefdZdS )CallbackaS  Tune base callback that can be extended and passed to a ``TrialRunner``

    Tune callbacks are called from within the ``TrialRunner`` class. There are
    several hooks that can be used, all of which are found in the submethod
    definitions of this base class.

    The parameters passed to the ``**info`` dict vary between hooks. The
    parameters passed are described in the docstrings of the methods.

    This example will print a metric each time a result is received:

    .. testcode::

        from ray import tune
        from ray.tune import Callback


        class MyCallback(Callback):
            def on_trial_result(self, iteration, trials, trial, result,
                                **info):
                print(f"Got result: {result['metric']}")


        def train_func(config):
            for i in range(10):
                tune.report(metric=i)

        tuner = tune.Tuner(
            train_func,
            run_config=tune.RunConfig(
                callbacks=[MyCallback()]
            )
        )
        tuner.fit()

    .. testoutput::
        :hide:

        ...
    Nstopr   num_samplestotal_num_samplesc                     dS )a  Called once at the very beginning of training.

        Any Callback setup should be added here (setting environment
        variables, etc.)

        Arguments:
            stop: Stopping criteria.
                If ``time_budget_s`` was passed to ``tune.RunConfig``, a
                ``TimeoutStopper`` will be passed here, either by itself
                or as a part of a ``CombinedStopper``.
            num_samples: Number of times to sample from the
                hyperparameter space. Defaults to 1. If `grid_search` is
                provided as an argument, the grid will be repeated
                `num_samples` of times. If this is -1, (virtually) infinite
                samples are generated until a stopping condition is met.
            total_num_samples: Total number of samples factoring
                in grid search samplers.
            **info: Kwargs dict for forward compatibility.
        Nr/   )selfrO   rP   rQ   infos        r    rA   zCallback.setupv   s	    4 	r!   	iterationtrialsr   c                     dS )zCalled at the start of each tuning loop step.

        Arguments:
            iteration: Number of iterations of the tuning loop.
            trials: List of trials.
            **info: Kwargs dict for forward compatibility.
        Nr/   rS   rU   rV   rT   s       r    on_step_beginzCallback.on_step_begin   s	     	r!   c                     dS )a/  Called at the end of each tuning loop step.

        The iteration counter is increased before this hook is called.

        Arguments:
            iteration: Number of iterations of the tuning loop.
            trials: List of trials.
            **info: Kwargs dict for forward compatibility.
        Nr/   rX   s       r    on_step_endzCallback.on_step_end   s	     	r!   trialc                     dS )a  Called after starting a trial instance.

        Arguments:
            iteration: Number of iterations of the tuning loop.
            trials: List of trials.
            trial: Trial that just has been started.
            **info: Kwargs dict for forward compatibility.

        Nr/   rS   rU   rV   r\   rT   s        r    on_trial_startzCallback.on_trial_start   s	     	r!   c                     dS )a  Called after restoring a trial instance.

        Arguments:
            iteration: Number of iterations of the tuning loop.
            trials: List of trials.
            trial: Trial that just has been restored.
            **info: Kwargs dict for forward compatibility.
        Nr/   r^   s        r    on_trial_restorezCallback.on_trial_restore   	     	r!   c                     dS )a$  Called after receiving a checkpoint from a trial.

        Arguments:
            iteration: Number of iterations of the tuning loop.
            trials: List of trials.
            trial: Trial that just saved a checkpoint.
            **info: Kwargs dict for forward compatibility.
        Nr/   r^   s        r    on_trial_savezCallback.on_trial_save   rb   r!   resultc                     dS )a  Called after receiving a result from a trial.

        The search algorithm and scheduler are notified before this
        hook is called.

        Arguments:
            iteration: Number of iterations of the tuning loop.
            trials: List of trials.
            trial: Trial that just sent a result.
            result: Result that the trial sent.
            **info: Kwargs dict for forward compatibility.
        Nr/   )rS   rU   rV   r\   re   rT   s         r    on_trial_resultzCallback.on_trial_result   s	    ( 	r!   c                     dS )ax  Called after a trial instance completed.

        The search algorithm and scheduler are notified before this
        hook is called.

        Arguments:
            iteration: Number of iterations of the tuning loop.
            trials: List of trials.
            trial: Trial that just has been completed.
            **info: Kwargs dict for forward compatibility.
        Nr/   r^   s        r    on_trial_completezCallback.on_trial_complete   	     	r!   c                     dS )a  Called after a trial instance failed (errored) but the trial is scheduled
        for retry.

        The search algorithm and scheduler are not notified.

        Arguments:
            iteration: Number of iterations of the tuning loop.
            trials: List of trials.
            trial: Trial that just has errored.
            **info: Kwargs dict for forward compatibility.
        Nr/   r^   s        r    on_trial_recoverzCallback.on_trial_recover   rj   r!   c                     dS )ax  Called after a trial instance failed (errored).

        The search algorithm and scheduler are notified before this
        hook is called.

        Arguments:
            iteration: Number of iterations of the tuning loop.
            trials: List of trials.
            trial: Trial that just has errored.
            **info: Kwargs dict for forward compatibility.
        Nr/   r^   s        r    on_trial_errorzCallback.on_trial_error  rj   r!   
checkpointzray.tune.Checkpointc                     dS )az  Called after a trial saved a checkpoint with Tune.

        Arguments:
            iteration: Number of iterations of the tuning loop.
            trials: List of trials.
            trial: Trial that just has errored.
            checkpoint: Checkpoint object that has been saved
                by the trial.
            **info: Kwargs dict for forward compatibility.
        Nr/   )rS   rU   rV   r\   ro   rT   s         r    on_checkpointzCallback.on_checkpoint  s	    $ 	r!   c                     dS )zCalled after experiment is over and all trials have concluded.

        Arguments:
            trials: List of trials.
            **info: Kwargs dict for forward compatibility.
        Nr/   )rS   rV   rT   s      r    on_experiment_endzCallback.on_experiment_end*  s	     	r!   r   c                     dS )a1  Get the state of the callback.

        This method should be implemented by subclasses to return a dictionary
        representation of the object's current state.

        This is called automatically by Tune to periodically checkpoint callback state.
        Upon :ref:`Tune experiment restoration <tune-experiment-level-fault-tolerance>`,
        callback state will be restored via :meth:`~ray.tune.Callback.set_state`.

        .. testcode::

            from typing import Dict, List, Optional

            from ray.tune import Callback
            from ray.tune.experiment import Trial

            class MyCallback(Callback):
                def __init__(self):
                    self._trial_ids = set()

                def on_trial_start(
                    self, iteration: int, trials: List["Trial"], trial: "Trial", **info
                ):
                    self._trial_ids.add(trial.trial_id)

                def get_state(self) -> Optional[Dict]:
                    return {"trial_ids": self._trial_ids.copy()}

                def set_state(self, state: Dict) -> Optional[Dict]:
                    self._trial_ids = state["trial_ids"]

        Returns:
            dict: State of the callback. Should be `None` if the callback does not
            have any state to save (this is the default).
        Nr/   rS   s    r    	get_statezCallback.get_state3  s
    H tr!   statec                     dS )a  Set the state of the callback.

        This method should be implemented by subclasses to restore the callback's
        state based on the given dict state.

        This is used automatically by Tune to restore checkpoint callback state
        on :ref:`Tune experiment restoration <tune-experiment-level-fault-tolerance>`.

        See :meth:`~ray.tune.Callback.get_state` for an example implementation.

        Args:
            state: State of the callback.
        Nr/   )rS   rw   s     r    	set_statezCallback.set_stateY  rj   r!   )NNN)rD   r8   r9   rE   _SAVED_FILE_TEMPLATESr	   intrA   r   rY   r[   r_   ra   rd   r   rg   ri   rl   rn   rq   rs   rv   ry   r/   r!   r    rN   rN   E   s       ' 'X 
 %)%)+/	 y! c] $C=	   8s DM    
S 
$w- 
 
 
 
&*7m<C   &*7m<C   &*7m<C    W 	
    ,&*7m<C    &*7m<C    &*7m<C     W 	
 *   (W    $8D> $ $ $ $Lt      r!   rN   )	metaclassc                       e Zd ZdZdZdZdee         f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ee         fdZdefdZd!dedefdZdefdZdedefdZdefdZdeddfdZ d S )"CallbackListz Call multiple callbacks at once.Tzcallback-states-{}.pkl	callbacksc                     || _         d S r   
_callbacks)rS   r   s     r    __init__zCallbackList.__init__q  s    #r!   c                     | j         D ]r}	  |j        di | # t          $ rU}dt          |          v r8t	          j        d|j         dt                     |                                 n|Y d }~kd }~ww xY wd S )Nargumentz*Please update `setup` method in callback `z@` to match the method signature in `ray.tune.callback.Callback`.r/   )r   rA   r7   rF   warningswarnr   FutureWarning)rS   rT   callbackes       r    rA   zCallbackList.setupt  s     	 	H&&&&&& 
 
 
Q''M<$.< < < &	   NN$$$$G %$$$$
	 	s   
A8AA33A8c                 4    | j         D ]} |j        di | d S Nr/   )r   rY   rS   rT   r   s      r    rY   zCallbackList.on_step_begin  9     	+ 	+H"H"**T****	+ 	+r!   c                 4    | j         D ]} |j        di | d S r   )r   r[   r   s      r    r[   zCallbackList.on_step_end  s9     	) 	)H H ((4((((	) 	)r!   c                 4    | j         D ]} |j        di | d S r   )r   r_   r   s      r    r_   zCallbackList.on_trial_start  9     	, 	,H#H#++d++++	, 	,r!   c                 4    | j         D ]} |j        di | d S r   )r   ra   r   s      r    ra   zCallbackList.on_trial_restore  9     	. 	.H%H%------	. 	.r!   c                 4    | j         D ]} |j        di | d S r   )r   rd   r   s      r    rd   zCallbackList.on_trial_save  r   r!   c                 4    | j         D ]} |j        di | d S r   )r   rg   r   s      r    rg   zCallbackList.on_trial_result  s9     	- 	-H$H$,,t,,,,	- 	-r!   c                 4    | j         D ]} |j        di | d S r   )r   ri   r   s      r    ri   zCallbackList.on_trial_complete  9     	/ 	/H&H&......	/ 	/r!   c                 4    | j         D ]} |j        di | d S r   )r   rl   r   s      r    rl   zCallbackList.on_trial_recover  r   r!   c                 4    | j         D ]} |j        di | d S r   )r   rn   r   s      r    rn   zCallbackList.on_trial_error  r   r!   c                 4    | j         D ]} |j        di | d S r   )r   rq   r   s      r    rq   zCallbackList.on_checkpoint  r   r!   c                 4    | j         D ]} |j        di | d S r   )r   rs   r   s      r    rs   zCallbackList.on_experiment_end  r   r!   r   c                     i }d}t          | j                  D ]"\  }}|                                }|rd}|||<   #|sdS |S )zGets the state of all callbacks contained within this list.
        If there are no stateful callbacks, then None will be returned in order
        to avoid saving an unnecessary callback checkpoint file.FTN)	enumerater   rv   )rS   rw   any_stateful_callbacksir   callback_states         r    rv   zCallbackList.get_state  sh     !&$T_55 	& 	&KAx%//11N .)-&%E!HH% 	4r!   rw   c                     t          | j                  D ]2\  }}|                    |d          }|r|                    |           3dS )zSets the state for all callbacks contained within this list.
        Skips setting state for all stateless callbacks where `get_state`
        returned None.N)r   r   r$   ry   )rS   rw   r   r   r   s        r    ry   zCallbackList.set_state  s[     %T_55 	3 	3KAx"YYq$//N 3"">222	3 	3r!   defaultcheckpoint_dirsession_strc                     |                                  }|r4| j                            |          }d| }t          ||||           dS dS )zSave the state of the callback list to the checkpoint_dir.

        Args:
            checkpoint_dir: directory where the checkpoint is stored.
            session_str: Unique identifier of the current run session (ex: timestamp).
        z.tmp-)rw   r   	file_nametmp_file_nameN)rv   CKPT_FILE_TMPLformatr   )rS   r   r   
state_dictr   r   s         r    save_to_dirzCallbackList.save_to_dir  su     ^^%%
 	+22;??I/I//M -#+	     	 	r!   c                     t          || j                            d                    }|s"t          d                    |                    |                     |           dS )a  Restore the state of the list of callbacks from the checkpoint_dir.

        You should check if it's possible to restore with `can_restore`
        before calling this method.

        Args:
            checkpoint_dir: directory where the checkpoint is stored.

        Raises:
            RuntimeError: if unable to find checkpoint.
            NotImplementedError: if the `set_state` method is not implemented.
        *z Unable to find checkpoint in {}.N)r   r   r   RuntimeErrorry   )rS   r   r   s      r    restore_from_dirzCallbackList.restore_from_dir  sp     -D/66s;;
 

  	299.II   	z"""""r!   c           
          t          t          j        t          || j                            d                                                                        S )zCheck if the checkpoint_dir contains the saved state for this callback list.

        Returns:
            can_restore: True if the checkpoint_dir contains a file of the
                format `CKPT_FILE_TMPL`. False otherwise.
        r   )anyglobiglobr   r   r   as_posix)rS   r   s     r    can_restorezCallbackList.can_restore  sJ     JtND,?,F,Fs,K,KLLUUWWXX
 
 	
r!   c                 *    t          | j                  S r   )lenr   ru   s    r    __len__zCallbackList.__len__  s    4?###r!   r   rN   c                     | j         |         S r   r   )rS   r   s     r    __getitem__zCallbackList.__getitem__  s    q!!r!   N)r   )!rD   r8   r9   rE   r#   r   r   rN   r   rA   rY   r[   r_   ra   rd   rg   ri   rl   rn   rq   rs   r	   r   rv   ry   rF   r   r   rI   r   r{   r   r   r/   r!   r    r~   r~   j  s       ** -N$$x. $ $ $ $   + + +) ) ), , ,. . .+ + +- - -/ / /. . ., , ,+ + +/ / /8D>    3t 3 3 3 3 # C    &#s # # # #,	
# 	
$ 	
 	
 	
 	
$ $ $ $ $"S "Z " " " " " "r!   r~   )r   r   abcr   pathlibr   typingr   r   r   r   r	   r
   ray.tunerayray.tune.utils.utilr   r   ray.util.annotationsr   r   ray.tune.experimentr   ray.tune.stopperr   r   rN   r~   r/   r!   r    <module>r      s                 B B B B B B B B B B B B B B B B  E E E E E E E E 8 8 8 8 8 8 8 8 )))))))((((((2 2 2 2 2G 2 2 2j Va a a a a a a a aH	 U" U" U" U" U"8 U" U" U" U" U"r!   