o
    $i>                     @   sd  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 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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 d d	lmZm Z  d d
l!m"Z" d dl#m$Z$m%Z% d dl&m'Z'm(Z(m)Z)m*Z* d dl+m,Z,m-Z- erd dl.Z/d dlm0Z0 d dl1m2Z2 e3e4Z5dd Z6e-G dd dZ7dee7ee7 ef fddZ8dS )    N)partial)Path)PicklingError)
TYPE_CHECKINGAnyCallableDictListMappingOptionalSequenceTypeUnion)RpcError)StorageContext)DEFAULT_STORAGE_PATH)CheckpointConfig
SyncConfig)	TuneError)is_function_trainableregister_trainable)CombinedStopperFunctionStopperStopperTimeoutStopper)
DeprecatedDeveloperAPI)PlacementGroupFactory)Trialc                 C   s   | s
d }}||fS t | tr| rd}d}||fS t | tr&|  }}||fS t | trBt| dkr:tdt| | \}}||fS tdt| )zsValidate ``tune.RunConfig``'s ``log_to_file`` parameter. Return
    validated relative stdout and stderr filenames.Nstdoutstderr   zIf you pass a Sequence to `log_to_file` it has to have a length of 2 (for stdout and stderr, respectively). The Sequence you passed has length {}.zqYou can pass a boolean, a string, or a Sequence of length 2 to `log_to_file`, but you passed something else ({}).)
isinstanceboolstrr   len
ValueErrorformattype)log_to_filestdout_filestderr_file r,   [/home/ubuntu/veenaModal/venv/lib/python3.10/site-packages/ray/tune/experiment/experiment.py_validate_log_to_file*   s0   


r.   c                &   @   s,  e Zd ZdZh dZeZdddddddddddddddddded	eee	e
f d
eeeee	eegef f  deeeeejf  deeeef  dedeeeeeef f df dedee ded deeeef  deeeef  dee	dgef  dee	dgef  dedee dedee dee f$ddZededefd d!Zed"eee	e
f fd#d$Zed"eee	e
f fd%d&Zed'd( Zed)ee fd*d+Z ee!d,d-d. Z"ed)ee fd/d0Z#ed)ee fd1d2Z$ed3d4 Z%ee!d,d5d6 Z&ed7d8 Z'ed)eeef fd9d:Z(dS );
Experimenta  Tracks experiment specifications.

    Implicitly registers the Trainable if needed. The args here take
    the same meaning as the arguments defined `tune.py:run`.

    .. code-block:: python

        experiment_spec = Experiment(
            "my_experiment_name",
            my_func,
            stop={"mean_accuracy": 100},
            config={
                "alpha": tune.grid_search([0.2, 0.4, 0.6]),
                "beta": tune.grid_search([1, 2]),
            },
            resources_per_trial={
                "cpu": 1,
                "gpu": 0
            },
            num_samples=10,
            local_dir="~/ray_results",
            checkpoint_freq=10,
            max_failures=2)

    >   stopnum_samplestime_budget_sN   Fr   )r0   r2   configresources_per_trialr1   storage_pathstorage_filesystemsync_configcheckpoint_configtrial_name_creatortrial_dirname_creatorr)   export_formatsmax_failuresrestore	local_dirnamerunr0   r2   r4   r5   r   r1   r6   r7   zpyarrow.fs.FileSystemr8   r9   r:   r   r;   r)   r<   r=   r>   r?   c                C   sD  t |trtdi |}n|pt }t|r$|jrtd|jr$tdzt|| _	W n t
yJ } z|jtjjkrDtdt  |d }~ww |sRt|}|pUt}| j||	|
|d| _td| j  |pli }t |ts|tdt| dd | _i }|snZt |trdd	 |D }|rd
d	 |D }td| dt| | _n7t |tr|}n/t|rt|rt|| _n t |t r|| _ntdt| dtd| dt| d|r| jrt| jt!|| _nt!|| _t"|\}}| j	||||||||||f|p	g ||rt#|$ % & nd | jd}|| _'d S )Nz'checkpoint_at_end' cannot be used with a function trainable. You should include one last call to `ray.tune.report(metrics=..., checkpoint=...)` at the end of your training loop to get this behavior.z'checkpoint_frequency' cannot be set for a function trainable. 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.a  The Trainable/training function is too large for grpc resource limit. Check that its definition is not implicitly capturing a large array or other object in scope. Tip: use tune.with_parameters() to put large objects in the Ray object store. 
Original exception: )r6   r7   r8   experiment_dir_namezStorageContext on the DRIVER:
z*`Experiment(config)` must be a dict, got: zB. Please convert your search space to a dict before passing it in.c                 S   s   g | ]	}t |ts|qS r,   )r"   r   .0sr,   r,   r-   
<listcomp>   s    z'Experiment.__init__.<locals>.<listcomp>c                 S   s   g | ]}t |qS r,   )r(   rC   r,   r,   r-   rF      s    zIf you pass a list as the `stop` argument to `tune.RunConfig()`, each element must be an instance of `tune.stopper.Stopper`. Got .zaProvided stop object must be either a dict, a function, or a subclass of `ray.tune.Stopper`. Got zInvalid stop criteria: z". Must be a callable or dict. Got )rA   r0   r2   r4   r5   r1   r9   r:   r;   r)   r<   r=   r>   storager,   )(r"   dictr   r   checkpoint_at_endr&   checkpoint_frequencyr/   register_if_needed_run_identifierr   rpc_coderay_raylet#GRPC_STATUS_CODE_RESOURCE_EXHAUSTEDr   	traceback
format_excr   get_experiment_dir_namer   _storage_context_clsrH   loggerdebugr(   _stopperlistr   callabler   is_valid_functionr   r   r.   r   
expanduserabsoluteas_posixspec)selfr@   rA   r0   r2   r4   r5   r1   r6   r7   r8   r9   r:   r;   r)   r<   r=   r>   r?   estopping_criteriabad_stoppersstopper_typesr*   r+   r_   r,   r,   r-   __init__f   s   

	








zExperiment.__init__r_   c              
   C   s   d|vrt dd|v r|di |d< |d |d d< |d= d|v r5t|d tr5td
i |d |d< d|v rKt|d trKtd
i |d |d< t|}|d}z| ||fi |}W |S  t	yz } zt dt
| d| d	}~ww )zGenerates an Experiment object from JSON.

        Args:
            name: Name of Experiment.
            spec: JSON configuration of experiment.
        rA   zNo trainable specified!envr4   r8   r9   z>Failed to load the following Tune experiment specification:

 zd.

Please check that the arguments are valid. Experiment creation failed with the following error:
 Nr,   )r   getr"   rI   r   r   copydeepcopypop	TypeErrorpppformat)clsr@   r_   	run_valueexpra   r,   r,   r-   	from_json   s2   

	zExperiment.from_json
run_objectc                 C   s   ddl m} t|tst||r|S t|tst|rdd}t|dr'|j}|S t|drD|j}|dkr7d}|S |	dr@d}|S |}|S t|t
rZt|d	rZt|jdrZ|jj}|S td
| |S td)a  Get Trainable name.

        Args:
            run_object: Trainable to run. If string,
                assumes it is an ID and does not modify it. Otherwise,
                returns a string corresponding to the run_object name.

        Returns:
            A string representing the trainable identifier.

        Raises:
            TuneError: if ``run_object`` passed in is invalid.
        r   DomainDEFAULT_name__name__z<lambda>lambda<funcz(No name detected on trainable. Using {}.z*Improper 'run' - not string nor trainable.)ray.tune.search.samplert   r"   r$   r(   rZ   hasattrrv   rw   
startswithr   rz   rV   warningr'   r   )rn   rr   rt   r@   fn_namer,   r,   r-   get_trainable_name  s:   


	
zExperiment.get_trainable_namec              
   C   s   ddl m} t|tr|S t||rtd |S | |}zt|| W |S  tt	fyC } zd}t
|t|d | dd}~ww )a  Registers Trainable or Function at runtime.

        Assumes already registered if run_object is a string.
        Also, does not inspect interface of given run_object.

        Args:
            run_object: Trainable to run. If string,
                assumes it is an ID and does not modify it. Otherwise,
                returns a string corresponding to the run_object name.

        Returns:
            A string representing the trainable identifier.
        r   rs   z0Not registering trainable. Resolving as variant.zOther options: 
-Try reproducing the issue by calling `pickle.dumps(trainable)`. 
-If the error is typing-related, try removing the type annotations and try again. N)r{   rt   r"   r$   rV   r~   r   r   rk   r   r(   )rn   rr   rt   r@   ra   	extra_msgr,   r,   r-   rL   G  s    




zExperiment.register_if_neededc                 C      | j S N)rX   r`   r,   r,   r-   stopperk  s   zExperiment.stopperreturnc                 C      | j jS r   )rH   experiment_driver_staging_pathr   r,   r,   r-   
local_patho     zExperiment.local_pathzReplaced by `local_path`c                 C      t d)Nz(Use `local_path` instead of `local_dir`.DeprecationWarningr   r,   r,   r-   r?   s     zExperiment.local_dirc                 C   r   r   )rH   experiment_fs_pathr   r,   r,   r-   remote_pathy  r   zExperiment.remote_pathc                 C   s   | j p| jS r   )r   r   r   r,   r,   r-   path}     zExperiment.pathc                 C   s   | j dS )Nr9   )r_   rg   r   r,   r,   r-   r9     r   zExperiment.checkpoint_configc                 C   r   )Nz-Use `local_path` instead of `checkpoint_dir`.r   r   r,   r,   r-   checkpoint_dir  r   zExperiment.checkpoint_dirc                 C   r   )z7Returns a string representing the trainable identifier.)rM   r   r,   r,   r-   run_identifier  s   zExperiment.run_identifierc                    s    fdd j  D S )zReturns the spec dict with only the public-facing keys.

        Intended to be used for passing information to callbacks,
        Searchers and Schedulers.
        c                    s    i | ]\}}| j v r||qS r,   )PUBLIC_KEYS)rD   kvr   r,   r-   
<dictcomp>  s     z*Experiment.public_spec.<locals>.<dictcomp>)r_   itemsr   r,   r   r-   public_spec  s   zExperiment.public_spec))rw   
__module____qualname____doc__r   r   rU   r$   r   r   r   r   r
   r   r#   intfloatdatetime	timedeltar   r   r   rI   r   r   re   classmethodrq   r   rL   propertyr   r   r   r?   r   r   r9   r   r   r   r,   r,   r,   r-   r/   F   s    
 &*#


r/   experimentsc                 C   s   | }| du r	g }nt | tr| g}nt| tu r!dd |  D }t|tu r=tdd |D r=t|dkr;t	d |S t
d| )	a%  Produces a list of Experiment objects.

    Converts input from dict, single experiment, or list of
    experiments to list of experiments. If input is None,
    will return an empty list.

    Arguments:
        experiments: Experiments to run.

    Returns:
        List of experiments.
    Nc                 S   s   g | ]
\}}t ||qS r,   )r/   rq   )rD   r@   r_   r,   r,   r-   rF     s    z/_convert_to_experiment_list.<locals>.<listcomp>c                 s   s    | ]}t |tV  qd S r   )r"   r/   )rD   rp   r,   r,   r-   	<genexpr>  s    z._convert_to_experiment_list.<locals>.<genexpr>r3   zeRunning with multiple concurrent experiments. All experiments will be using the same SearchAlgorithm.zInvalid argument: {})r"   r/   r(   rI   r   rY   allr%   rV   infor   r'   )r   exp_listr,   r,   r-   _convert_to_experiment_list  s    
r   )9rh   r   loggingpprintrl   rR   	functoolsr   pathlibr   pickler   typingr   r   r   r   r	   r
   r   r   r   r   rO   ray.exceptionsr   ray.train._internal.storager   ray.train.constantsr   ray.tuner   r   ray.tune.errorr   ray.tune.registryr   r   ray.tune.stopperr   r   r   r   ray.util.annotationsr   r   
pyarrow.fspyarrowr   ray.tune.experimentr   	getLoggerrw   rV   r.   r/   r   r,   r,   r,   r-   <module>   s:    0
   U