
    jn                        d Z ddlm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
 ddlmZ ddlmZ ddlZddlZddlmZmZ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!  G d d          Z"dS )a5  
Module provides functionalities for hyperparameter tuning of the Ultralytics YOLO models for object detection, instance
segmentation, image classification, pose estimation, and multi-object tracking.

Hyperparameter tuning is the process of systematically searching for the optimal set of hyperparameters
that yield the best model performance. This is particularly crucial in deep learning models like YOLO,
where small changes in hyperparameters can lead to significant differences in model accuracy and efficiency.

Examples:
    Tune hyperparameters for YOLO26n on COCO8 at imgsz=640 and epochs=10 for 300 tuning iterations.
    >>> from ultralytics import YOLO
    >>> model = YOLO("yolo26n.pt")
    >>> model.tune(data="coco8.yaml", epochs=10, iterations=300, optimizer="AdamW", plots=False, save=False, val=False)
    )annotationsN)Counter)datetime)Path)CFG_INT_KEYSget_cfgget_save_dir)DEFAULT_CFGLOGGERYAML	callbackscolorstrremove_colorstr)check_requirements)
torch_load)plot_tune_resultsc                     e Zd ZdZedfdCdZdDdEdZdFdZdGdHdZe	d             Z
	 dIdJdZdKd Zd! ZdLd#ZdIdMd'ZdNd)Ze	dOd*            Ze	dPdQd.            ZedRd0            Ze	dSd3            Ze	dTdUd9            Z	 	 	 dVdWd=ZdXdYdBZdS )ZTuneraS  A class for hyperparameter tuning of YOLO models.

    The class evolves YOLO model hyperparameters over a given number of iterations by mutating them according to the
    search space and retraining the model to evaluate their performance. Supports both local NDJSON storage and
    distributed MongoDB Atlas coordination for multi-machine hyperparameter optimization.

    Attributes:
        space (dict[str, tuple]): Hyperparameter search space containing bounds and scaling factors for mutation.
        tune_dir (Path): Directory where evolution logs and results will be saved.
        tune_file (Path): Path to the NDJSON file where evolution logs are saved.
        args (SimpleNamespace): Configuration arguments for the tuning process.
        callbacks (dict): Callback functions to be executed during tuning.
        prefix (str): Prefix string for logging messages.
        mongodb (MongoClient): Optional MongoDB client for distributed tuning.
        collection (Collection): MongoDB collection for storing tuning results.

    Methods:
        _mutate: Mutate hyperparameters based on bounds and scaling factors.
        __call__: Execute the hyperparameter evolution across multiple iterations.

    Examples:
        Tune hyperparameters for YOLO26n on COCO8 at imgsz=640 and epochs=10 for 300 tuning iterations.
        >>> from ultralytics import YOLO
        >>> model = YOLO("yolo26n.pt")
        >>> model.tune(
        >>>     data="coco8.yaml",
        >>>     epochs=10,
        >>>     iterations=300,
        >>>     plots=False,
        >>>     save=False,
        >>>     val=False
        >>> )

        Tune with distributed MongoDB Atlas coordination across multiple machines:
        >>> model.tune(
        >>>     data="coco8.yaml",
        >>>     epochs=10,
        >>>     iterations=300,
        >>>     mongodb_uri="mongodb+srv://user:pass@cluster.mongodb.net/",
        >>>     mongodb_db="ultralytics",
        >>>     mongodb_collection="tune_results"
        >>> )

        Tune with custom search space:
        >>> model.tune(space={"lr0": (1e-5, 1e-2), "momentum": (0.7, 0.98)})
    N
_callbacksdict | Nonec                h   |                     dd          p@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'          }t          |(          | _        | j        j        | j        _        t          | j        | j        j        pd)*          | _        d+\  | j        _        | j        _        | j        _        | j        d,z  | _	        |pt          j                    | _
        t          d-          | _        t          j        |            d| _        |r|                     |||           t#          j        | j         d.| j         d/| j         d0           dS )1zInitialize the Tuner with configurations.

        Args:
            args (dict): Configuration for hyperparameter evolution.
            _callbacks (dict | None, optional): Callback functions to be executed during tuning.
        spaceNlr0)gh㈵>{Gz?lrf)r         ?momentum)gffffff?g\(\?g333333?weight_decay)        gMbP?warmup_epochs)r   g      @warmup_momentum)r   gffffff?box)r   g      4@cls)皙?      @cls_pw)r   r   dfl)g?g      (@hsv_h)r   r$   hsv_s)r   g?hsv_vdegrees)r   g     F@	translatescaleshear)r   g      $@)	perspectiveflipudfliplrbgrmosaicmixupcutmix
copy_pasteclose_mosaicmongodb_uri
mongodb_dbultralyticsmongodb_collectiontuner_results)	overridestunename)NFFztune_results.ndjsonzTuner: z*Initialized Tuner instance with 'tune_dir=z'
uT   💡 Learn about tuning at https://docs.ultralytics.com/guides/hyperparameter-tuning)popr   r   argsresumeexist_okr	   r@   tune_dir	tune_filer   get_default_callbacksr   prefixadd_integration_callbacksmongodb_init_mongodbr   info)selfrB   r   r8   r9   r;   s         [/var/www/html/Carbon-Document/venv/lib/python3.11/site-packages/ultralytics/engine/tuner.py__init__zTuner.__init__W   sv    XXgt,, 
 1
<1
 ;1
 (	1

 L1
 Z1
 {1
 ;1
 :1
 j1
 ;1
 Z1
 Z1
 Z1
 {1
  !1
" [#1
$ [%1
& (    $'71
 1
 1

: hh}d33XXlM::
!XX&:OLLd+++	!Y-	$TYTY^5MvNNN?S<		*DI,<)>>#Hy'F'H'Hy))+D111  	L{J8JKKK{ q qdm q q{q q q	
 	
 	
 	
 	
        uristrmax_retriesintc                   t          d           ddlm} ddlm}m} t          |          D ]}	  ||dddddd	d
d	  	        }|j                            d           t          j
        | j         d|dz    d           |c S # ||f$ rK ||dz
  k    r d|z  }t          j        | j         d|dz    d| d           t          j        |           Y w xY wdS )af  Create MongoDB client with exponential backoff retry on connection failures.

        Args:
            uri (str): MongoDB connection string with credentials and cluster information.
            max_retries (int): Maximum number of connection attempts before giving up.

        Returns:
            (MongoClient): Connected MongoDB client instance.
        pymongor   )MongoClient)ConnectionFailureServerSelectionTimeoutErrori0u  i N  i@  T   rR   i`  )serverSelectionTimeoutMSconnectTimeoutMSsocketTimeoutMSretryWrites
retryReadsmaxPoolSizeminPoolSizemaxIdleTimeMSpingz$Connected to MongoDB Atlas (attempt    )   z#MongoDB connection failed (attempt z), retrying in zs...N)r   rX   rY   pymongo.errorsrZ   r[   rangeadmincommandr   rL   rH   warningtimesleep)	rM   rS   rU   rY   rZ   r[   attemptclient	wait_times	            rN   _connectzTuner._connect   sj    	9%%%''''''QQQQQQQQ[)) 	& 	&G&$-2%*$) $# " !"'
 
 
 $$V,,,t{^^PWZ[P[^^^___%'BC & & &kAo--wJ	{rrwQR{rrclrrr   
9%%%%%&!	& 	&s   ABACCc                    |                      |          | _        | j        |         |         | _        | j                            dgd           t	          j        | j         d           dS )a  Initialize MongoDB connection for distributed tuning.

        Connects to MongoDB Atlas for distributed hyperparameter optimization across multiple machines. Each worker
        saves results to a shared collection and reads the latest best hyperparameters from all workers for evolution.

        Args:
            mongodb_uri (str): MongoDB connection string.
            mongodb_db (str, optional): Database name.
            mongodb_collection (str, optional): Collection name.

        Notes:
            - Creates a fitness index for fast queries of top results
            - Falls back to local NDJSON mode if connection fails
            - Uses connection pooling and retry logic for production reliability
        )fitnessT)
backgroundz*Using MongoDB Atlas for distributed tuningN)rs   rJ   
collectioncreate_indexr   rL   rH   )rM   r8   r9   r;   s       rN   rK   zTuner._init_mongodb   sj      }}[11,z23EF$$o%64$HHHt{NNNOOOOOrP      nreturnlistc                    	 t          | j                                                            dd                              |                    S # t
          $ r g cY S w xY w)zGet top N results from MongoDB sorted by fitness.

        Args:
            n (int): Number of top results to retrieve.

        Returns:
            (list[dict]): List of result documents with fitness scores and hyperparameters.
        ru   rv   )r}   rx   findsortlimit	Exception)rM   r{   s     rN   _get_mongodb_resultszTuner._get_mongodb_results   se    	,,..33IrBBHHKKLLL 	 	 	III	s   AA AAc                h    t          | d          r|                                 nt          |           S )z2Convert tensor-like values for JSON serialization.item)hasattrr   rT   )xs    rN   _json_defaultzTuner._json_default   s+     #1f--9qvvxxx3q669rP   	iterationru   floathyperparametersdict[str, float]datasetsdict[str, dict]	save_dirsdict[str, str] | Nonedictc                >    |t          |d          ||d}|r||d<   |S )z%Build one local tuning result record.rz   )r   ru   r   r   r   )round)rM   r   ru   r   r   r   results          rN   _result_recordzTuner._result_record   s?     #Wa((. 	
 
  	,"+F;rP   metricsc           	        	 | j                             |d |                                D             ||t          j                    |d           dS # t
          $ r)}t          j        | j         d|            Y d}~dS d}~ww xY w)a  Save results to MongoDB with proper type conversion.

        Args:
            fitness (float): Fitness score achieved with these hyperparameters.
            hyperparameters (dict[str, float]): Dictionary of hyperparameter values.
            metrics (dict): Complete training metrics dictionary (mAP, precision, recall, losses, etc.).
            datasets (dict[str, dict]): Per-dataset metrics for the iteration.
            iteration (int): Current iteration number.
        c                b    i | ],\  }}|t          |d           r|                                n|-S )r   )r   r   .0kvs      rN   
<dictcomp>z*Tuner._save_to_mongodb.<locals>.<dictcomp>
  s=    'w'w'wW[WXZ[68J8J,QAFFHHHPQ'w'w'wrP   )ru   r   r   r   	timestampr   zMongoDB save failed: N)	rx   
insert_oneitemsr   nowr   r   rm   rH   )rM   ru   r   r   r   r   es          rN   _save_to_mongodbzTuner._save_to_mongodb   s    "	EO&&&'w'w_n_t_t_v_v'w'w'w& (!)!* 	 	 	 	 	  	E 	E 	ENdkCCCCDDDDDDDDD	Es   AA 
BB  Bc                ~   	 t          | j                                                            dd                    }|sdS t	          | j        dd          5 }|D ]}|                    t          j        | 	                    |d         |d         pd|
                    d	i           |
                    d
i           |
                    d                    | j                  dz              	 ddd           dS # 1 swxY w Y   dS # t          $ r)}t          j        | j         d|            Y d}~dS d}~ww xY w)a  Sync MongoDB results to the local NDJSON tuning log.

        Downloads all results from MongoDB and writes them to the local NDJSON file in chronological order. This keeps
        resume, mutation, and plotting on the same local source of truth when using distributed tuning.
        r   rf   Nwutf-8encodingru   r   r   r   r   default
zMongoDB to NDJSON sync failed: )r}   rx   r   r   openrF   writejsondumpsr   getr   r   r   rm   rH   )rM   all_resultsfr   r   s        rN   _sync_mongodb_to_filezTuner._sync_mongodb_to_file  s   	Ot3355::;JJKKK dncG<<< )  FGG
 // &{ 3 &y 1 8S &

+<b A A &

:r : : &

; 7 7  %)$6	 	 	 
                       	O 	O 	ONdkMM!MMNNNNNNNNN	OsB   <D	  D	 BC</D	 <D  D	 D D	 	
D<D77D<
list[dict]c                    | j                                         sg S t          | j         d          5 }d |D             cddd           S # 1 swxY w Y   dS )z.Load local tuning results from the NDJSON log.r   r   c                ^    g | ]*}|                                 t          j        |          +S  )stripr   loads)r   lines     rN   
<listcomp>z-Tuner._load_local_results.<locals>.<listcomp>7  s/    CCCdjjllCDJt$$CCCrP   N)rF   existsr   )rM   r   s     rN   _load_local_resultszTuner._load_local_results2  s    ~$$&& 	I$.7333 	DqCCCCC	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	D 	Ds   AAAresults
int | Nonenp.ndarray | Nonec                     |sdS t          j         fd|D             t                    }||S t          j        |dddf                    }||         d|         S )zKConvert local NDJSON records to a fitness-plus-hyperparameters numpy array.Nc                j    g | ].                     d d          gfdj        D             z   /S )ru   r   c           	         g | ]?}                     d i                                |t          j        |                    @S r   )r   getattrrB   r   r   rrM   s     rN   r   z<Tuner._local_results_to_array.<locals>.<listcomp>.<listcomp>@  sE    bbbRS155*B//33Awty!7L7LMMbbbrP   )r   r   r   r   rM   s    @rN   r   z1Tuner._local_results_to_array.<locals>.<listcomp>>  sa         y#&&'bbbbbW[Wabbbc  rP   )dtyper   )nparrayr   argsort)rM   r   r{   r   orders   `    rN   _local_results_to_arrayzTuner._local_results_to_array9  s     	4H    !  
 
 
 
 9H
AaaadG8$$x|rP   r   c                    t          | j        dd          5 }|                    t          j        || j                  dz              ddd           dS # 1 swxY w Y   dS )z1Append one tuning result to the local NDJSON log.ar   r   r   r   N)r   rF   r   r   r   r   )rM   r   r   s      rN   _save_local_resultzTuner._save_local_resultJ  s    $.#888 	KAGGDJvt/ABBBTIJJJ	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	Ks   2AAAc                   |                      di           }t          |          dk    r.t          t          |                                                    S t          |          dk    rd |                                D             S dS )z*Summarize best-result metrics for logging.r   rf   c                `    i | ]+\  }}|t          |                    d           pdd          ,S )ru   r   rz   )r   r   r   s      rN   r   z'Tuner._best_metrics.<locals>.<dictcomp>V  s9    VVVTQAuQUU9--4a88VVVrP   N)r   lennextitervaluesr   )r   r   s     rN   _best_metricszTuner._best_metricsO  s|     ::j"--x==AX__..//000x==1VVX^^EUEUVVVVtrP   Frequire_allboolc                    |                      di           }t          |          oC|r!t          |                                          n t	          |                                          S )z9Return whether a tuning result contains training metrics.r   )r   r   allr   any)r   r   r   s      rN   _has_training_metricszTuner._has_training_metricsY  sY     ::j"--H~~e[#d3x'8'8#9#9#9cRZRaRaRcRcNdNderP   
np.ndarrayc                      fdt          |          D             }|r-|t          ||                                                            n t          |                                          S )zDReturn the best result index, preferring rows with training metrics.c                D    g | ]\  }}                     |          |S r   )r   )r   ir   r#   s      rN   r   z,Tuner._best_result_index.<locals>.<listcomp>b  s1    \\\yq&#:S:STZ:[:[\\\\rP   )	enumeraterV   argmax)r#   r   ru   valids   `   rN   _best_result_indexzTuner._best_result_index_  sf     ]\\\Ig$6$6\\\6;VuS..001122W^^EUEUAVAVVrP   data	list[str]c                    d | D             }t          |          t                      }}g }|D ]@}||xx         dz  cc<   |                    ||         dk    r| d||          n|           A|S )zGCreate stable unique dataset names for logging and per-run directories.c                P    g | ]#}t          t          |                    j        $S r   )r   rT   stem)r   ds     rN   r   z(Tuner._dataset_names.<locals>.<listcomp>h  s'    111qc!ff"111rP   rf   -)r   append)r   stemstotalsseennamesr   s         rN   _dataset_nameszTuner._dataset_namese  s     21D111u~~wyy 	O 	ODJJJ!OJJJLL6$<!3C3CD//4:///NNNNrP   皙?	   r   alphar   c                    t          |t                               } dddf          dddf                                          z
  dz   }t          j        |                                          r|                                dk    rt          j        |          }t          j        t          t                               ||          }t          j
         fd|D             d          }|                     d          |                    d          }}||z
  }t          j        |dk    t          j                            dd|j                  |          }t          j                            |||z  z
  |||z  z             S )uG   BLX-α crossover from up to top-k parents (x[:,0]=fitness, rest=genes).Nr   gư>)weightsr   c                0    g | ]}|         d d         S )rf   Nr   )r   r   r   s     rN   r   z$Tuner._crossover.<locals>.<listcomp>y  s%    777Q!QRR777rP   r   r$   )minr   r   isfiniter   sum	ones_likerandomchoicesrj   stackmaxwhereuniformshape)	r   r   r   r   idxsparents_matlohispans	   `        rN   
_crossoverzTuner._crossoverp  sO    3q66NNAAAqD'AaaadGKKMM)D0{7##'')) 	,W[[]]a-?-?l7++G~eCFFmmWBBBh7777$777;;##[__Q%7%7BBwx	29#4#4T3
#K#KTRRy  edl!2B4EFFFrP         ?mutationsigmac           
         d} j         r                     |          x}r!t          j         fd|D                       }nf j        j         j        j                                        v r<t          j        dg fd j        	                                D             z   g          }|) 
                                                     |          }|dt          j                                        }t           j                  }                     |          t          j        d  j                                        D                       }t          j        |          t          j        dk              r|                    |          |k     }	|                    |          ||z  z  }
t          j        |	t          j        |
          d                              d	d
          t          j        dk              fdt/           j        	                                          D             }n% fd j        	                                D             } j                                        D ]F\  }}t3          t5          t7          ||         |d                   |d                   d          ||<   Gd|v rt3          |d                   |d<   d|v rt3          |d                   |d<   |S )a  Mutate hyperparameters based on bounds and scaling factors specified in `self.space`.

        Args:
            n (int): Number of top parents to consider.
            mutation (float): Probability of a parameter mutation in any given iteration.
            sigma (float): Standard deviation for Gaussian random number generator.

        Returns:
            (dict[str, float]): A dictionary containing mutated hyperparameters.
        Nc                r    g | ]2d          gfdj                                         D             z   3S )ru   c                x    g | ]6}d                               |j                             |                    7S r   )r   rB   r   s     rN   r   z,Tuner._mutate.<locals>.<listcomp>.<listcomp>  s?    )s)s)s\]!,=*>*B*B1dimmTUFVFV*W*W)s)s)srP   )r   keysr   s    @rN   r   z!Tuner._mutate.<locals>.<listcomp>  s]        9)s)s)s)s)saeakapaparar)s)s)ss  rP   r   c                :    g | ]}t          j        |          S r   r   rB   r   r   rM   s     rN   r   z!Tuner._mutate.<locals>.<listcomp>  s%    &X&X&Xwty!'<'<&X&X&XrP   )r{   c                H    g | ]}t          |          d k    r|d         nd S )rR   rh   r   )r   )r   r   s     rN   r   z!Tuner._mutate.<locals>.<listcomp>  s.    XXXqc!ffkkaddsXXXrP   rf   r   g      ?r%   c                T    i | ]$\  }}|t          |         |         z            %S r   )r   )r   r   r   factorsgeness      rN   r   z!Tuner._mutate.<locals>.<dictcomp>  s4    \\\tq!1eE!Hwqz122\\\rP   c                <    i | ]}|t          j        |          S r   r  r  s     rN   r   z!Tuner._mutate.<locals>.<dictcomp>  s'    GGG1gdi++GGGrP   r   rz   r7   epochs)rJ   r   r   r   rx   r@   databaselist_collection_namesr   r  r   r   r   default_rngr   r
  r   onesr   standard_normalr  expclipr   r   r   r   r  )rM   r{   r  r  r   r   rngnggainsmaskstephypr   boundsr  r  s   `             @@rN   _mutatezTuner._mutate  s      < 
	[33A666w 	[H   !(    %)A)W)W)Y)YYYHse&X&X&X&XdjooFWFW&X&X&XXYZZ 9,,T-E-E-G-G1,MMA =)''))CTZB OOA&&E HXXDJDUDUDWDWXXXYYEgbkkG&A&& Lzz"~~0**2..%%-@(4s;;@@sKK &A&& L ]\\\\yIZIZ?[?[\\\CCGGGGTZ__5F5FGGGC ))++ 	F 	FIAv3s3q66!955vayAA1EECFF S  "'N(;"<"<Cs??!#h-00CM
rP   
   T
iterationscleanupc                  - t          j                     }| j                            dd           | j        dz                      dd           i }d}| j        r|                                  d}| j                                        rKt          |                                           }t          j
        | j         d| j         d|dz    d           t          ||          D ]	}t          |d	z  d
          }dd|z  z
  }	|                     |	          }
t          j
        | j         d|dz    d| d|
            i t          | j                  |
--                    d          }t%          |t&          t(          f          s|g}|                     |          }t          |          dk    rt-          t/          -                    gn-fd|D             }d |D             }i }g }i }t1          t3          ||                    D ]d\  }\  }}i }	 |-d<   t5          ||                   -d<   t7          d          j        ddg}g |dd -                                D             }t=          j        |d           ||         ||         dz                                  rdndz  }tA          |          d         }|}t          j!        d           tE          j#                     tH          j%        &                                 n4# tN          $ r'}t          j(        d|dz    d|            Y d }~nd }~ww xY w|||<   |)                    |*                    d!          pd"           ftW          |          t          |          z  }| ,                    |dz   ||
|d# t3          ||          D                       }| -                    |d$          r|dz  }d%}| j        rS| .                    ||
|||dz              |                                  | j/        0                    i           }||k    rd}n| 1                    |           |                                 }| 2                    |          }|d d df         }| 3                    ||          } ||          }!|dz   |z
  }"|!*                    d&i           }#| |k    }$|$r|rC|4                                D ].}%|%|#4                                vrtk          j6        |%d'           /t3          ||          D ]s\  }}&t          |          dk    r
| j        dz  n| j        dz  |z  }'|'                    dd           |&7                    d(          D ]}(tk          j8        |(|'           t|#}n|r|D ]}%tk          j6        |%d'           |#}ts          t5          | j                             ||"k    rd)})n|dk    rd*})n	d+| d|" d,})| -                    |!          }*| j         |dz    d| d-|) d.t          j                     |z
  d/d0	| j         d1tu          d2| j                   g}+|*r|+;                    | j         d3||           d4| dz    | j         d5| <                    |!           | j         d6t          |!*                    d7i                     dk    r
| j        dz  nd8 g           d=                    |+          },t          j
        d|,z              |*st          j(        | j         d9           nd: t3          | j>        ?                                || dd f                   D             }t          jA        | j        d;z  |t          |,C                    | j        d<                    dz   =           t          jD        | j        d;z             |r%t          j
        | j         d>| d?| d@            d S d S )Aa  Execute the hyperparameter evolution process when the Tuner instance is called.

        This method iterates through the specified number of iterations, performing the following steps:
        1. Sync MongoDB results to local NDJSON (if using distributed mode)
        2. Mutate hyperparameters using the best previous results or defaults
        3. Train a YOLO model with the mutated hyperparameters
        4. Log fitness scores and hyperparameters to MongoDB and/or NDJSON
        5. Track the best performing configuration across all iterations

        Args:
            iterations (int): The number of generations to run the evolution for.
            cleanup (bool): Whether to delete iteration weights to reduce storage space during tuning.
        T)parentsrD   r   r   zResuming tuning run z from iteration rf   z...g     r@r   r   r$   )r  zStarting iteration /z with hyperparameters: r   c                L    g | ] }t          t                    |           !S )r?   )r	   r   )r   r@   
train_argss     rN   r   z"Tuner.__call__.<locals>.<listcomp>  s.    ]]]tl7:#6#6TBBB]]]rP   c                    g | ]}|d z  S )r   r   )r   ss     rN   r   z"Tuner.__call__.<locals>.<listcomp>  s    ;;;Q1y=;;;rP   save_dirsysz-mzultralytics.cfg.__init__trainc              3  *   K   | ]\  }}| d | V  dS )=Nr   r   s      rN   	<genexpr>z!Tuner.__call__.<locals>.<genexpr>   s0      .Y.Yda!zzazz.Y.Y.Y.Y.Y.YrP   )checkzbest.ptzlast.pttrain_metricsz5training failure for hyperparameter tuning iteration r   Nru   r   c                4    i | ]\  }}|t          |          S r   )rT   )r   datasetr3  s      rN   r   z"Tuner.__call__.<locals>.<dictcomp>  s$    PPPZWa#a&&PPPrP   )r   Fr   )ignore_errorsz*.ptu   complete ✅u   complete (all failed) ❌z
complete (u    succeeded) ⚠️z iterations z (z.2fzs)zResults saved to boldzBest fitness=z observed at iteration zBest fitness metrics are zBest fitness model is r   z"not saved for multi-dataset tuningzKNo iterations produced training metrics; skipping best_hyperparameters.yamlc                d    i | ]-\  }}||t           v rt          |          nt          |          .S r   )r   rV   r   r   s      rN   r   z"Tuner.__call__.<locals>.<dictcomp>_  sE       EIQAl!2!2s1vvva  rP   zbest_hyperparameters.yamlz# )r   headerzTarget iterations (z) reached in MongoDB (z). Stopping.)Ern   rE   mkdirrJ   r   rF   r   r   r   r   rL   rH   rj   r   r)  varsrB   rA   
isinstancer}   tupler   r	   r   r   ziprT   
__import__
executabler   
subprocessrunr   ro   gccollecttorchcudaempty_cacher   errorr   r   r   r   r   r   rx   count_documentsr   r   r   r   shutilrmtreeglobcopy2r   r   extendr   joinr   r  r   saver   replaceprint).rM   r+  r,  t0best_save_dirsn_successfulstartr   fracsigma_imutated_hypr   dataset_namesr4  weights_dirr   all_fitnessdataset_metricsjr   r=  	metrics_ilaunchcmd	ckpt_filer   ru   r   stop_after_iterationtotal_mongo_iterationsr   r   best_idxbest_resultn_attemptedcurrent_best_save_dirsbest_is_currentr3  
weight_dirbest_weights_dirckptstatushas_valid_bestheader_linesrA  r1  s.                                                @rN   __call__zTuner.__call__  s	    Y[[D4888		"))$)FFF < 	)&&(((>  "" 	k002233EK4;iiDMii[`cd[diiijjjuj)) N	 N	Aq5y#&&DC$J&G ,,W,55KK4;ss1q5ss:ssfqssttt;DOO;{;J>>&))DdT5M22 v //55M t99>> gj112233]]]]}]]] 
 <;(;;;KGK O#,S}-E-E#F#F D D<Aw	g)*Jv&-0!-=-=Jz* #5))42F
 [FZGZ.Y.YjFVFVFXFX.Y.Y.YZCN3d3333 +AAQZ@Z?b?b?d?d2s))js tI *9 5 5o FI'G JqMMMJLLLJ**,,,,  g g gL!eYZ]^Y^!e!ebc!e!effffffffg ,5(""9==#;#;#BsCCCC+&&[)9)99G((APP3}h3O3OPPP F ))&d)CC "!#( | 0%%g{G_VWZ[V[\\\**,,,)-)H)H)L)L&)Z77+/(''/// ..00G,,W55A1gG..w@@H!(+Kq5E/K%0__["%E%E"&!mO 8 A+2244 A A$:$A$A$C$CCC"M!4@@@@+.}k+J+J = ='GZ58YY!^^	11YbIbelIl % %**4$*GGG * 7 7 = =T+;<<<<=!7 8! 9 9AM!488888!7 c$.11222 {**'""4TlTT[TTT!77DDN;bAbb
bbbb$)++XZJZbbbb;RR&$-1P1PRRL  ##;mmWX5Fmm_gjk_kmm;bbASAST_A`A`bb; N N8;KOOJXZ<[<[8\8\`a8a8a4=944  hLN N   YY|,,FKv&&&! H{ooo    MPQUQ[Q`Q`QbQbdefnpqprprfrdsMtMt   	M$??*6>>$+t+L+LMMPTT   
 
4=+FFGGG# {}}z}}Yo}}}   	UN	 N	s   C4L
M L;;M )r   r   )rQ   rR   )rS   rT   rU   rV   )rQ   rQ   rQ   )rz   )r{   rV   r|   r}   )N)r   rV   ru   r   r   r   r   r   r   r   r|   r   )
ru   r   r   r   r   r   r   r   r   rV   )r|   r   )r   r   r{   r   r|   r   )r   r   )r   r   r|   r   )F)r   r   r   r   r|   r   )r   r   ru   r   r|   rV   )r   r}   r|   r   )r   r   )r   r   r   r   r   rV   r|   r   )r   r  r   )r{   rV   r  r   r  r   r|   r   )r*  T)r+  rV   r,  r   )__name__
__module____qualname____doc__r
   rO   rs   rK   r   staticmethodr   r   r   r   r   r   r   r   r   classmethodr   r   r
  r)  rx  r   rP   rN   r   r   '   s9       - -^ (4 9
 9
 9
 9
 9
v&& && && && &&PP P P P*     : : \: ,0    &E E E E>O O O<D D D D    "K K K K
    \ f f f f \f
 W W W [W
    \ G G G G \G" 	@ @ @ @ @Dj j j j j j jrP   r   )#r|  
__future__r   rK  r   r   rR  rI  rn   collectionsr   r   pathlibr   numpyr   rM  ultralytics.cfgr   r   r	   ultralytics.utilsr
   r   r   r   r   r   ultralytics.utils.checksr   ultralytics.utils.patchesr   ultralytics.utils.plottingr   r   r   rP   rN   <module>r     sg    # " " " " " 				                                ? ? ? ? ? ? ? ? ? ? ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] 7 7 7 7 7 7 0 0 0 0 0 0 8 8 8 8 8 8E	 E	 E	 E	 E	 E	 E	 E	 E	 E	rP   