
    jP              
          d dl mZ d dl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 dddddgd	d
dddd	Zd$dZd Zd Zd Zd Zd Zd Zd Zd Zd Z	 	 	 	 	 d%d&d#ZdS )'    )annotationsN)	TASK2DATATASK2METRICget_cfgget_save_dir)DEFAULT_CFGDEFAULT_CFG_DICTLOGGERNUM_THREADScheckscolorstrzax-platformzbayesian-optimization==1.4.3
hpbandsterConfigSpacezHEBO>=0.2.0hyperopt	nevergradoptunazoopt)	randomaxbayesoptbohbhebor   r   r   r   valuedictc                   t          | t                    rd |                                 D             S t          | t                    rd | D             S t          | t                    rt	          d | D                       S t          | t
          j                  r|                                 S t          | t
          j                  r| 	                                S | S )a#  Convert NumPy-backed Tune values into native Python types for YAML serialization.

    Args:
        value (dict): The value to convert. Can be a dict, list, tuple, NumPy scalar, or NumPy array.

    Returns:
        The converted value with NumPy types replaced by native Python types.
    c                4    i | ]\  }}|t          |          S  _sanitize_tune_value).0kvs      Z/var/www/html/Carbon-Document/venv/lib/python3.11/site-packages/ultralytics/utils/tuner.py
<dictcomp>z(_sanitize_tune_value.<locals>.<dictcomp>!   s'    EEEtq!'**EEE    c                ,    g | ]}t          |          S r   r   r    r"   s     r#   
<listcomp>z(_sanitize_tune_value.<locals>.<listcomp>#   s!    777A$Q''777r%   c              3  4   K   | ]}t          |          V  d S Nr   r'   s     r#   	<genexpr>z'_sanitize_tune_value.<locals>.<genexpr>%   s+      <<)!,,<<<<<<r%   )

isinstancer   itemslisttuplenpgenericitemndarraytolist)r   s    r#   r   r      s     % FEEu{{}}EEEE% 8777777% =<<e<<<<<<%$$ zz||%$$ ||~~Lr%   c                d   | dS t          | t                    r*|                                                                 }|pdS | j        }|j        |j        }}|dk    r|                    d          rdS |dk    r|                    d          rdS |dk    r|                    d	          rd
S dS )a\  Return the normalized Ray Tune search algorithm kind for known searcher objects.

    Args:
        search_alg (str | ray.tune.search.Searcher): The search algorithm to identify. Can be None, a string, or a Ray
            Tune searcher object.

    Returns:
        str | None: The normalized search algorithm name, or None if not recognized.
    NAxSearchzray.tune.search.axr   TuneBOHBzray.tune.search.bohbr   ZOOptSearchzray.tune.search.zooptr   )r,   strstriplower	__class__
__module____name__
startswith)
search_alg
normalizedclsmodulenames        r#   _get_ray_search_alg_kindrE   -   s     t*c"" "%%''--//
!T!

C>3<DFzf//0DEEtzf//0FGGv}!2!23J!K!Kw4r%   c                v    t          j        t          d                    ddlm} |                    |           S )a  Validate that a Tune search space can be consumed by Ax.

    Args:
        space (dict): The hyperparameter search space to validate.

    Returns:
        list: The converted Ax parameters.

    Raises:
        ImportError: If the required 'ax-platform' package is not installed.
    r   r   r6   )r   check_requirementsRAY_SEARCH_ALG_REQUIREMENTSray.tune.search.ax.ax_searchr6   convert_search_space)spacer6   s     r#   _validate_ax_search_spacerM   H   sA     9$?@@@555555((///r%   c                    t          |           }ddlm} ddlm} ddlm}  |            }|                    |t          |          |d          i            ||          S )	as  Create an Ax searcher with an initialized experiment.

    Args:
        space (dict): The hyperparameter search space.
        task (str): The task type (e.g., 'detect', 'segment', 'classify').

    Returns:
        AxSearch (ray.tune.search.Searcher): The configured Ax search algorithm.

    Raises:
        ImportError: If required Ax packages are not installed.
    r   )AxClient)ObjectivePropertiesrG   F)minimize)
parameters
objectives)	ax_client)	rM   ax.service.ax_clientrO   ax.service.utils.instantiationrP   rJ   r6   create_experimentr   )rL   taskrR   rO   rP   r6   rT   s          r#   _create_ax_searchrY   [   s     +511J------BBBBBB555555

I%':':E'J'J'JK      8i((((r%   c                   t          j        t          d                    ddl}ddlm}m}m}m}m	}m
} ddlm} ddlm}	  |	| d          }
 ||
          \  }}}|rt          d	          |                                }|D ]\  }}d
                    d |D                       }|                                }t'          ||          rt          d          t'          ||          rWt'          |||f          rE|                    |                    ||j        |j        t'          ||                               t'          ||          r]t'          |||f          rK|j        dz
  }|                    |                    ||j        |t'          ||                               ,t'          ||          rAt'          ||          r1|                    |                    ||j                             }t          dt7          |          j         dt7          |j                  j         d          d |D             }||fS )a  Convert a Tune search space into BOHB-compatible ConfigSpace and fixed-only Tune param_space.

    Args:
        space (dict): The hyperparameter search space.

    Returns:
        (tuple): A tuple containing the ConfigSpace object and a dict of fixed parameters.

    Raises:
        ValueError: If the search space contains grid search parameters or unsupported samplers.
        ImportError: If required BOHB packages are not installed.
    r   r   N)CategoricalFloatInteger
LogUniform	QuantizedUniformparse_spec_varsflatten_dictTprevent_delimiterzTGrid search parameters cannot be automatically converted to a TuneBOHB search space./c              3  4   K   | ]}t          |          V  d S r*   r9   r    ps     r#   r+   z-_convert_bohb_search_space.<locals>.<genexpr>   s(      ,,!s1vv,,,,,,r%   zWTuneBOHB does not support quantized search spaces with the current ConfigSpace version.)r;   upperlog   )choicesz-TuneBOHB does not support parameters of type z with sampler type .c                T    i | ]%\  }}d                      d |D                       |&S )rg   c              3  4   K   | ]}t          |          V  d S r*   ri   rj   s     r#   r+   z8_convert_bohb_search_space.<locals>.<dictcomp>.<genexpr>   (      !7!7Q#a&&!7!7!7!7!7!7r%   joinr    pathr   s      r#   r$   z._convert_bohb_search_space.<locals>.<dictcomp>   9    ```;4!7!7$!7!7!777```r%   )r   rH   rI   r   ray.tune.search.sampler[   r\   r]   r^   r_   r`   !ray.tune.search.variant_generatorrb   ray.tune.utilsrd   
ValueErrorConfigurationSpaceru   get_samplerr,   addUniformFloatHyperparameterr;   rl   UniformIntegerHyperparameterCategoricalHyperparameter
categoriestyper>   sampler)rL   r   r[   r\   r]   r^   r_   r`   rb   rd   resolved_spaceresolved_varsdomain_vars	grid_varscsrw   domainparr   rl   fixed_param_spaces                        r#   _convert_bohb_search_spacer   v   s    9&ABBBbbbbbbbbbbbbbbbbAAAAAA++++++!\%4@@@N,;ON,K,K)M;	 qoppp		'	'	)	)B#  fhh,,t,,,,,$$&&gy)) 	xvwwwfe$$ 	Ggz=R)S)S 	FF66v|6<ZPWYcEdEd 7     
 (( 	Z':AV-W-W 	L1$EFF88v|5jR\>]>] 9     
 ,, 	GW1M1M 	FF;88fFW8XXYYYYFV@U F F%)&.%9%9%BF F F  
 a`R_```   r%   c                h    t          |           \  }}ddlm}  ||t          |         d          |fS )a  Create a BOHB searcher using a ConfigSpace definition compatible with current ConfigSpace versions.

    Args:
        space (dict): The hyperparameter search space.
        task (str): The task type (e.g., 'detect', 'segment', 'classify').

    Returns:
        (tuple): A tuple containing the TuneBOHB searcher and fixed parameter space dict.

    Raises:
        ImportError: If required BOHB packages are not installed.
    r   )r7   max)rL   metricmode)r    ray.tune.search.bohb.bohb_searchr7   r   )rL   rX   r   r   r7   s        r#   _create_bohb_searchr      sK     7u==B9999998"[%6UCCCEVVVr%   c                    t          j        t          d                    ddl}ddlm}  ||j        j        t          |          d          S )a3  Create a Nevergrad searcher with a default optimizer.

    Args:
        task (str): The task type (e.g., 'detect', 'segment', 'classify').

    Returns:
        (NevergradSearch): The configured Nevergrad search algorithm.

    Raises:
        ImportError: If the 'nevergrad' package is not installed.
    r   r   N)NevergradSearchr   )	optimizerr   r   )	r   rH   rI   r   ray.tune.search.nevergradr   
optimizers
OnePlusOner   )rX   ngr   s      r#   _create_nevergrad_searchr      s\     9+FGGG999999?R]%=kRVFW^cddddr%   c                    t          j        t          d                    ddlm} ddlm} ddlm}  || d          } ||          \  }}}d |D             }|	                    |           }||fS )	aZ  Convert a Tune search space into ZOOpt-compatible dimensions and fixed-only Tune param_space.

    Args:
        space (dict): The hyperparameter search space.

    Returns:
        (tuple): A tuple containing the ZOOpt dimension dict and fixed parameter space dict.

    Raises:
        ImportError: If the 'zoopt' package is not installed.
    r   r   ra   r8   rc   Tre   c                T    i | ]%\  }}d                      d |D                       |&S )rg   c              3  4   K   | ]}t          |          V  d S r*   ri   rj   s     r#   r+   z9_convert_zoopt_search_space.<locals>.<dictcomp>.<genexpr>   rs   r%   rt   rv   s      r#   r$   z/_convert_zoopt_search_space.<locals>.<dictcomp>   rx   r%   )
r   rH   rI   rz   rb   ray.tune.search.zooptr8   r{   rd   rK   )	rL   rb   r8   rd   r   r   _r   dim_dicts	            r#   _convert_zoopt_search_spacer      s     9'BCCCAAAAAA111111++++++!\%4@@@N)/.99M1a``R_```//66H&&&r%   c                l    t          |           \  }}ddlm}  |d||t          |         d          |fS )a  Create a ZOOpt searcher with required budget and converted search space.

    Args:
        space (dict): The hyperparameter search space.
        task (str): The task type (e.g., 'detect', 'segment', 'classify').
        iterations (int): The maximum number of trials (budget) for ZOOpt.

    Returns:
        (tuple): A tuple containing the ZOOptSearch searcher and fixed parameter space dict.

    Raises:
        ImportError: If the 'zoopt' package is not installed.
    r   r   asracosr   )algobudgetr   r   r   )r   r   r8   r   )rL   rX   
iterationsr   r   r8   s         r#   _create_zoopt_searchr      s\     #>e"D"DH111111;zH[QUEV]b   r%   c                   | d|dfS t          |           }t          | t                    rX|sd|dfS |t          vr=d                    t          t                              }t          d|  d| d          |dk    rd||fS 	 |dk    r<t          | t                    rt          ||          i |fS t          |           | i |fS |dk    rBt          | t                    rt          ||          \  }}nt          |          \  }}| }|||fS |d	k    rt          |          ||fS |d
k    rCt          | t                    rt          |||          \  }}nt          |          \  }}| }|||fS t          | t                    s| |dfS t          |         }	|	rt          j        |	           ddlm}
  |
|t$          |         d          ||fS # t&          t(          f$ r}t)          d|  d|           |d}~ww xY w)a  Resolve search algorithms and normalize Tune param_space for known Ray Tune searchers.

    Args:
        search_alg (str | object | None): The search algorithm to use. Can be a string name, a pre-instantiated Ray Tune
            searcher object, or None for default behavior.
        task (str): The task type (e.g., 'detect', 'segment', 'classify').
        space (dict): The hyperparameter search space.
        iterations (int): The maximum number of trials to run.

    Returns:
        (tuple): A tuple containing (resolved_search_alg, tuner_param_space, resolved_search_alg_kind).
            - resolved_search_alg: The configured searcher or None.
            - tuner_param_space: The normalized parameter space for the tuner.
            - resolved_search_alg_kind: The normalized algorithm name or None.

    Raises:
        ValueError: If an unsupported search_alg string is provided.
        ModuleNotFoundError: If required dependencies for the chosen algorithm are not installed.
    Nz, z!Unsupported Ray Tune search_alg 'z'. Supported values: rp   r   r   r   r   r   r   )create_searcherr   )r   r   zRay Tune search_alg 'z4' requires additional dependencies. Original error: )rE   r,   r9   rI   ru   sortedr|   rY   rM   r   r   r   r   r   r   rH   ray.tune.searchr   r   ImportErrorModuleNotFoundError)r@   rX   rL   r   rA   	supportedresolved_search_algtuner_param_spacer   requirementsr   es               r#   _resolve_ray_search_algr     s   ( UD  )*55J*c"" + 	%$$888		&)D"E"EFFInnnbknnnooo!!
**#*c** F(55r:EE%e,,,r:--*c** 19LUTX9Y9Y6#%6%6'A%'H'H$$&0#&(9:EE$$+D115*DD  *c** 19MeUY[e9f9f6#%6%6'B5'I'I$$&0#&(9:EE*c** 	+ud**2:> 	4%l333333333z+d2C%PPPRWYccc,-   !gJggdegg
 
	s?   -G 3G AG G 'AG 0G 
AG G; G66G;
   rL   dict | Nonegrace_periodintgpu_per_trial
int | Noner   c                N   t          j        d           	 t          j        ddg           ddlddlm ddlm} dd	lm	}m
}	 n# t          $ r t          d
          w xY w	 ddl}
t          |
d          sJ n# t          t          f$ r d}
Y nw xY wt          j        j        dd           i d                    dd          d                    dd          d                    dd          d                    dd          d                    dd          d                    dd          d                    dd          d                     d!d"          d#                    dd          d$                    d%d&          d'                    dd!          d(                    dd)          d*                    dd)          d+                    dd,          d-                    dd)          d.                    dd          d/                    dd0                              dd                              dd                              dd                              dd                              dd                              dd                              dd                              dd                              dd1          d2	}| j        }                    |                               d3d4          fd5}|s+                    d6          s|}t          j        d7                               d8t0          |                   }||d8<   d8vrt          j        d9| d:           t3          ||||          \  }}}                    |t6          |pdd;          }                    d<          pt8          d<         pd=} |d>t:          |         d?|t=          ||          d@A          }|dBk    r |	d>t:          |         d?|d@C          }t?          tA          tB          i dD"                    d6d          i          "                    d3d4          E          }|#                    dFdFG           j$        %                    |          rRt          j        tM          dH           dI| dJ           j$        '                    tQ          |          |dFK          }nH$                    ||)                    |||dL dM N           ||j*        |j+        O          P          }|,                                 |-                                }.                                 |S )Qa  Run hyperparameter tuning using Ray Tune.

    Args:
        model (YOLO): Model to run the tuner on.
        space (dict, optional): The hyperparameter search space. If not provided, uses default space.
        grace_period (int, optional): The grace period in epochs of the ASHA scheduler.
        gpu_per_trial (int, optional): The number of GPUs to allocate per trial.
        iterations (int, optional): The maximum number of trials to run.
        search_alg (str | ray.tune.search.Searcher | ray.tune.search.SearchAlgorithm, optional): Search algorithm to
            use. Strings are resolved to supported Ray Tune searchers. Pre-instantiated objects are reused, and known
            searchers with special Tune param_space requirements are normalized automatically.
        **train_args (Any): Additional arguments to pass to the `train()` method.

    Returns:
        (ray.tune.ResultGrid): A ResultGrid containing the results of the hyperparameter search.

    Examples:
        >>> from ultralytics import YOLO
        >>> model = YOLO("yolo26n.pt")  # Load a YOLO26n model

        Start tuning hyperparameters for YOLO26n training on the COCO8 dataset
        >>> result_grid = model.tune(data="coco8.yaml", use_ray=True)
    uN   💡 Learn about RayTune at https://docs.ultralytics.com/integrations/ray-tunez	ray[tune]zpydantic>=2.0,<2.12)	constrainr   N)tune)	RunConfig)ASHASchedulerHyperBandForBOHBzHRay Tune required but not found. To install run: pip install "ray[tune]"__version__Fz>=2.0.0raylr0gh㈵>g{Gz?lrfg      ?momentumgffffff?g\(\?weight_decayg        gMbP?warmup_epochsg      @warmup_momentumgffffff?boxg      4@rB   g?g      @cls_pwdflg?g      (@hsv_hhsv_sg?hsv_vdegreesg     F@	translatescaleshearg      $@   )	perspectiveflipudfliplrbgrmosaicmixupcutmix
copy_pasteclose_mosaicrD   r   c                                                  }d|_        |                                 t          t	          |                     } |                                	 	                                }d|v r|                    d          d         n|} d| | d<   n# t          $ r | d<   Y nw xY w |j	        di | }|j
        S )zKTrain the YOLO model with the specified hyperparameters and return results.Nr   rD   r   )gettrainerreset_callbacksr   r   updateget_trial_idsplit	Exceptiontrainresults_dict)
configmodel_to_traintrial_idtrial_suffixresults	base_namemodel_in_storer   
train_argsr   s
        r#   _tunezrun_ray_tune.<locals>._tune  s    00!%&&(((%d6ll33j!!!	'((**H69Xoo8>>#..r228L )::L::F6NN 	' 	' 	'&F6NNN	' '.&0000##s   $?B$ $B65B6resumez6Search space not provided, using default search space.dataz'Data not provided, using default "data=z".)cpugpuepochsd   epochr      )	time_attrr   r   max_tr   reduction_factorr   )r   r   r   r   r   exist_ok)rD   T)parentsr   zTuner: z Resuming tuning run z...)	trainableresume_erroredc                $    | j          d| j         S Nr   trainable_namer   trials    r#   <lambda>zrun_ray_tune.<locals>.<lambda>  s    E4H1[1[5>1[1[ r%   c                $    | j          d| j         S r  r  r  s    r#   r  zrun_ray_tune.<locals>.<lambda>  s    u7K4^4^en4^4^ r%   )r@   	schedulernum_samplestrial_name_creatortrial_dirname_creator)storage_pathrD   )param_spacetune_config
run_config)/r
   infor   rH   r   r   ray.tuner   ray.tune.schedulersr   r   r   r   wandbhasattrAssertionErrorcheck_versionr   uniformrandintrX   putr   warningr   r   with_resourcesr   r	   r   minr   r   r   popmkdirTunercan_restorer   restorer9   
TuneConfigparentrD   fitget_resultsshutdown)modelrL   r   r   r   r@   r   r   r   r   r  default_spacerX   r   r   r   r   resolved_search_alg_kindtrainable_with_resourcesr   r
  tune_dirtunerr   r   r   r   r   s         `                 @@@@r#   run_ray_tuner/  N  s   @ K`aaan!+:O9PQQQQ


&&&&&&GGGGGGGGG n n n!"lmmmnum,,,,,,(    )U;;;t||D$'' 	t||D#&& 	DLLd++	
 	S%00 	c3// 	4<<T22 	t||C&& 	t||C%% 	$,,sC(( 	t||C&& 	c3'' 	c3'' 	c3'' 	4<<T**  	T\\#s++!" 	c4((#$ 	c4((%& ||C//,,sC((,,sC((||C%%,,sC((c3'',,sC((ll3,,Q++7  M> :DWWU^^Nvv..I$ $ $ $ $ $ $ $ $*  Q11 QOPPP >>&)D/22DE&MZIIIIJJJG^D%H HD*,D
  $225+VcVhgh:i:ijj NN8$$I(8(BIcE4 u--  I  6))$$t$
 
 
	 KzKj*..5*I*IJK	
 	
 ^^FF++  H NN4$N///zh'' 
x	**NNNNNOOO
""3x==<Tei"jj

$).#&#[#[&^&^ (   !yhoHMRRR  
 
 
IIKKK !!G LLNNNNs   /A A%)B   BB)r   r   )Nr   Nr   N)rL   r   r   r   r   r   r   r   )
__future__r   numpyr0   ultralytics.cfgr   r   r   r   ultralytics.utilsr   r	   r
   r   r   r   rI   r   rE   rM   rY   r   r   r   r   r   r   r/  r   r%   r#   <module>r4     s   # " " " " "     I I I I I I I I I I I I b b b b b b b b b b b b b b b b 
.=)
 
    ,  60 0 0&) ) )66! 6! 6!rW W W(e e e(' ' '2  .D D DR  $r r r r r r rr%   