
    &`ik                        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mZ d dlZd dlmZ d dlmZ d dlmZmZ d dlm Z m!Z!m"Z" d d	l#m$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/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z< d dl=m>Z> d dl?m@Z@ d dlAmBZB d dlCmDZDmEZE erd dlFmGZG  ejH        eI          ZJdZKdZLeE G d d                      ZMdS )    N)redirect_stderrredirect_stdout)datetime)Path)TYPE_CHECKINGAnyCallableDictListOptionalUnion)try_to_create_directory)exception_causeskip_exceptions)TIME_THIS_ITER_S	TIMESTAMPTRAINING_ITERATION)_TrainingResult)StorageContext_exists_at_fs_path)DEFAULT_STORAGE_PATH)PlacementGroupFactory)DEBUG_METRICSDONEEPISODES_THIS_ITEREPISODES_TOTALHOSTNAMENODE_IPPIDRESULT_DUPLICATESHOULD_CHECKPOINTSTDERR_FILESTDOUT_FILETIME_TOTAL_STIMESTEPS_THIS_ITERTIMESTEPS_TOTALTRIAL_ID
TRIAL_INFO)UtilMonitor)disable_ipython)Tee)DeveloperAPI	PublicAPI)Logger
   z_dict_checkpoint.pklc                   z   e Zd ZdZ	 	 	 d;deeef         deeeef         gdf         dee	         fdZ
edeeef         dee         fd	            Zedefd
            Zd Z	 	 	 	 d<dee         dee         dee         dedef
dZd Zd=dedefdZd Zd Zdedeeef         defdZed>dee         defd            Zedeedef         fd            Z	 d>d ee e         ef         d!ee         fd"Z!d?d#Z"d$edefd%Z#	 d>deeef         deeeef         gdf         fd&Z$d' Z%d( Z&d) Z'e(d*             Z)e(d+             Z*e(d,             Z+e(dee         fd-            Z,e(d.             Z-e(d/             Z.d0 Z/d1 Z0dedee         fd2Z1d3ee         fd4Z2defd5Z3d6efd7Z4d8 Z5d e e         d!efd9Z6d: Z7dS )@	Trainablea  Abstract class for trainable models, functions, etc.

    A call to ``train()`` on a trainable will execute one logical iteration of
    training. As a rule of thumb, the execution time of one train call should
    be large enough to avoid overheads (i.e. more than a few seconds), but
    short enough to report progress periodically (i.e. at most a few minutes).

    Calling ``save()`` should save the training state of a trainable to disk,
    and ``restore(path)`` should restore a trainable to the given state.

    Generally you only need to implement ``setup``, ``step``,
    ``save_checkpoint``, and ``load_checkpoint`` when subclassing Trainable.

    Other implementation methods that may be helpful to override are
    ``log_result``, ``reset_config``, ``cleanup``, and ``_export_model``.

    Tune will convert this class into a Ray actor, which runs on a separate process.
    By default, Tune will also change the current working directory of this process to
    its corresponding trial-level log directory ``self.logdir``.
    This is designed so that different trials that run on the same physical node won't
    accidentally write to the same location and overstep each other.

    The behavior of changing the working directory can be disabled by setting the
    `RAY_CHDIR_TO_TRIAL_DIR=0` environment variable. This allows access to files
    in the original working directory, but relative paths should be used for read only
    purposes, and you must make sure that the directory is synced on all nodes if
    running on multiple machines.

    The `TUNE_ORIG_WORKING_DIR` environment variable was the original workaround for
    accessing paths relative to the original working directory. This environment
    variable is deprecated, and the `RAY_CHDIR_TO_TRIAL_DIR` environment variable
    described above should be used instead.

    This class supports checkpointing to and restoring from remote storage.
    Nconfiglogger_creatorr.   storagec                    |pi | _         | j                             t          d          }|                                 rt	                       dx| _        | _        |                     | j         |           dx| _        x| _	        | _
        dx| _        x| _        | _        d| _        | j                             t          d          }| j                             t           d          }d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        || _        || _        || _        t;          j                    | _        t>          j         !                                | _"        || _#        |r&|j$        sJ tJ          &                    d|            | '                    ||           | (                    tS          j*        | j                              t;          j                    | j        z
  }|tV          k    r-tJ          ,                    d-                    |                     | j         .                    dd          }t_          |          | _0        dS )	at  Initialize a Trainable.

        Sets up logging and points ``self.logdir`` to a directory in which
        training outputs should be placed.

        Subclasses should prefer defining ``setup()`` instead of overriding
        ``__init__()`` directly.

        Args:
            config: Trainable-specific configuration data. By default
                will be saved as ``self.config``.
            logger_creator: (Deprecated) Function that creates a ray.tune.Logger
                object. If unspecified, a default logger is created.
            storage: StorageContext object that contains persistent storage paths
        Nr           Fz!StorageContext on the TRAINABLE:
zTrainable.setup took {:.3f} seconds. If your trainable is slow to initialize, consider setting reuse_actors=True to reduce actor creation overheads.log_sys_usage)start)1r2   popr(   is_actorr*   _result_logger_logdir_create_logger_stdout_context
_stdout_fp_stdout_stream_stderr_context
_stderr_fp_stderr_stream_stderr_logging_handlerr#   r"   
_iteration_time_total_timesteps_total_episodes_total_time_since_restore_timesteps_since_restore_iterations_since_restore_last_result	_restored_trial_info_stdout_file_stderr_filetime_start_timerayutilget_node_ip_address	_local_ip_storagetrial_fs_pathloggerdebug_open_logfilessetupcopydeepcopySETUP_TIME_THRESHOLDinfoformatgetr)   _monitor)	selfr2   r3   r4   
trial_infostdout_filestderr_file
setup_timer7   s	            p/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/tune/trainable/trainable.py__init__zTrainable.__init___   s.   , l[__Z66
==?? 	 .21dlDK888GKKKt1DGKKKt1D'+$kook488kook488 $##& ()%)*& %''9;;5577 	I((((LLGgGGHHHK555

4=--...Y[[4#33
,,,KK $VJ//	   ??#-888    returnc                     dS )aK  Provides a static resource requirement for the given configuration.

        This can be overridden by sub-classes to set the correct trial resource
        allocation, so the user does not need to.

        .. testcode::

            @classmethod
            def default_resource_request(cls, config):
                return PlacementGroupFactory([{"CPU": 1}, {"CPU": 1}])


        Args:
            config[Dict[str, Any]]: The Trainable's config dict.

        Returns:
            PlacementGroupFactory: A PlacementGroupFactory consumed by Tune
                for queueing.
        N clsr2   s     ri   default_resource_requestz"Trainable.default_resource_request   s	    . trk   c                     dS )zReturns a help string for configuring this trainable's resources.

        Args:
            config: The Trainer's config dict.
         rn   ro   s     ri   resource_helpzTrainable.resource_help   s	     rrk   c                 6    | j         t          j                    fS N)rV   osgetpidrd   s    ri   get_current_ip_pidzTrainable.get_current_ip_pid   s    ~ry{{**rk   Fnowtime_this_iter	timestampdebug_metrics_onlyc                    |t          j                    }t          | j        d|                    d          d|r|n2t          t          j        |                                                    t          |t          | j        t          t          j                    t          t!          j                    t$          | j        d| j        d| j        d| j        i}| j        r
| j        |d<   |rd	 |                                D             }|S )
zReturn a dict with metrics auto-filled by the trainable.

        If ``debug_metrics_only`` is True, only metrics that don't
        require at least one iteration will be returned
        (``ray.tune.result.DEBUG_METRICS``).
        Ndate%Y-%m-%d_%H-%M-%Sr}   r2   time_since_restoreiterations_since_restoretimesteps_since_restorec                 ,    i | ]\  }}|t           v ||S rn   )r   ).0kvs      ri   
<dictcomp>z5Trainable.get_auto_filled_metrics.<locals>.<dictcomp>   s(    TTT41amASAS!QASASASrk   )r   todayr'   trial_idstrftimeintrQ   mktime	timetupler   r$   rF   r   rw   rx   r   platformnoder   rV   r2   rI   rK   rJ   items)rd   r{   r|   r}   r~   
autofilleds         ri   get_auto_filled_metricsz!Trainable.get_auto_filled_metrics   s     ;.""CdmCLL!455iVSS]]__9U9U5V5Vn$*hmooT^dk $":&(F

 ( 	R484QJ01 	UTT:+;+;+=+=TTTJrk   c                     	 t           j        j        j        j        }||                                k    S # t          $ r Y dS w xY w)NF)rS   _privateworkerglobal_workeractor_idnil	Exception)rd   r   s     ri   r:   zTrainable.is_actor   sL    	|*8AHx||~~-- 	 	 	55	s   25 
AA  buffer_time_smax_buffer_lengthc                    g }t          j                     }||z   }||k     s|s|                                 }|                    |           |                    t          d          rnf|                    t
          d          rnJ|                    t                    rn/t          |          |k    rnt          j                     }||k     ||S )a  Runs multiple iterations of training.

        Calls ``train()`` internally. Collects and combines multiple results.
        This function will run ``self.train()`` repeatedly until one of
        the following conditions is met: 1) the maximum buffer length is
        reached, 2) the maximum buffer time is reached, or 3) a checkpoint
        was created. Even if the maximum time is reached, it will always
        block until at least one result is received.

        Args:
            buffer_time_s: Maximum time to buffer. The next result
                received after this amount of time has passed will return
                the whole buffer.
            max_buffer_length: Maximum number of results to buffer.

        F)rQ   trainappendrb   r   r!   r    len)rd   r   r   resultsr{   send_buffer_atresults          ri   train_bufferedzTrainable.train_buffered   s    " ikk},N""'"ZZ\\FNN6"""zz$&& -u55 ,-- W!222)++C N""'"" rk   c                    t          j                     }	 |                                 }n1# t          $ r$}t          |          }|t	          |          d}~ww xY wt          |t                    s
J d            t          |v r|S |                                }| xj	        dz  c_	        | xj
        dz  c_
        |                    t                    |t                   }nt          j                     |z
  }| xj        |z  c_        | xj        |z  c_        |                    t          d          }|                    t"          d           |                    t$                    D| j        d| _        | xj        |t$                   z  c_        | xj        |t$                   z  c_        |                    t*                    )| j        d| _        | xj        |t*                   z  c_        | j         |                    t.          | j                   | j         |                    t0          | j                   |                    t2          | j	                   t5          j                    }|                    |                     |||                     | j                                        }|r|                    |           |                      |           | j!        r| j"        #                                 | j$        r| j%        #                                 || _&        | j'        r| j'        (                                 |S )a  Runs one logical iteration of training.

        Calls ``step()`` internally. Subclasses should override ``step()``
        instead to return results.
        This method automatically fills the following fields in the result:

            `done` (bool): training is terminated. Filled only if not provided.

            `time_this_iter_s` (float): Time in seconds this iteration
            took to run. This may be overridden in order to override the
            system-computed time difference.

            `time_total_s` (float): Accumulated time in seconds for this
            entire experiment.

            `training_iteration` (int): The index of this
            training iteration, e.g. call to train(). This is incremented
            after `step()` is called.

            `pid` (str): The pid of the training process.

            `date` (str): A formatted date of when the result was processed.

            `timestamp` (str): A UNIX timestamp of when the result
            was processed. This may be overridden.

            `hostname` (str): Hostname of the machine hosting the training
            process.

            `node_ip` (str): Node ip of the machine hosting the training
            process.

        Returns:
            A dict that describes training progress.
        Nzstep() needs to return a dict.   Fr   )r{   r|   r}   ))rQ   stepr   r   r   
isinstancedictr    r]   rE   rK   rb   r   rF   rI   r   
setdefaultr   r%   rG   rJ   r   rH   r&   r   r   r   r   updater   rc   get_data
log_resultr>   r@   flushrA   rC   rL   rW   persist_artifacts)	rd   r8   r   eskippedr|   result_timestampr{   monitor_datas	            ri   r   zTrainable.train"  s.   H 		8YY[[FF 	8 	8 	8%a((Gw777	8 &$''II)III' v%%M1&&!+&&::&''3#$45NN!Y[[50NN*  N2  !::i66$&&& ::)**6$,()%!!V,?%@@!!))V4G-HH)) ::())5#+'($  F+=$>>    ,ot/DEEE+nd.BCCC,do>>>n((BR )  	
 	
 	
 }--// 	(MM,''' 	(%%''' 	(%%'''"= 	.M++---s   * 
AAAc                 Z    | j         | j        | j        | j        | j        t
          j        dS )N)	iterationtimesteps_total
time_totalepisodes_totallast_resultray_version)rE   rG   rF   rH   rL   rS   __version__ry   s    ri   	get_statezTrainable.get_state  s3    #4*"2,?
 
 	
rk   checkpoint_dircheckpoint_dict_or_pathc                    t          |t                    rVt          |t                                        d          5 }t          j        ||           ddd           n# 1 swxY w Y   n0t          |t                    r||k    rt          d| d|           t          j
        j                            |          }| j        r| j                                        ni }| j        rp| j                            |           | j                            |          }t%          ||          }| j                            | j        j        j                   nt%          ||          }|S )a  Report a checkpoint saved via Trainable.save_checkpoint.

        Need to handle both dict or path checkpoint returned by the user's
        `save_checkpoint` method.

        This is to get class trainables to work with storage backend used by
        function trainables.
        This basically re-implements `tune.report` for class trainables,
        making sure to persist the checkpoint to storage.
        wbNzoThe returned checkpoint path from `save_checkpoint` must be None or the same as the provided path argument.Got z != 
checkpointmetrics)force)r   r   r   _DICT_CHECKPOINT_FILE_NAMEopen
ray_pickledumpstr
ValueErrorrS   tune
Checkpointfrom_directoryrL   r]   rW   _update_checkpoint_indexpersist_current_checkpointr   r   sync_configsync_artifacts_on_checkpoint)rd   r   r   flocal_checkpointr   persisted_checkpointcheckpoint_results           ri   "_report_class_trainable_checkpointz,Trainable._report_class_trainable_checkpoint  s    -t44 		n&@AAFFtLL <PQ 7;;;< < < < < < < < < < < < < < </55 	&.88 I2I I8FI I   8.==nMM.2.?G$#((***R= 	 M227;;;#'=#K#K $ $  !0/! ! ! M++m/L ,     !0+W! ! ! ! s   A  A$'A$c                    t          | t          j        j        j                  sy| }|pt          j                    }t          j        |d           | 	                    |          }| 
                    ||          }|r| j        rt          j        |d           nT| 	                    d          }t          |t                    sJ | j        sJ |j                            | j                   |S )ar  Saves the current model state to a checkpoint.

        Subclasses should override ``save_checkpoint()`` instead to save state.

        Args:
            checkpoint_dir: Optional dir to place the checkpoint.

        Returns:
            The given or created checkpoint directory.

        Note the return value matches up with what is expected of `restore()`.
        T)exist_ok)ignore_errorsN)r   rS   r   	trainableFunctionTrainabletempfilemkdtemprw   makedirssave_checkpointr   rW   shutilrmtreer   rL   r   r   )rd   r   use_temp_dirr   r   s        ri   savezTrainable.save  s    $ 2 DEE 	@--L+Ax/?/A/ANK6666&*&:&:>&J&J# $ G G 7! !  B BnDAAAA151E1Ed1K1K/AAAAA$$$$%,,T->???  rk   checkpoint_pathzray.tune.Checkpointc                 @   t          |t                    r$t          j        j                            |          }t          |t          j        j                  rt          |i           }n|}t          |t                    sJ t          |                      |j        }|j	        }|
                    t          d          | _        |
                    t          d          | _        d| _        d| _        |
                    t"                    | _        d| _        |
                    t(                    | _        t-          |j        |j                  s$t3          d|j        j         d|j                   t          | t          j        j        j                  s|                                5 }t=          |          }|t>          z  }|                                 rRtC          |d          5 }tE          j#        |          }ddd           n# 1 swxY w Y   | $                    |           n| $                    |           ddd           n# 1 swxY w Y   n| $                    |           d| _%        tL          '                    d	| j(         d
|            dS )a  Restores training state from a given model checkpoint.

        These checkpoints are returned from calls to save().

        Subclasses should override ``load_checkpoint()`` instead to
        restore state.
        This method restores additional metadata saved with the checkpoint.

        `checkpoint_path` should match with the return from ``save()``.

        Args:
            checkpoint_path: training result that was returned by a
                previous call to `save()`.
        r   r   r6   z`Could not recover from checkpoint as it does not exist on storage anymore. Got storage fs type `z` and path: rbNTzRestored on z from checkpoint: ))r   r   rS   r   r   r   r   typer   r   rb   r   rE   r$   rF   rI   rK   r&   rG   rJ   r   rH   r   
filesystempathr   	type_namer   r   as_directoryr   r   existsr   r   loadload_checkpointrM   rY   r`   rV   )	rd   r   r   r   checkpoint_metricsr   dict_checkpoint_filer   checkpoint_dicts	            ri   restorezTrainable.restore  s   * os++ 	R!h1@@QQOosx':;; 	A /?TV W W W1@+_==VVtDU?V?VVV=&1
.6,001CQGG-11,BB#& )*& !3 6 6 G G()%155nEE!*"7II 	+(2(=(G+ + $+ +   $ 2 DEE 	4 ((** 	9n"&~"6"6'69S'S$'..00 92D99 =Q*4/!*<*<= = = = = = = = = = = = = = =((9999((888	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9   !2333Q4>QQZQQRRRRRs6   0>I.HIH	IH	.IIIexport_formats
export_dirc                 p    t          |t                    r|g}|p| j        }|                     ||          S )a  Exports model based on export_formats.

        Subclasses should override _export_model() to actually
        export model to local directory.

        Args:
            export_formats: Format or list of (str) formats
                that should be exported.
            export_dir: Optional dir to place the exported model.
                Defaults to self.logdir.

        Returns:
            A dict that maps ExportFormats to successfully exported models.
        )r   r   logdir_export_modelrd   r   r   s      ri   export_modelzTrainable.export_modelD  s@    " nc** 	.,-N.4;
!!.*===rk   c                    || _         || _        |                    t          d          }|r|| _        | j                                         | j                                         |rCt          	                    d           | 
                    |                                |           nt          	                    d| d           |                    t          d          }|                    t          d          }|                                  |                     ||           |                     |          }|sdS d| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _        dS )	zResets trial for use with new config.

        Subclasses should override reset_config() to actually
        reset actor behavior for the new config.NzLogger reset.z:Did not reset logger. Got: trainable.reset(logger_creator=z).Fr   r6   T)r2   rW   r9   r(   rN   r;   r   closerY   rZ   r=   r]   r#   r"   _close_logfilesr[   reset_configrE   rF   rG   rH   rI   rJ   rK   rM   )rd   
new_configr3   r4   re   rf   rg   successs           ri   resetzTrainable.resetZ  s   
 !^^J55
 	*)D!!###!!### 	LL)))
 1 1>BBBBLLE2@E E E  
 !nn[$77 nn[$77K555##J// 	5  $##& ()%)*&trk   r   c                     dS )a  Resets configuration without restarting the trial.

        This method is optional, but can be implemented to speed up algorithms
        such as PBT, and to allow performance optimizations such as running
        experiments with reuse_actors=True.

        Args:
            new_config: Updated hyperparameter configuration
                for the trainable.

        Returns:
            True if reset was successful else False.
        Frn   )rd   r   s     ri   r   zTrainable.reset_config  s	     urk   c                 @   |r# ||          | _         | j         j        | _        dS ddlm} t          j                                        d          }t          t                     t          j        |t                    | _         ||| j        d          | _         dS )zCreate logger from logger creator.

        Sets _logdir and _result_logger.

        `_logdir` is the **per trial** directory for the Trainable.
        r   )UnifiedLoggerr   )prefixdirN)loggers)r;   r   r<   ray.tune.loggerr  r   r   r   r   r   r   r   )rd   r2   r3   r  logdir_prefixs        ri   r=   zTrainable._create_logger  s      	T"0."8"8D.5DLLL555555$N,,556IJJM#$8999#+$*>  DL #0-d"S"S"SDrk   c                    |rt          | j                  |z                                                                  }t	          |d          | _        t          t          j        | j                  | _	        t          | j	                  | _        | j                                         |rt          | j                  |z                                                                  }t	          |d          | _        t          t          j        | j                  | _        t!          | j                  | _        | j                                         t%          j        d          }t%          j        | j                  | _        | j                            |           t.          j                            | j                   dS dS )z0Create loggers. Open stdout and stderr logfiles.za+zA[%(levelname)s %(asctime)s] %(filename)s: %(lineno)d  %(message)sN)r   r<   
expanduseras_posixr   r?   r+   sysstdoutr@   r   r>   	__enter__rB   stderrrC   r   rA   logging	FormatterStreamHandlerrD   setFormatterrS   rY   
addHandler)rd   rf   rg   stdout_pathstderr_path	formatters         ri   r[   zTrainable._open_logfiles  s{    	---;GGIIRRTTK";55DO"%cj$/"B"BD#243F#G#GD  **,,, 	@--;GGIIRRTTK";55DO"%cj$/"B"BD#243F#G#GD  **,,,  ) I
 ,3+@+Q+QD((55i@@@J!!$">?????	@ 	@rk   c                    | j         r$t          j                            | j                    | j        rU| j                                         | j                            ddd           | j        	                                 d| _        | j
        rW| j                                         | j
                            ddd           | j        	                                 d| _
        dS dS )z!Close stdout and stderr logfiles.N)rD   rS   rY   removeHandlerr>   r@   r   __exit__r?   r   rA   rC   rB   ry   s    ri   r   zTrainable._close_logfiles  s    ' 	CJ$$T%ABBB 	(%%''' ))$d;;;O!!####'D  	(%%''' ))$d;;;O!!####'D   		( 	(rk   c                 P   | j                                          | j                                          | j                                        r2| j                                         | j                                         |                                  |                                  dS )zReleases all resources used by this trainable.

        Calls ``Trainable.cleanup`` internally. Subclasses should override
        ``Trainable.cleanup`` for custom cleanup procedures.
        N)	r;   r   r   rc   is_alivestopjoincleanupr   ry   s    ri   r  zTrainable.stop  s     	!!###!!###=!!## 	!M   M   rk   c                     | j         S )zDirectory of the results and checkpoints for this Trainable.

        Note that the current working directory will also be changed to this.
        )r<   ry   s    ri   r   zTrainable.logdir  s     |rk   c                 ,    | j         r| j         j        S dS )zTrial name for the corresponding trial of this Trainable.

        This is not set if not using Tune.

        .. testcode::

            from ray.tune import Trainable

            name = Trainable().trial_name
        default)rN   
trial_namery   s    ri   r%  zTrainable.trial_name  s       	#..9rk   c                 ,    | j         r| j         j        S dS )zTrial ID for the corresponding trial of this Trainable.

        This is not set if not using Tune.

        .. testcode::

            from ray.tune import Trainable

            trial_id = Trainable().trial_id
        r$  )rN   r   ry   s    ri   r   zTrainable.trial_id  s       	#,,9rk   c                 ,    | j         r| j         j        S dS )zResources currently assigned to the trial of this Trainable.

        This is not set if not using Tune.

        .. testcode::

            from ray.tune import Trainable

            trial_resources = Trainable().trial_resources
        N)rN   trial_resourcesry   s    ri   r(  zTrainable.trial_resources  s       	#334rk   c                     | j         S )zCurrent training iteration.

        This value is automatically incremented every time `train()` is called
        and is automatically inserted into the training result dict.

        rE   ry   s    ri   r   zTrainable.iteration&       rk   c                     | j         S )zCurrent training iteration (same as `self.iteration`).

        This value is automatically incremented every time `train()` is called
        and is automatically inserted into the training result dict.

        r*  ry   s    ri   training_iterationzTrainable.training_iteration0  r+  rk   c                     | j         S )z(Returns configuration passed in by Tune.)r2   ry   s    ri   
get_configzTrainable.get_config:  s
    {rk   c                     t           )a  Subclasses should override this to implement train().

        The return value will be automatically passed to the loggers. Users
        can also return `tune.result.DONE` or `tune.result.SHOULD_CHECKPOINT`
        as a key to manually trigger termination or checkpointing of this
        trial. Note that manual checkpointing only works when subclassing
        Trainables.

        .. versionadded:: 0.8.7

        Returns:
            A dict that describes training progress.

        NotImplementedErrorry   s    ri   r   zTrainable.step>  s
     "!rk   c                     t           )a  Subclasses should override this to implement ``save()``.

        Warning:
            Do not rely on absolute paths in the implementation of
            ``Trainable.save_checkpoint`` and ``Trainable.load_checkpoint``.

        Use ``validate_save_restore`` to catch ``Trainable.save_checkpoint``/
        ``Trainable.load_checkpoint`` errors before execution.

        >>> from ray.tune.utils import validate_save_restore
        >>> MyTrainableClass = ... # doctest: +SKIP
        >>> validate_save_restore(MyTrainableClass) # doctest: +SKIP

        .. versionadded:: 0.8.7

        Args:
            checkpoint_dir: The directory where the checkpoint
                file must be stored. In a Tune run, if the trial is paused,
                the provided path may be temporary and moved.

        Returns:
            A dict or None. If dict, the return value will
            be automatically serialized by Tune. In that case,
            ``Trainable.load_checkpoint()`` will receive the dict upon restore.

        Example:
            >>> trainable, trainable1, trainable2 = ... # doctest: +SKIP
            >>> print(trainable1.save_checkpoint("/tmp/checkpoint_1")) # doctest: +SKIP
            "/tmp/checkpoint_1"
            >>> print(trainable2.save_checkpoint("/tmp/checkpoint_2")) # doctest: +SKIP
            {"some": "data"}
            >>> trainable.save_checkpoint("/tmp/bad_example") # doctest: +SKIP
            "/tmp/NEW_CHECKPOINT_PATH/my_checkpoint_file" # This will error.
        r1  )rd   r   s     ri   r   zTrainable.save_checkpointO  s    F "!rk   r   c                     t           )a  Subclasses should override this to implement restore().

        Warning:
            In this method, do not rely on absolute paths. The absolute
            path of the checkpoint_dir used in ``Trainable.save_checkpoint``
            may be changed.

        If ``Trainable.save_checkpoint`` returned a prefixed string, the
        prefix of the checkpoint string returned by
        ``Trainable.save_checkpoint`` may be changed.
        This is because trial pausing depends on temporary directories.

        The directory structure under the checkpoint_dir provided to
        ``Trainable.save_checkpoint`` is preserved.

        See the examples below.

        Example:
            >>> import os
            >>> from ray.tune.trainable import Trainable
            >>> class Example(Trainable):
            ...    def save_checkpoint(self, checkpoint_path):
            ...        my_checkpoint_path = os.path.join(checkpoint_path, "my/path")
            ...        return my_checkpoint_path
            ...    def load_checkpoint(self, my_checkpoint_path):
            ...        print(my_checkpoint_path)
            >>> trainer = Example()
            >>> # This is used when PAUSED.
            >>> checkpoint_result = trainer.save() # doctest: +SKIP
            >>> trainer.restore(checkpoint_result) # doctest: +SKIP

        If `Trainable.save_checkpoint` returned a dict, then Tune will directly pass
        the dict data as the argument to this method.

        Example:
            >>> from ray.tune.trainable import Trainable
            >>> class Example(Trainable):
            ...    def save_checkpoint(self, checkpoint_path):
            ...        return {"my_data": 1}
            ...    def load_checkpoint(self, checkpoint_dict):
            ...        print(checkpoint_dict["my_data"])

        .. versionadded:: 0.8.7

        Args:
            checkpoint: If dict, the return value is as
                returned by ``save_checkpoint``. Otherwise, the directory
                the checkpoint was stored in.
        r1  )rd   r   s     ri   r   zTrainable.load_checkpointt  s    d "!rk   c                     dS )zSubclasses should override this for custom initialization.

        .. versionadded:: 0.8.7

        Args:
            config: Hyperparameters and other configs given.
                Copy of `self.config`.

        Nrn   )rd   r2   s     ri   r\   zTrainable.setup  s	     	rk   r   c                 :    | j                             |           dS )a  Subclasses can optionally override this to customize logging.

        The logging here is done on the worker process rather than
        the driver.

        .. versionadded:: 0.8.7

        Args:
            result: Training result returned by step().
        N)r;   	on_result)rd   r   s     ri   r   zTrainable.log_result  s!     	%%f-----rk   c                     dS )a  Subclasses should override this for any cleanup on stop.

        If any Ray actors are launched in the Trainable (i.e., with a RLlib
        trainer), be sure to kill the Ray actor process here.

        This process should be lightweight. Per default,

        You can kill a Ray actor by calling `ray.kill(actor)`
        on the actor or removing all references to it and waiting for garbage
        collection

        .. versionadded:: 0.8.7
        Nrn   ry   s    ri   r!  zTrainable.cleanup  s	     	rk   c                     i S )a&  Subclasses should override this to export model.

        Args:
            export_formats: List of formats that should be exported.
            export_dir: Directory to place exported models.

        Return:
            A dict that maps ExportFormats to successfully exported models.
        rn   r   s      ri   r   zTrainable._export_model  s	     	rk   c                 \    t          | |          ot          t          | |                    S rv   )hasattrcallablegetattr)rd   keys     ri   _implements_methodzTrainable._implements_method  s)    tS!!BhwtS/A/A&B&BBrk   )NNN)NNNF)r   rv   )NN)8__name__
__module____qualname____doc__r
   r   r   r	   r   r   rj   classmethodr   rq   rt   rz   r   floatr   boolr   r   r:   r   r   r   r   r   r   r,   r   r   r   r   r  r   r=   r[   r   r  propertyr   r%  r   r(  r   r-  r/  r   r   r   r\   r   r!  r   r?  rn   rk   ri   r1   r1   9   s        " "L "&?C,0	I9 I9S#XI9 !$sCx.!18!;<I9 .)	I9 I9 I9 I9V #s(^	'	(   [0 4    [+ + +
 #'*.#'#(! !h! !! C=	!
 !! 
! ! ! !F  & &E &c & & & &Pm m m^
 
 
6!!6!<A#t)<L6!	6! 6! 6! 6!p %! %!8C= %!O %! %! %! \%!N FS$S*?%PQFS FS FS \FSR RV> >#DIsN3>AI#> > > >,. . . .`t     & @DT TS#XT !$sCx.!18!;<T T T T0@ @ @4( ( (      X   X    X  *?!@    X    X   X  " " ""#"c #"htn #" #" #" #"J2"(4. 2" 2" 2" 2"h
D 
 
 
 
. . . . .   
DI 
3 
 
 
 
C C C C Crk   r1   )Nr]   r  rw   r   r   r  r   rQ   
contextlibr   r   r   pathlibr   typingr   r   r	   r
   r   r   r   rS   ray.cloudpicklecloudpickler   ray._common.utilsr   ray.air._internal.utilr   r   ray.air.constantsr   r   r   &ray.train._internal.checkpoint_managerr   ray.train._internal.storager   r   ray.train.constantsr   #ray.tune.execution.placement_groupsr   ray.tune.resultr   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   ray.tune.utilsr)   ray.tune.utils.logr*   ray.tune.utils.utilr+   ray.util.annotationsr,   r-   r	  r.   	getLoggerr@  rY   r_   r   r1   rn   rk   ri   <module>rZ     s      				   



   7 7 7 7 7 7 7 7             L L L L L L L L L L L L L L L L L L 



 $ $ $ $ $ $ 5 5 5 5 5 5 C C C C C C C C M M M M M M M M M M B B B B B B J J J J J J J J 4 4 4 4 4 4 E E E E E E                                   $ ' & & & & & . . . . . . # # # # # # 8 8 8 8 8 8 8 8 '&&&&&&		8	$	$  4  dC dC dC dC dC dC dC dC dC dCrk   