
    &`izj                        d dl Z d dlZd dlZd dlZd dlmZ d dlmZmZ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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! d dl"m#Z# d d	lm$Z$m%Z%m&Z&m'Z'm(Z(m)Z) d d
l*m+Z+ d dl,m-Z- d dl.m/Z/ d dl0m1Z1m2Z2 d dl3m4Z4 d dl5m6Z6 erd dl7m8Z8 d dl9m:Z: dZ;dZ<dZ=dZ>dZ? ej@        eA          ZBeeCe	ee/         f         ZDeeDdf         ZE G d d          ZFdS )    N)Path)	TYPE_CHECKINGAnyCallableDictListOptionalTupleTypeUnion)URI)AirEntrypoint)StorageContextget_fs_and_path)V2_MIGRATION_GUIDE_MESSAGE_v2_migration_warnings_enabled)_log_deprecation_warning)
ExperimentExperimentAnalysisResumeConfig	RunConfig
TuneConfig	TuneError)is_function_trainable)
ResultGrid)	Trainable)_Configrun)flatten_dict)inspect_serializabilityBaseTrainer)Queuez	tuner.pkl
_trainable_converted_trainable_param_space_experiment_analysisr"   c                   4   e Zd ZdZddddddddej        f	dedeej	        j
                 dee         dee         deeeef                  dee         d	ee         d
ee         defdZdefdZd	eddfdZd Zd Z	 d3dedee         fdZdedee         fdZdeeef         deee                  fdZdeeeef                  deee                  fdZdeeef         deee         eee                  f         fdZdededeeeef                  dedeej	        j
                 f
d Zd!ee         d"d#deeeef                  defd$Zd4d%Z e!defd&            Z"e!defd'            Z#e"j$        defd(            Z"e!deeeef                  fd)            Z%e%j$        deeeef                  fd*            Z%dedefd+Z&de'fd,Z(de'fd-Z)dedeeef         fd.Z*dedeeeef                  de+fd/Z,dedeeeef                  de+fd0Z-d1 Z.d2 Z/dS )5TunerInternalaO  The real implementation behind external facing ``Tuner``.

    The external facing ``Tuner`` multiplexes between local Tuner and remote Tuner
    depending on whether in Ray client mode.

    In Ray client mode, external ``Tuner`` wraps ``TunerInternal`` into a remote actor,
    which is guaranteed to be placed on head node.

    ``TunerInternal`` can be constructed from fresh, in which case, ``trainable`` needs
    to be provided, together with optional ``param_space``, ``tune_config`` and
    ``run_config``.

    It can also be restored from a previous failed run (given ``restore_path``).

    Args:
        restore_path: The path from where the Tuner can be restored. If provided, None
            of the rest args are needed.
        resume_config: Resume config to configure which trials to continue.
        trainable: The trainable to be tuned.
        param_space: Search space of the tuning job.
            One thing to note is that both preprocessor and dataset can be tuned here.
        tune_config: Tuning algorithm specific configs.
            Refer to ray.tune.tune_config.TuneConfig for more info.
        run_config: Runtime configuration that is specific to individual trials.
            If passed, this will overwrite the run config passed to the Trainer,
            if applicable. Refer to ray.tune.RunConfig for more info.
    Nrestore_pathstorage_filesystemresume_config	trainableparam_spacetune_config
run_config_tuner_kwargs_entrypointc
                 0   ddl m}
 t          ||
          r=t                      rt	          dt
                      |                     |||          }|pt                      | _        t          j	        |          pt                      | _        |	| _        |r|                     |||||           d S |st          d          | j        t          j        k    rIt          | j        t"          j        j
                  s%t                      rt	          dt
                      || _        | j        sJ |                     | j                   || _        d | _        d| _        t          j        |          pi | _        d | _        | j        j        pt;          j        | j                  | j        _        t;          | j        j        | j        j        | j        j         	          }|j         }|!                    |j"                   |#                    tI          |j"        tJ                    &                                          5 }|'                    tQ          j)        | *                                                     d d d            d S # 1 swxY w Y   d S )
Nr   r!   zThe Ray Train + Ray Tune integration has been reworked. Passing a Trainer to the Tuner is deprecated and will be removed in a future release. )tuner_run_configtrainerr.   )path_or_urir-   overwrite_param_spacer,   r+   z(You need to provide a trainable to tune.zsThe `RunConfig` class should be imported from `ray.tune` when passing it to the Tuner. Please update your imports. F)storage_pathexperiment_dir_namer+   )+ray.train.trainerr"   
isinstancer   r   r   _choose_run_configr   _tune_configcopyr   _run_configr2   _restore_from_path_or_urir   r   TUNERraytuner-   converted_trainable_validate_trainabler.   _resume_config_is_restoreddeepcopyr1   r'   namer   get_experiment_dir_namer8   r+   
create_direxperiment_fs_pathopen_output_streamr   
_TUNER_PKLas_posixwritepickledumps__getstate__)selfr*   r+   r,   r-   r.   r/   r0   r1   r2   r"   storagefsfs                 p/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/tune/impl/tuner_internal.py__init__zTunerInternal.__init__\   s    	211111i-- 	-// (4 24 4   00!+!' 1  J (7:<<9Z00?IKK&  	**(#&1+#5 +    F  	HFGGG}222:ch0<
 <
2 .// (414 4   #''''  !9:::&"!!]=99?R$(! ! P5d6NOO 	 !)6 $ 0 5#/B
 
 
 '
g0111""+Z88AACC
 
 	7GGFL!2!2!4!455666	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7s   :JJJreturnc                     | j         S N)r?   rT   s    rX   get_run_configzTunerInternal.get_run_config   s        string_queuer#   c                 (    || _         || j        d<   d S N_remote_string_queue)r?   r1   )rT   r0   r`   s      rX   &set_run_config_and_remote_string_queuez4TunerInternal.set_run_config_and_remote_string_queue   s      &5A1222r_   c                 <    | j                             dd            d S rb   )r1   popr]   s    rX   clear_remote_string_queuez'TunerInternal.clear_remote_string_queue   s"    5t<<<<<r_   c                     | j         j        }|dk     rt          j        }| j         j        pd}|dk     rt          j        }t          |r||z  nd||f          }||z  |dz   z  S )Nr      gMbP?)r=   num_samplesmathinfmax_concurrent_trialsmin)rT   cpus_per_trial
cpus_totalrj   concurrent_trialsactual_concurrencys         rX   _expected_utilizationz#TunerInternal._expected_utilization   s    '3??(K -CHqq   $ 2@G~--a!
 
 #^3
U8JKKr_   required_trainable_namec                 T   	 t          j        |           n]# t          $ rP}t          j                    }t          ||           d|                                 }t          |          |d}~ww xY w|sdS t          j        |          }||k    rt          d| d| d          dS )a  Determines whether or not the trainable is valid.

        This includes checks on the serializability of the trainable, as well
        asserting that the trainable name is as expected on restoration.

        This trainable name validation is needed due to an implementation detail
        where the trainable name (which is differently generated depending on
        the trainable type) is saved in the Trial metadata and needs to match
        upon restoration. This does not affect the typical path, since `Tuner.restore`
        expects the exact same trainable (which will have the same name).

        Raises:
            ValueError: if the trainable name does not match or if the trainable
                is not serializable.
        )
print_filezThe provided trainable is not serializable, which is a requirement since the trainable is serialized and deserialized when transferred to remote workers. See below for a trace of the non-serializable objects that were found in your trainable:
NzInvalid `trainable` input to `Tuner.restore()`. To fix this error, pass in the same trainable that was used to initialize the Tuner. Got a trainable with identifier 'z' but expected 'z'.)
rQ   rR   	TypeErrorioStringIOr    getvaluer   get_trainable_name
ValueError)rT   r-   rt   esiomsgtrainable_names          rX   rE   z!TunerInternal._validate_trainable   s    $	(L#### 
	( 
	( 
	(+--C#I#>>>>$ <<>>	$ $  C..a'
	( ' 	F#6yAA444P #P P 5LP P P   54s    
A1AA,,A1old_trainable_namec                     ddl m} || _        | j        sJ |                     | j        |           t          | j        |          rF| j        }|j        t                      k    rt          	                    d           | j
        |_        d S d S )Nr   r!   )r-   rt   zThe Tune experiment will restore using the original run's `RunConfig`. If you made any changes to the `RunConfig` within the Trainer you passed into `Tuner.restore`, they will be ignored in the resumed run.)ray.train.base_trainerr"   r-   rD   rE   r;   r0   r   loggerwarningr?   )rT   r-   r   r"   r5   s        rX   _set_trainable_on_restorez'TunerInternal._set_trainable_on_restore   s     	766666"''''  .$6 	! 	
 	
 	

 dnk22 	2 $(>G !Y[[00?   "&!1G	2 	2r_   new_param_spaceflattened_param_space_keysc                     |dS t          t          |                                                    }||k    rt          d| d|           dS )aG  Determines whether the (optionally) re-specified `param_space` is valid.

        This method performs very loose validation on the new param_space to
        prevent users from trying to specify new hyperparameters to tune over.

        Raises:
            ValueError: if not all keys match the original param_space.
        NaZ  Invalid `param_space` input to `Tuner.restore()`. To fix this error, pass in the same `param_space` that was used to initialize the Tuner. Only re-specify the `param_space` to refresh Ray object references that no longer exist due to restoring from a new Ray cluster session. It should not be used to introduce new hyperparameters to tune.

Got: z
Expected: )sortedr   keysr|   )rT   r   r   r   s       rX    _validate_param_space_on_restorez.TunerInternal._validate_param_space_on_restore  s     &-Fl?3388::;;---K
 !K K
 /IK K   .-r_   c                 ^    || _         | j         |                     | j         |           d S d S )N)r   r   )r.   r   )rT   r.   r   s      rX   _set_param_space_on_restorez)TunerInternal._set_param_space_on_restore8  sM    
 ''11 $ 0+E 2      ('r_   tuner_statec                     |                     dd          }|                     dd          }|                     |           ||fS )a  Loads Tuner state from the previously saved `tuner.pkl`.

        Args:
            tuner_pkl_path: pathlib.Path of the `tuner.pkl` file saved during the
                original Tuner initialization.

        Returns:
            tuple: of `(old_trainable_name, flattened_param_space_keys)` used for
                validating the re-specified `trainable` and `param_space`.
        __trainable_nameN__flattened_param_space_keys)rf   __setstate__)rT   r   r   r   s       rX   _load_tuner_statezTunerInternal._load_tuner_stateF  sT     )__-?FF%0__*D&
 &
" 	+&&&!#===r_   r6   r7   c                    t          ||          \  }}|                    t          |t                                                              5 }t          j        |                                          }	d d d            n# 1 swxY w Y   |                     |	          \  }
}| 	                    ||
           | 
                    ||           t          |          }|j        | j        _        t          |j                  | j        _        || j        _        	 t%          || j        j        | j        j        |          | _        n# t.          $ r
 d | _        Y nw xY w|| _        d| _        d S )N)r-   r   )r.   r   )experiment_checkpoint_pathdefault_metricdefault_moder+   T)r   open_input_filer   rN   rO   rQ   loadsreadallr   r   r   r   rI   r?   strparentr8   r+   r   r=   metricmoder'   	ExceptionrF   rG   )rT   r6   r-   r7   r,   r+   rV   fs_pathrW   r   r   r   path_or_uri_objs                rX   r@   z'TunerInternal._restore_from_path_or_uri]  s    &k3EFFGWj 9 9 B B D DEE 	4 ,qyy{{33K	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 :>9O9O:
 :
66
 	&&4F 	' 	
 	
 	
 	((-'A 	) 	
 	
 	
 k** !0 4(+O,B(C(C%.@+	-(:+6#07!.3#5	) ) )D%%  	- 	- 	-(,D%%%	- , s$   'BBB,E
 
EEr4   r5   r"   c                     |rd|v rt          d          |rQ|j        t          j                                        k    r*t
                              d|j        j         d           |S |s|j        S |S )a  Chooses which `RunConfig` to use when multiple can be passed in
        through a Trainer or the Tuner itself.

        Args:
            tuner_run_config: The run config passed into the Tuner constructor.
            trainer: The Trainer instance to use with Tune, which may have
                a RunConfig specified by the user.
            param_space: The param space passed to the Tuner.

        Raises:
            ValueError: if the `run_config` is specified as a hyperparameter.
        r0   z`RunConfig` cannot be tuned as part of the `param_space`! Move the run config to be a parameter of the `Tuner`: Tuner(..., run_config=RunConfig(...))z6A `RunConfig` was passed to both the `Tuner` and the `zE`. The run config passed to the `Tuner` is the one that will be used.)	r|   r0   rB   trainr   r   info	__class____name__)rT   r4   r5   r.   s       rX   r<   z TunerInternal._choose_run_config  s    $  	<;668    	$ 2ci6I6I6K6K K KKK<%.< < <  
 $#
   	&%%  r_   c                     | j                             d          }t          |t          j        j                  sdS |j                                        | j         d<   dS )zConverts ``self._param_space["scaling_config"]`` to a dict.

        The dict is converted back to a dataclass by the Trainer, after the
        Tune search specification is resolved.
        scaling_configN)r&   getr;   rB   r   ScalingConfig__dict__r>   )rT   r   s     rX   _process_scaling_configz%TunerInternal._process_scaling_config  sZ     *../?@@.#)*ABB 	F.<.E.J.J.L.L*+++r_   c                     | j         S r\   )r$   r]   s    rX   r-   zTunerInternal.trainable  s
    r_   c                     | j         S r\   )r%   r]   s    rX   rD   z!TunerInternal.converted_trainable  s    ((r_   c                 H    || _         |                     |          | _        d S r\   )r$   _convert_trainabler%   )rT   r-   s     rX   r-   zTunerInternal.trainable  s%    #$($;$;I$F$F!!!r_   c                     | j         S r\   )r&   r]   s    rX   r.   zTunerInternal.param_space  s      r_   c                    t          |t                    r|                                }t          |t                    s"| t	          dt          |           d          || _        |r|                                  d S d S )Nz=The `param_space` passed to the `Tuner` must be a dict. Got 'z
' instead.)r;   r   to_dictdictr|   typer&   r   )rT   r.   s     rX   r.   zTunerInternal.param_space  s     k7++ 	0%--//K+t,, 	1H6[))6 6 6  
 ( 	+((*****	+ 	+r_   c                 Z    ddl m} t          ||          r|                                n|S )zConverts a Trainer to a Tune trainable and saves the converted
        trainable. If not using a Trainer, this leaves the trainable as is.r   r!   )r:   r"   r;   as_trainable)rT   r-   r"   s      rX   r   z TunerInternal._convert_trainable  sC     	211111 )[11I""$$$	
r_   c                     | j         }t          j        | j                  }| j        s|                     ||          }n|                     ||          }|| _        t          | j                  S r\   )	rD   r>   rH   r.   rG   _fit_internal_fit_resumer'   r   )rT   r-   r.   analysiss       rX   fitzTunerInternal.fit  sm    ,	mD$455  	@)))[AAHH''	;??H$,!$3444r_   c                 V    | j         st          d          t          | j                   S )NziCan't return results as experiment has not been run, yet. Call `Tuner.fit()` to run the experiment first.)r'   RuntimeErrorr   r]   s    rX   get_resultszTunerInternal.get_results  s8    ( 	B   $3444r_   c                    t          j        | j        j                  }|j        r8t          |dd          }|du rt          d|j         d          |du rd|_        |j        9t          |dd          }|du rt          d	|j         d
          |du rd|_        nt          |          rd|_        nd|_        t          d i d| j        j
        d| j        j        d| j        j        d| j        j        d| j        j        d| j        j        d| j        j        d| j        j        d| j        j        j        d|ddd| j        j        j        d| j        j        d| j        j        d| j        j        d| j        j        d| j        j        d| j        j        d| j        j        d| j        d| j        j        S )!z<Get tune.run arguments common for both new and resumed runs._handles_checkpoint_freqNFz!You passed `checkpoint_frequency=a?  ` to your CheckpointConfig, but this trainer does not support this argument. If you passed in a Trainer that takes in a custom training loop, you will need to report a checkpoint every `checkpoint_frequency` iterations within your training loop using `ray.tune.report(metrics=..., checkpoint=...)` to get this behavior.Tr   _handles_checkpoint_at_endzYou passed `checkpoint_at_end=a  ` to your CheckpointConfig, but this trainer does not support this argument. If you passed in a Trainer that takes in a custom training loop, you should include one last call to `ray.tune.report(metrics=..., checkpoint=...)` at the end of your training loop to get this behavior.r8   r+   rI   r   r   	callbackssync_configstopmax_failurescheckpoint_configraise_on_failed_trial	fail_fastprogress_reporterverbosereuse_actorsrm   time_budget_strial_name_creatortrial_dirname_creatorr2   chdir_to_trial_dir )r>   rH   r?   r   checkpoint_frequencygetattrr|   checkpoint_at_endr   r   r8   r+   rI   r=   r   r   r   r   r   failure_configr   r   r   r   r   rm   r   r   r   r2   r   )rT   r-   r   handle_checkpoint_freqhandle_cp_at_ends        rX   _get_tune_run_argumentsz%TunerInternal._get_tune_run_arguments
  s    !M$*:*LMM1 	; &-5t& &" &.. !,(=, , ,
 
 
 (4// :;!6 .:&y2NPTUU5(( M(:M M M   "T)) 7<!3
 %Y// ;6;!336:!3 
 
 
)66
#/BB
 !&&
 "''	

 $++
 &00
 (44
 !&&
 )8EE
 0/
 #(%
 '6@@
 #.@@
 $,,
 *77
  #'"3"I"I!
" +99#
$  $0CC%
& #'"3"I"I'
( (()
,  $0CC-
 	
r_   c           	          i |                      |          t          ||| j        j        | j        j        | j        j        | j        j                  | j        }t          di |}| 
                                 |S )zFitting for a fresh Tuner.)run_or_experimentconfigrj   
search_alg	schedulerlog_to_filer   )r   r   r=   rj   r   r   r?   r   r1   r   rg   rT   r-   r.   argsr   s        rX   r   zTunerInternal._fit_internal^  s    
**955
"+" -9,7+5 ,8  
  
  
 

 
 	&&(((r_   c                     | j         sJ i |                     |          t          ||| j         | j        j        | j        j                  | j        }t          di |}|                                  |S )zFitting for a restored Tuner.)r   r   r,   r   r   r   )	rF   r   r   r=   r   r   r1   r   rg   r   s        rX   r   zTunerInternal._fit_resumet  s     """"

**955

"+""1,7+5  

  

 ;;;;&&(((r_   c                 "   | j                                         }|d                                         |d<   |d                             dd            |                    t          d            |                    t          d           }|                    t
          d           }|                    t          d            |rt          j        |          nd |d<   |.t          t          |                                                    nd |d<   |S )Nr1   rc   r   r   )r   r>   rf   _TRAINABLE_KEY_CONVERTED_TRAINABLE_KEY_PARAM_SPACE_KEY_EXPERIMENT_ANALYSIS_KEYr   r{   r   r   r   )rT   stater-   r.   s       rX   rS   zTunerInternal.__getstate__  s   ""$$!&!7!<!<!>!>oo""#94@@@		.$'''II6==	ii 0$77		*D111 9BKJ))444t 	 !
 & <,,1133444 	,- r_   c                     |                     dd            |                     dd            | j                            |           d S )Nr   r   )rf   r   update)rT   r   s     rX   r   zTunerInternal.__setstate__  sH    		0$777		$d+++U#####r_   r\   )rZ   N)0r   
__module____qualname____doc__r   rA   r   r	   pyarrowrV   
FileSystemr   TrainableTypeOrTrainerr   r   r   r   rY   r^   rd   rg   rs   TrainableTyperE   r   r   r   r   r
   r   r@   r<   r   propertyr-   rD   setterr.   r   r   r   r   r   r   r   r   rS   r   r   r_   rX   r)   r)   ?   s.        < !>B046:04,0*.(,%2%8W7 W7W7 %WZ%:;W7  -	W7
 23W7 d38n-W7 j)W7 Y'W7  ~W7 #W7 W7 W7 W7r 	        B#B3:B B B B= = =L L L$ RV+ +&+AI#+ + + +Z2&2<DSM2 2 2 28c3h %-T#Y$7   8d38n- %-T#Y$7   >S>>	x}htCy11	2> > > >.1!1! *1!  (S#X7	1!
 $1! %WZ%:;1! 1! 1! 1!f) "9-)  )  d38n-	) 
 
)  )  )  ) VM M M M 1    X )] ) ) ) X) G#9 G G G G !Xd38n5 ! ! ! X! +xS#X'? + + + +"	
,B 	
} 	
 	
 	
 	

5Z 
5 
5 
5 
55Z 5 5 5 5R
 R
4S> R
 R
 R
 R
h&5=d38n5M	   ,&5=d38n5M	   *  ($ $ $ $ $r_   r)   )Gr>   rx   loggingrk   pathlibr   typingr   r   r   r   r   r	   r
   r   r   
pyarrow.fsr   ray.cloudpicklecloudpicklerQ   	ray.trainrB   ray.tuneray.air._internal.uri_utilsr   ray.air._internal.usager   ray.train._internal.storager   r   ray.train.constantsr   r   ray.train.utilsr   r   r   r   r   r   r   ray.tune.registryr   ray.tune.result_gridr   ray.tune.trainabler   ray.tune.tuner   r   ray.tune.utilsr   ray.utilr    r:   r"   ray.util.queuer#   rN   r   r   r   r   	getLoggerr   r   r   r   r   r)   r   r_   rX   <module>r	     s    				        
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
                      + + + + + + 1 1 1 1 1 1 G G G G G G G G        5 4 4 4 4 4                4 3 3 3 3 3 + + + + + + ( ( ( ( ( ( & & & & & & & & ' ' ' ' ' ' , , , , , , %------$$$$$$ 
1 ! 1 		8	$	$c8T)_45}m;< c	$ c	$ c	$ c	$ c	$ c	$ c	$ c	$ c	$ c	$r_   