
    &`ig                        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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lmZmZmZmZ d dlmZmZmZmZmZmZmZ d dl m!Z! d d	l"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/m0Z1m2Z3 n# e4$ r dZ'dZ*dZ,dZ.dZ3dZ1Y nw xY w ej5        e6          Z7dZ8 G d d          Z9 G d de          Z:dS )    N)AnyCallableDictListOptionalTupleUnion)version)TRAINING_ITERATION)DEFAULT_METRIC)UNDEFINED_METRIC_MODEUNDEFINED_SEARCH_SPACEUNRESOLVED_SEARCH_SPACESearcher)CategoricalDomainFloatInteger
LogUniform	QuantizedUniform)parse_spec_vars)flatten_dictunflatten_dictvalidate_warmstart)BaseDistribution)BaseSampler)BaseStorage)Trial
TrialState   c                   B    e Zd ZdZdeddfdZdedefdZdede	fd	Z
dS )
_OptunaTrialSuggestCaptora  Utility to capture returned values from Optuna's suggest_ methods.

    This will wrap around the ``optuna.Trial` object and decorate all
    `suggest_` callables with a function capturing the returned value,
    which will be saved in the ``captured_values`` dict.
    ot_trialreturnNc                 "    || _         i | _        d S N)r$   captured_values)selfr$   s     x/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/tune/search/optuna/optuna_search.py__init__z"_OptunaTrialSuggestCaptor.__init__:   s     /1    funcc                 J     t          j                   fd            }|S )Nc                  d    |                     d| d                   } | i |}|j        |<   |S )Nnamer   )getr(   )argskwargsr0   retr-   r)   s       r*   wrapperz7_OptunaTrialSuggestCaptor._get_wrapper.<locals>.wrapper?   sB     ::fd1g..D$'''C),D &Jr,   )	functoolswraps)r)   r-   r5   s   `` r*   _get_wrapperz&_OptunaTrialSuggestCaptor._get_wrapper>   s>    				 	 	 	 	 
		 r,   	item_namec                     t          | j        |          }|                    d          r$t          |          r|                     |          S |S )Nsuggest_)getattrr$   
startswithcallabler8   )r)   r9   items      r*   __getattr__z%_OptunaTrialSuggestCaptor.__getattr__I   sO    t}i00
++ 	+ 	+$$T***r,   )__name__
__module____qualname____doc__OptunaTrialr+   r   r8   strr   r@    r,   r*   r#   r#   2   s         2 2 2 2 2 2	 	h 	 	 	 	S S      r,   r#   c                       e Zd ZdZ	 	 	 	 	 	 	 	 	 d)deeeedf         ee	         e
dgeeeef                  f         f                  deeeee         f                  deeeee         f                  deee                  d	ed
         dee         ded         dee         dee         f fdZdeeef         fdZdee         dee         dedefdZde
dgeeeef                  f         dddefdZdedee         fdZdedefdZ	 d*dedee         defdZ	 	 	 d+ded eded!ed"eee                  f
d#Zd$efd%Zd$efd&Zed'edeeef         fd(            Z xZS ),OptunaSearcha   A wrapper around Optuna to provide trial suggestions.

    `Optuna <https://optuna.org/>`_ is a hyperparameter optimization library.
    In contrast to other libraries, it employs define-by-run style
    hyperparameter definitions.

    This Searcher is a thin wrapper around Optuna's search algorithms.
    You can pass any Optuna sampler, which will be used to generate
    hyperparameter suggestions.

    Multi-objective optimization is supported.

    Args:
        space: Hyperparameter search space definition for
            Optuna's sampler. This can be either a :class:`dict` with
            parameter names as keys and ``optuna.distributions`` as values,
            or a Callable - in which case, it should be a define-by-run
            function using ``optuna.trial`` to obtain the hyperparameter
            values. The function should return either a :class:`dict` of
            constant values with names as keys, or None.
            For more information, see https://optuna.readthedocs.io/en/stable/tutorial/10_key_features/002_configurations.html.

            .. warning::
                No actual computation should take place in the define-by-run
                function. Instead, put the training logic inside the function
                or class trainable passed to ``tune.Tuner()``.

        metric: The training result objective value attribute. If
            None but a mode was passed, the anonymous metric ``_metric``
            will be used per default. Can be a list of metrics for
            multi-objective optimization.
        mode: One of {min, max}. Determines whether objective is
            minimizing or maximizing the metric attribute. Can be a list of
            modes for multi-objective optimization (corresponding to
            ``metric``).
        points_to_evaluate: Initial parameter suggestions to be run
            first. This is for when you already have some good parameters
            you want to run first to help the algorithm make better suggestions
            for future parameters. Needs to be a list of dicts containing the
            configurations.
        sampler: Optuna sampler used to
            draw hyperparameter configurations. Defaults to ``MOTPESampler``
            for multi-objective optimization with Optuna<2.9.0, and
            ``TPESampler`` in every other case.
            See https://optuna.readthedocs.io/en/stable/reference/samplers/index.html
            for available Optuna samplers.

            .. warning::
                Please note that with Optuna 2.10.0 and earlier
                default ``MOTPESampler``/``TPESampler`` suffer
                from performance issues when dealing with a large number of
                completed trials (approx. >100). This will manifest as
                a delay when suggesting new configurations.
                This is an Optuna issue and may be fixed in a future
                Optuna release.
        study_name: Optuna study name that uniquely identifies the trial
            results. Defaults to ``"optuna"``.
        storage: Optuna storage used for storing trial results to
            storages other than in-memory storage,
            for instance optuna.storages.RDBStorage.
        seed: Seed to initialize sampler with. This parameter is only
            used when ``sampler=None``. In all other cases, the sampler
            you pass should be initialized with the seed already.
        evaluated_rewards: If you have previously evaluated the
            parameters passed in as points_to_evaluate you can avoid
            re-running those trials by passing in the reward attributes
            as a list so the optimiser can be told the results without
            needing to re-compute the trial. Must be the same length as
            points_to_evaluate.

            .. warning::
                When using ``evaluated_rewards``, the search space ``space``
                must be provided as a :class:`dict` with parameter names as
                keys and ``optuna.distributions`` instances as values. The
                define-by-run search space definition is not yet supported with
                this functionality.

    Tune automatically converts search spaces to Optuna's format:

    .. code-block:: python

        from ray.tune.search.optuna import OptunaSearch

        config = {
            "a": tune.uniform(6, 8)
            "b": tune.loguniform(1e-4, 1e-2)
        }

        optuna_search = OptunaSearch(
            metric="loss",
            mode="min")

        tuner = tune.Tuner(
            trainable,
            tune_config=tune.TuneConfig(
                search_alg=optuna_search,
            ),
            param_space=config,
        )
        tuner.fit()

    If you would like to pass the search space manually, the code would
    look like this:

    .. code-block:: python

        from ray.tune.search.optuna import OptunaSearch
        import optuna

        space = {
            "a": optuna.distributions.FloatDistribution(6, 8),
            "b": optuna.distributions.FloatDistribution(1e-4, 1e-2, log=True),
        }

        optuna_search = OptunaSearch(
            space,
            metric="loss",
            mode="min")

        tuner = tune.Tuner(
            trainable,
            tune_config=tune.TuneConfig(
                search_alg=optuna_search,
            ),
        )
        tuner.fit()

        # Equivalent Optuna define-by-run function approach:

        def define_search_space(trial: optuna.Trial):
            trial.suggest_float("a", 6, 8)
            trial.suggest_float("b", 1e-4, 1e-2, log=True)
            # training logic goes into trainable, this is just
            # for search space definition

        optuna_search = OptunaSearch(
            define_search_space,
            metric="loss",
            mode="min")

        tuner = tune.Tuner(
            trainable,
            tune_config=tune.TuneConfig(
                search_alg=optuna_search,
            ),
        )
        tuner.fit()

    Multi-objective optimization is supported:

    .. code-block:: python

        from ray.tune.search.optuna import OptunaSearch
        import optuna

        space = {
            "a": optuna.distributions.FloatDistribution(6, 8),
            "b": optuna.distributions.FloatDistribution(1e-4, 1e-2, log=True),
        }

        # Note you have to specify metric and mode here instead of
        # in tune.TuneConfig
        optuna_search = OptunaSearch(
            space,
            metric=["loss1", "loss2"],
            mode=["min", "max"])

        # Do not specify metric and mode here!
        tuner = tune.Tuner(
            trainable,
            tune_config=tune.TuneConfig(
                search_alg=optuna_search,
            ),
        )
        tuner.fit()

    You can pass configs that will be evaluated first using
    ``points_to_evaluate``:

    .. code-block:: python

        from ray.tune.search.optuna import OptunaSearch
        import optuna

        space = {
            "a": optuna.distributions.FloatDistribution(6, 8),
            "b": optuna.distributions.FloatDistribution(1e-4, 1e-2, log=True),
        }

        optuna_search = OptunaSearch(
            space,
            points_to_evaluate=[{"a": 6.5, "b": 5e-4}, {"a": 7.5, "b": 1e-3}]
            metric="loss",
            mode="min")

        tuner = tune.Tuner(
            trainable,
            tune_config=tune.TuneConfig(
                search_alg=optuna_search,
            ),
        )
        tuner.fit()

    Avoid re-running evaluated trials by passing the rewards together with
    `points_to_evaluate`:

    .. code-block:: python

        from ray.tune.search.optuna import OptunaSearch
        import optuna

        space = {
            "a": optuna.distributions.FloatDistribution(6, 8),
            "b": optuna.distributions.FloatDistribution(1e-4, 1e-2, log=True),
        }

        optuna_search = OptunaSearch(
            space,
            points_to_evaluate=[{"a": 6.5, "b": 5e-4}, {"a": 7.5, "b": 1e-3}]
            evaluated_rewards=[0.89, 0.42]
            metric="loss",
            mode="min")

        tuner = tune.Tuner(
            trainable,
            tune_config=tune.TuneConfig(
                search_alg=optuna_search,
            ),
        )
        tuner.fit()

    .. versionadded:: 0.8.8

    NspaceOptunaDistributionrE   metricmodepoints_to_evaluatesamplerr   
study_namestorager   seedevaluated_rewardsc
                 `   t           
J d            t          t          |                               ||           t	          |t
                    r|r}t          |          \  }
}}|s|rVt                              t          j
        dt          |           j                             |                     |          }nt          |d          }|| _        |pg | _        |	| _        |r|| _        nd| _        |r|rt                              d           n!|rt	          |t&                    s
J d            || _        || _        |rt	          |t,                    s
J d	            || _        t1                      | _        i | _        d | _        | j        r|                     |           d S d S )
Nz3Optuna must be installed! Run `pip install optuna`.)rL   rM   rJ   )parcls/optunazYou passed an initialized sampler to `OptunaSearch`. The `seed` parameter has to be passed to the sampler directly and will be ignored.z`You can only pass an instance of `optuna.samplers.BaseSampler` as a sampler to `OptunaSearcher`.zaThe `storage` parameter in `OptunaSearcher` must be an instance of `optuna.storages.BaseStorage`.)otsuperrI   r+   
isinstancedictr   loggerwarningr   formattyperA   convert_search_spacer   _space_points_to_evaluate_evaluated_rewards_study_namer   _sampler_seedr   _storageset_completed_trials
_ot_trials	_ot_study_setup_study)r)   rJ   rL   rM   rN   rO   rP   rQ   rR   rS   resolved_varsdomain_vars	grid_vars	__class__s                r*   r+   zOptunaSearch.__init__=  s   $ ~~T~~~lD!!**&t*DDDeT"" 		1u 		14CE4J4J1M;	 1i 1+2wDJJDWXXX   11%88 %UC00#5#; "3 	()D'D 	t 	NN'   
  	g{33  4 3  
 	g{33  4 3  !$; 	$d#####	$ 	$r,   c           	      6   | j         <| j        r5t          | j        t                    rt	          d          t
          | _         t          j                                        }| j	        r| j	        }nt          |t                    rZt          j        t          j                  t          j        d          k     r&t          j                            | j                  }n%t          j                            | j                  }t          |t                    rt#          d |D                       }nt#          |dk    rdnd	          }t          j        j        d| j        ||| j        d
d|| _        | j        rt1          | j        | j        | j        t7          | j                              | j        r8t9          | j        | j                  D ]\  }}|                     ||           d S | j        D ]}| j                            |           d S d S )NzVIf ``mode`` is a list (multi-objective optimization case), ``metric`` must be defined.z2.9.0)rR   c                 "    g | ]}|d k    rdndS )minminimizemaximizerG   ).0ms     r*   
<listcomp>z-OptunaSearch._setup_study.<locals>.<listcomp>  s$    SSS!u**JJ*SSSr,   )
directionsrt   ru   rv   )	directionT)rQ   rO   prunerrP   load_if_exists)validate_point_name_lengthsrG   )_metric_moder[   list
ValueErrorr   rY   pruners	NopPrunerrf   r
   parse__version__samplersMOTPESamplerrg   
TPESamplerr\   studycreate_studyrh   re   rl   rc   r   rb   rd   r>   zipadd_evaluated_pointenqueue_trial)r)   rM   r|   rO   study_direction_argspointrewards          r*   rm   zOptunaSearch._setup_study  sa   <DJ$*d++  9  
 *DL%%''= 	>mGGd## 	>bn(E(EI
 I
 )
 )
 k..DJ.??GGk,,$*,==GdD!! 	#'SSdSSS$ $ $   $((,**:$ $ $  . 
M'
 
 #
 
 # 	8('080E0E,E	    & 8%(,d.E& & < <ME6 ,,UF;;;;< <
 "5 8 8EN007777	8 	88 8r,   configr%   c                     | j         rdS |                     |          }|| _         |r|| _        |r|| _        |                     | j                   dS )NFT)rb   ra   r   r   rm   )r)   rL   rM   r   specrJ   s         r*   set_search_propertiesz"OptunaSearch.set_search_properties  sf     ; 	5))&11 	"!DL 	DJ$*%%%tr,   r-   r$   c                    t          |          }t          j                    } ||          }t          j                    |z
  }|t          k    rt          j        d| d           |ot          |t                    s t          dt          |           d          t          d |
                                D                       st          d          |ri |j        |n|j        S )Nz;Define-by-run function passed in the `space` argument took z seconds to run. Ensure that actual computation, training takes place inside Tune's train functions or Trainables passed to `tune.Tuner()`.zThe return value of the define-by-run function passed in the `space` argument should be either None or a `dict` with `str` keys. Got .c              3   @   K   | ]}t          |t                    V  d S r'   )r[   rF   )rw   ks     r*   	<genexpr>z@OptunaSearch._suggest_from_define_by_run_func.<locals>.<genexpr>  s,      >>az!S))>>>>>>r,   z{At least one of the keys in the dict returned by the define-by-run function passed in the `space` argument was not a `str`.)r#   timeDEFINE_BY_RUN_WARN_THRESHOLD_Swarningswarnr[   r\   	TypeErrorr`   allkeysr(   )r)   r-   r$   captor
time_startr4   
time_takens          r*    _suggest_from_define_by_run_funcz-OptunaSearch._suggest_from_define_by_run_func  s   
 +844Y[[
d6llY[[:-
666M,", , ,   ?c4(( (  99( ( (   >>388::>>>>> '  
 58S0&(0C00V=SSr,   trial_idc                 l   | j         s-t          t          j        | j        j        d                    | j        r| j        s8t          t          j        | j        j        | j        | j                            t          | j                   rS|| j
        vr!| j                                        | j
        |<   | j
        |         }|                     | j         |          }nE|| j
        vr(| j                            | j                   | j
        |<   | j
        |         }|j        }t          |          S )NrJ   rV   rJ   rV   rL   rM   )fixed_distributions)rb   RuntimeErrorr   r_   rq   rA   r   r   r   r>   rk   rl   askr   paramsr   )r)   r   r$   r   s       r*   suggestzOptunaSearch.suggest  sC   { 	&-/w    
 | 	4: 	%,/4:    
 DK   	%t..,0N,>,>,@,@)x0H::4;QQFF t..,0N,>,>(, -? - -) x0H_Ff%%%r,   resultc                    t          | j        t                    rd S || j        v r"t                              d| d|            d S || j                 }|t                   }| j        |         }|                    ||           d S )Nz%Received additional result for trial #, but it already finished. Result: )	r[   rL   r   rj   r]   r^   r   rk   report)r)   r   r   rL   stepr$   s         r*   on_trial_resultzOptunaSearch.on_trial_result  s    dk4(( 	 Ft---NN9 9 9069 9   F$()?8,%%%%%r,   Ferrorc                 :   || j         v r"t                              d| d            d S | j        |         }rJt	          | j        t                    rfd| j        D             }n                    | j        d           }nd }t          j	        }||rt          j
        }nt          j        }	 | j                            |||           n1# t          $ r$}t                              |           Y d }~nd }~ww xY w| j                             |           d S )Nz)Received additional completion for trial r   c                 <    g | ]}                     |d           S r'   )r1   )rw   rL   r   s     r*   ry   z2OptunaSearch.on_trial_complete.<locals>.<listcomp>,  s'    JJJFvzz&$//JJJr,   )state)rj   r]   r^   rk   r[   rL   r   r1   OptunaTrialStateCOMPLETEFAILPRUNEDrl   tell	Exceptionadd)r)   r   r   r   r$   valot_trial_stateexcs     `     r*   on_trial_completezOptunaSearch.on_trial_complete  sZ    t---NN9H 9 9069 9   F?8, 	$+t,, 4JJJJdkJJJjjd33C)2; 9!1!6!1!8	 N#^DDDD 	  	  	 NN3	  	""8,,,,,s   2C 
C>C99C>
parametersvalueprunedintermediate_valuesc                 ~   | j         s-t          t          j        | j        j        d                    | j        r| j        s8t          t          j        | j        j        | j        | j                            t          | j                   rt          d          t          j        }|rt          j        }n|rt          j        }|rt          t!          |                    }nd }|t          j        k    rd }t"          j                            |||| j         |          }| j                            |           d S )NrJ   r   r   zDefine-by-run function passed in `space` argument is not yet supported when using `evaluated_rewards`. Please provide an `OptunaDistribution` dict or pass a Ray Tune search space to `tune.Tuner()`.)r   r   r   distributionsr   )rb   r   r   r_   rq   rA   r   r   r   r>   r   r   r   r   r   r\   	enumeraterY   trialcreate_trialrl   	add_trial)	r)   r   r   r   r   r   r   intermediate_values_dictr   s	            r*   r   z OptunaSearch.add_evaluated_point>  sk    { 	&-/w    
 | 	4: 	%,/4:    
 DK   	2   *2 	5-2NN 	5-4N 	,'+I6I,J,J'K'K$$'+$ -222E%% + 8 & 
 
 	  '''''r,   checkpoint_pathc                     | j                                         }t          |d          5 }t          j        ||           d d d            d S # 1 swxY w Y   d S )Nwb)__dict__copyopenpickledump)r)   r   save_object
outputFiles       r*   savezOptunaSearch.savex  s    m((**/4(( 	1JKZ000	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1s   AAAc                 "   t          |d          5 }t          j        |          }d d d            n# 1 swxY w Y   t          |t                    r| j                            |           d S |\  | _        | _        | _	        | _
        | _        d S )Nrb)r   r   loadr[   r\   r   updaterf   rk   rl   rc   rd   )r)   r   	inputFiler   s       r*   restorezOptunaSearch.restore}  s    /4(( 	1I +i00K	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1k4(( 
	M  ----- ('''s   266r   c                     t          |           \  }}}|s|si S |rt          d          t          | d          } t          |           \  }}}dt          dt          j        j        fdfd|D             }|S )NzSGrid search parameters cannot be automatically converted to an Optuna search space.T)prevent_delimiterdomainr%   c           	      D   d }|                                  }t          |t                    r=|j        }|j        }t          |t
                    rt                              d           t          | t                    rt          |t
                    rH|rt                              d           t          j
                            | j        | j        d          S t          |t                    rX|r,t          j
                            | j        | j        |          S t          j
                            | j        | j                  S nt          | t                    rt          |t
                    r2t          j
                            | j        | j        dz
  |pdd          S t          |t                    rLt          j
                            | j        | j        t#          t%          |                     z
  |pd          S nNt          | t&                    r9t          |t                    r$t          j
                            | j                  S t-          d                    t1          |           j        t1          | j                  j                            )	NzyOptuna does not handle quantization in loguniform sampling. The parameter will be passed but it will probably be ignored.z]Optuna does not support both quantization and sampling from LogUniform. Dropped quantization.T)log)r   r!   )r   r   zQOptuna search does not support parameters of type `{}` with samplers of type `{}`)get_samplerr[   r   qrO   r   r]   r^   r   rY   r   FloatDistributionlowerupperr   r   IntDistributionintboolr   CategoricalDistribution
categoriesr   r_   r`   rA   )r   quantizerO   s      r*   resolve_valuez8OptunaSearch.convert_search_space.<locals>.resolve_value  s   H((**G'9-- "9!/gz22 NN/   &%(( #Wgz22  N   +==fl >     11  !/AA"L&,X  B      +==fl   FG,, Wgz22 +;;flQ&6X]PT <     11  +;;s4H+=+='>'>>%] <    FK00 Wgw// W+CCFDUVVV228&LL)4+?+?+H3 3  r,   c                 T    i | ]$\  }}d                      |           |          %S )rW   )join)rw   pathr   r   s      r*   
<dictcomp>z5OptunaSearch.convert_search_space.<locals>.<dictcomp>  s3    XXXLD&#((4..--"7"7XXXr,   )r   r   r   r   rY   r   r   )r   rn   ro   rp   valuesr   s        @r*   ra   z!OptunaSearch.convert_search_space  s    0?0E0E-{I 	9 	I 	-   DD9990?0E0E-{I8	& 8	R-=-N 8	 8	 8	 8	v YXXXKXXXr,   )	NNNNNNNNN)NF)FFN)rA   rB   rC   rD   r   r	   r   rF   r   r   r   r   r   r+   r   rm   r   r   r   r   r   r   floatr   r   r   staticmethodra   __classcell__)rq   s   @r*   rI   rI   P   sh       j jh 260437+/$(+/",0!G$ G$S../U-(4S>*BBCE
G$ sDI~./G$ uS$s)^,-G$ %T$Z0G$ -(G$ SMG$ -(G$ smG$  $D>!G$ G$ G$ G$ G$ G$R68sDy!1 68 68 68 68psm+3C=BF	   Tc3h(@@AT  T 
	T T T TB& & & & & &@& &T & & & &" KP- --%-d^-CG- - - -H 598( 8(8( 8( 	8(
 8( &d5k28( 8( 8( 8(t1C 1 1 1 1
s     M4 MDcN M M M \M M M M Mr,   rI   );r6   loggingr   r   r   typingr   r   r   r   r   r   r	   	packagingr
   ray.air.constantsr   ray.tune.resultr   ray.tune.searchr   r   r   r   ray.tune.search.sampler   r   r   r   r   r   r   !ray.tune.search.variant_generatorr   ray.tune.utils.utilr   r   r   rX   rY   optuna.distributionsr   rK   optuna.samplersr   optuna.storagesr   optuna.trialr   rE   r    r   ImportError	getLoggerrA   r]   r   r#   rI   rG   r,   r*   <module>r     s           D D D D D D D D D D D D D D D D D D       0 0 0 0 0 0 * * * * * *                             > = = = = = P P P P P P P P P PKKKKKK++++++++++++QQQQQQQQQ   	BKKKKK 
	8	$	$ "#        <J
 J
 J
 J
 J
8 J
 J
 J
 J
 J
s   (B BB