o
    Wht                  	   @   s  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 d dlmZ d dlZd dlZd dlmZ d dlmZ d dlm  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# d d	l$m%Z% zd dl&Z&W n e'y   dZ&Y nw e%ejd
Z(e%ejdZ)e%ejdZ*e%ejdZ+e%e!dZ,e%e!dZ-e%e!dZ.e%e!dZ/e"re%ejdre0d ede1fddZ2dd Z3dgde4de5fddZ6dd Z7d d! Z8dhd%d&Z9d'd( Z:d)d* Z;d+d, Z<did.d/Z=d0d1 Z>d2d3 Z?d4d5 Z@djd6d7ZAdjd8d9ZBd:d; ZCdkd>d?ZDdldAdBZEdCdD ZFdmdEdFZGdGdH ZHdIdJ ZIdndMdNZJdodOdPZKdQdR ZLG dSdT dTZMdpdVee5ef dWe5dXeNdYeNfdZd[ZOd\d] ZPedqd^d_ZQdrdadbZRG dcdd ddZSG dedf dfejTZUdS )s    N)contextmanager)deepcopy)datetime)Path)Union)__version__)DEFAULT_CFG_DICTDEFAULT_CFG_KEYSLOGGERNUM_THREADSPYTHON_VERSIONTORCHVISION_VERSIONWINDOWScolorstr)check_versionz1.9.0z1.13.0z2.0.0z2.4.0z0.10.0z0.11.0z0.13.0z0.18.0z==2.4.0zKnown issue with torch==2.4.0 on Windows with CPU, recommend upgrading to torch>=2.4.1 to resolve https://github.com/ultralytics/ultralytics/issues/15049
local_rankc                 c   s    t  ot  }|ot  dk}|r$| dvr$|r t j| gdnt   dV  |r<| dkr>|r6t j| gdnt   dS dS dS )zjEnsures all processes in distributed training wait for the local master (rank 0) to complete a task first.nccl>   r   )
device_idsNr   )distis_availableis_initializedget_backendbarrier)r   initializeduse_ids r   Q/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/utils/torch_utils.pytorch_distributed_zero_first6   s    r   c                  C   s   dd } | S )zXApplies torch.inference_mode() decorator if torch>=1.9.0 else torch.no_grad() decorator.c                 S   s,   t rt r| S t rtj | S tj | S )zNApplies appropriate torch decorator for inference mode based on torch version.)	TORCH_1_9torchis_inference_mode_enabledinference_modeno_grad)fnr   r   r   decorateF   s   z&smart_inference_mode.<locals>.decorater   )r%   r   r   r   smart_inference_modeC   s   r&   cudaenableddevicec                 C   s"   t r
tjj|| dS tjj| S )a]  
    Get the appropriate autocast context manager based on PyTorch version and AMP setting.

    This function returns a context manager for automatic mixed precision (AMP) training that is compatible with both
    older and newer versions of PyTorch. It handles the differences in the autocast API between PyTorch versions.

    Args:
        enabled (bool): Whether to enable automatic mixed precision.
        device (str, optional): The device to use for autocast. Defaults to 'cuda'.

    Returns:
        (torch.amp.autocast): The appropriate autocast context manager.

    Notes:
        - For PyTorch versions 1.13 and newer, it uses `torch.amp.autocast`.
        - For older versions, it uses `torch.cuda.autocast`.

    Examples:
        >>> with autocast(enabled=True):
        ...     # Your mixed precision operations here
        ...     pass
    )r(   )
TORCH_1_13r    ampautocastr'   )r(   r)   r   r   r   r,   P   s   r,   c                  C   s   ddl m}  d| vrLz8ddl}d}| }||d |v r!|d n|d |v r+|d n|d d}|d	d
dd
dd
| d< W n	 tyK   Y nw | ddS )z=Return a string with system CPU information, i.e. 'Apple M2'.r   )PERSISTENT_CACHEcpu_infoN)	brand_rawhardware_rawarch_string_raw      unknownz(R) zCPU z@ )ultralytics.utilsr-   cpuinfoget_cpu_infogetreplace	Exception)r-   r7   kinfostringr   r   r   r8   m   s   8$r8   c                 C   s&   t j| }|j d|jd ddS )zGReturn a string with system GPU information, i.e. 'Tesla T4, 15102MiB'., i   z.0fMiB)r    r'   get_device_propertiesnametotal_memory)index
propertiesr   r   r   get_gpu_info~   s   rF   r5   FTc                 C   s  t | tjst| dst| dr| S dt dt dtj d}t|  } dD ]}| |d} q+| d	k}| d
v }|s@|rFdt	j
d< n_| r| dkrNd} d| v r_ddd | dD } t	j
dd}| t	j
d< tj r|tj t| dkst| tj dkrdnd}	td|  dtj  dtj  d| d|	 
|s|stj r| r| dnd}
t|
}|dkr|dk rtd|dkr|| dkrtd| d| d|| |  d|| | |  d | d!dt|d  }t|
D ]\}}||dkr
dn| d"| d#t| d$7 }qd%}n$|r5tr5tjj r5|d&t  d$7 }d'}n|d(t  d$7 }d	}|d)v rJtt |rYt|rT|n|  t|S )*a  
    Select the appropriate PyTorch device based on the provided arguments.

    The function takes a string specifying the device or a torch.device object and returns a torch.device object
    representing the selected device. The function also validates the number of available devices and raises an
    exception if the requested device(s) are not available.

    Args:
        device (str | torch.device, optional): Device string or torch.device object.
            Options are 'None', 'cpu', or 'cuda', or '0' or '0,1,2,3'. Defaults to an empty string, which auto-selects
            the first available GPU, or CPU if no GPU is available.
        batch (int, optional): Batch size being used in your model. Defaults to 0.
        newline (bool, optional): If True, adds a newline at the end of the log string. Defaults to False.
        verbose (bool, optional): If True, logs the device information. Defaults to True.

    Returns:
        (torch.device): Selected device.

    Raises:
        ValueError: If the specified device is not available or if the batch size is not a multiple of the number of
            devices when using multiple GPUs.

    Examples:
        >>> select_device("cuda:0")
        device(type='cuda', index=0)

        >>> select_device("cpu")
        device(type='cpu')

    Note:
        Sets the 'CUDA_VISIBLE_DEVICES' environment variable for specifying which GPUs to use.
    tpuintelzUltralytics u    🚀 Python-z torch- )zcuda:none()[]'rI   r5   cpu>   mps:0mpsz-1CUDA_VISIBLE_DEVICESr'   0,c                 S   s   g | ]}|r|qS r   r   .0xr   r   r   
<listcomp>   s    z!select_device.<locals>.<listcomp>Nr   z}See https://pytorch.org/get-started/locally/ for up-to-date torch install instructions if no CUDA devices are seen by torch.
zInvalid CUDA 'device=z' requested. Use 'device=cpu' or pass valid CUDA device(s) if available, i.e. 'device=0' or 'device=0,1,2,3' for Multi-GPU.

torch.cuda.is_available(): z
torch.cuda.device_count(): z%
os.environ['CUDA_VISIBLE_DEVICES']: 
r2   znAutoBatch with batch<1 not supported for Multi-GPU training, please specify a valid batch size, i.e. batch=16.z'batch=z"' must be a multiple of GPU count z. Try 'batch=z' or 'batch=z/', the nearest batch sizes evenly divisible by .zCUDA:z (z)
zcuda:0zMPS (rR   zCPU (>   rP   rR   )
isinstancer    r)   str
startswithr   r   lowerr:   osenvironjoinsplitr9   r'   r   device_countlenr
   r=   
ValueError	enumeraterF   	TORCH_2_0backendsrR   r8   set_num_threadsr   rstrip)r)   batchnewlineverbosesremoverP   rR   visibleinstalldevicesnspaceidargr   r   r   select_device   s   (!
"

.


ry   c                   C   s   t j r
t j  t S )zPyTorch-accurate time.)r    r'   r   synchronizetimer   r   r   r   	time_sync   s   

r|   c              
   C   s  t j| j| j| j| j| j| j| jdd	d
| jj}| j| jd}t|jt|j|j }|jt|||jj | jdu rXtj| jjd | jj| jjdn| j}|j|j|jt|j|j  }|jt||ddd|  |S )	z'Fuse Conv2d() and BatchNorm2d() layers.T)kernel_sizestridepaddingdilationgroupsbiasFr   Nr   )dtyper)   r2   )nnConv2din_channelsout_channelsr}   r~   r   r   r   requires_grad_toweightr)   viewr    diagdivsqrtepsrunning_varcopy_mmshaper   zerosr   mulrunning_meanreshape)convbn	fusedconvw_convw_bnb_convb_bnr   r   r   fuse_conv_and_bn   s.   

 
 (&r   c                 C   s  t j| j| j| j| j| j| j| j| j	dd	
d| jj}| j| jd}t|jt|j|j }|jt|||jj | jdu rWtj| jjd | jjdn| j}|j|j|jt|j|j  }|jt||ddd|  |S )z0Fuse ConvTranspose2d() and BatchNorm2d() layers.T)r}   r~   r   output_paddingr   r   r   Fr   Nr2   r)   )r   ConvTranspose2dr   r   r}   r~   r   r   r   r   r   r   r   r)   r   r    r   r   r   r   r   r   r   r   r   r   r   r   r   )deconvr   
fuseddconvw_deconvr   r   r   r   r   r   fuse_deconv_and_bn  s*   
 *(&r     c                 C   s,  |sdS t | }t| }tddd |  D }t|}|rddddd	d
dddddd
dddd}t| t|	 D ]y\}	\}
}|

dd}
|jj}t|jr| D ]<\}}t|	d|
 d| d|d
|jd| dtt|jd
| d| dt|j
ddd	 q^qEt|	d|
d|d
ddddtg d
dddddd	 qEt| |}t| ddd  rd nd}|rd!|d"d#nd}t| d$dpt| d%i d$d}t|j
d&d'pd(}t| d)| d*|d+d,|d+d-|d+d.|  ||||fS )/a  
    Print and return detailed model information layer by layer.

    Args:
        model (nn.Module): Model to analyze.
        detailed (bool, optional): Whether to print detailed layer information. Defaults to False.
        verbose (bool, optional): Whether to print model information. Defaults to True.
        imgsz (int | List, optional): Input image size. Defaults to 640.

    Returns:
        (Tuple[int, int, int, float]): Number of layers, parameters, gradients, and GFLOPs.
    Ncollectionsc                 s   s*    | ]\}}t |jd kr||fV  qdS )r   N)re   _modules)rW   rt   mr   r   r   	<genexpr>C     ( zmodel_info.<locals>.<genexpr>layerz>5rB   z>40typez>20gradientz>10
parametersz>12r   musigmazmodule_list.r5   z>5gr[   z>12gz>10.3gztorch.z>15Fr   -is_fusedc                   S   s   dS )NFr   r   r   r   r   <lambda>T  s    zmodel_info.<locals>.<lambda>z (fused)r?   .1fz GFLOPs	yaml_fileyamlyoloYOLOModelz summaryz: rU   z	 layers, z parameters, z
 gradients)get_num_paramsget_num_gradients
__import__OrderedDictnamed_modulesre   r
   r=   rg   itemsr:   	__class____name___parametersnamed_parametersrequires_gradnumelr]   listr   meanstdr   	get_flopsgetattrr9   r   stem)modeldetailedrn   imgszn_pn_glayersn_lhrv   mnr   mtpnpflopsfusedfsr   
model_namer   r   r   
model_info2  s4   4

hF
 2r   c                 C      t dd |  D S )z6Return the total number of parameters in a YOLO model.c                 s       | ]}|  V  qd S Nr   rV   r   r   r   r   ^      z!get_num_params.<locals>.<genexpr>sumr   r   r   r   r   r   \     r   c                 C   r   )zEReturn the total number of parameters with gradients in a YOLO model.c                 s   s    | ]
}|j r| V  qd S r   )r   r   rV   r   r   r   r   c  s    z$get_num_gradients.<locals>.<genexpr>r   r   r   r   r   r   a  r   r   c                 C   sp   | j jrddlm} || jg| jd d }|d nt| jt	t
| jdd}t	| jjd d|d< |S )	a[  
    Return model info dict with useful model information.

    Args:
        trainer (ultralytics.engine.trainer.BaseTrainer): The trainer object containing model and validation data.

    Returns:
        (dict): Dictionary containing model parameters, GFLOPs, and inference speeds.

    Examples:
        YOLOv8n info for loggers
        >>> results = {
        ...    "model/parameters": 3151904,
        ...    "model/GFLOPs": 8.746,
        ...    "model/speed_ONNX(ms)": 41.244,
        ...    "model/speed_TensorRT(ms)": 3.211,
        ...    "model/speed_PyTorch(ms)": 18.755,
        ...}
    r   )ProfileModelsr   z
model/name   )zmodel/parameterszmodel/GFLOPs	inferencezmodel/speed_PyTorch(ms))argsprofileultralytics.utils.benchmarksr   lastr)   popr   r   roundr   	validatorspeed)trainerr   resultsr   r   r   model_info_for_loggersf  s   r   c                 C   s  t sdS zt| } t|  }t|ts||g}zAt| dr(tt| j	 dnd}t
jd|jd ||f|jd}t jt| |gddd d	 d
 }||d  | |d  | W W S  ty   t
jd|jd g|R |jd}t jt| |gddd d	 d
  Y W S w  ty   Y dS w )a	  
    Calculate FLOPs (floating point operations) for a model in billions.

    Attempts two calculation methods: first with a stride-based tensor for efficiency,
    then falls back to full image size if needed (e.g., for RTDETR models). Returns 0.0
    if thop library is unavailable or calculation fails.

    Args:
        model (nn.Module): The model to calculate FLOPs for.
        imgsz (int | List[int], optional): Input image size. Defaults to 640.

    Returns:
        (float): The model FLOPs in billions.
            r~       r2   r   Finputsrn   r       eAr3   )thopde_parallelnextr   r\   r   hasattrmaxintr~   r    emptyr   r)   r   r   r;   )r   r   r   r~   imr   r   r   r   r     s&   
""  (r   c                 C   sj  t sdS t| } t|  }t|ts||g}z[t| dr'tt| j	 dndd }t
jd|jd ||f|jd}t
jjdd}| | W d	   n1 sPw   Y  td
d | D d }||d  | |d  | }W |S  ty   t
jd|jd g|R |jd}t
jjdd}| | W d	   n1 sw   Y  tdd | D d }Y |S w )a7  
    Compute model FLOPs using torch profiler (alternative to thop package, but 2-10x slower).

    Args:
        model (nn.Module): The model to calculate FLOPs for.
        imgsz (int | List[int], optional): Input image size. Defaults to 640.

    Returns:
        (float): The model's FLOPs in billions.
    r   r~   r   r3   r2   r   T)
with_flopsNc                 s       | ]}|j V  qd S r   r   rV   r   r   r   r         z0get_flops_with_torch_profiler.<locals>.<genexpr>r   r   c                 s   r  r   r  rV   r   r   r   r     r  )rh   r   r   r   r\   r   r   r   r   r~   r    r  r   r)   profilerr   r   key_averagesr;   )r   r   r   r~   r  profr   r   r   r   get_flops_with_torch_profiler  s.   
&
 
r
  c                 C   s`   |   D ])}t|}|tju rq|tju rd|_d|_q|tjtjtj	tj
tjhv r-d|_qdS )z*Initialize model weights to random values.gMbP?gQ?TN)modulesr   r   r   BatchNorm2dr   momentum	Hardswish	LeakyReLUReLUReLU6SiLUinplace)r   r   tr   r   r   initialize_weights  s   

r        ?r   c                    s   dkr| S | j dd \}}t| t| f}tj| |ddd} |s4 fdd||fD \}}tj| d	||d
  d	||d	  gddS )a  
    Scales and pads an image tensor, optionally maintaining aspect ratio and padding to gs multiple.

    Args:
        img (torch.Tensor): Input image tensor.
        ratio (float, optional): Scaling ratio. Defaults to 1.0.
        same_shape (bool, optional): Whether to maintain the same shape. Defaults to False.
        gs (int, optional): Grid size for padding. Defaults to 32.

    Returns:
        (torch.Tensor): Scaled and padded image tensor.
    r  r3   NbilinearF)sizemodealign_cornersc                 3   s&    | ]}t |     V  qd S r   )mathceilrV   gsratior   r   r     s   $ zscale_img.<locals>.<genexpr>r   r2   gS㥛?)value)r   r   Finterpolatepad)imgr  
same_shaper  r   wro   r   r  r   	scale_img  s   (r'  r   c                 C   sH   |j  D ]\}}t|r||vs|ds||v rqt| || qdS )a  
    Copies attributes from object 'b' to object 'a', with options to include/exclude certain attributes.

    Args:
        a (object): Destination object to copy attributes to.
        b (object): Source object to copy attributes from.
        include (tuple, optional): Attributes to include. If empty, all attributes are included. Defaults to ().
        exclude (tuple, optional): Attributes to exclude. Defaults to ().
    _N)__dict__r   re   r^   setattr)abincludeexcluder<   vr   r   r   	copy_attr  s
   
"r0  c                  C   sL   t rtdd ttjD d S tjjddd } dddd	d	d
| d	S )z
    Return the second-most recent ONNX opset version supported by this version of PyTorch, adjusted for maturity.

    Returns:
        (int): The ONNX opset version.
    c                 s   s(    | ]}d |v rt |dd V  qdS )symbolic_opset   N)r   )rW   r<   r   r   r   r     s   & z#get_latest_opset.<locals>.<genexpr>r2   r[   r      r2        )z1.12z1.11z1.10z1.9z1.8)r*   r   varsr    onnxproducer_versionrsplitr9   )versionr   r   r   get_latest_opset  s   r;  c                    s    fdd|   D S )ab  
    Returns a dictionary of intersecting keys with matching shapes, excluding 'exclude' keys, using da values.

    Args:
        da (dict): First dictionary.
        db (dict): Second dictionary.
        exclude (tuple, optional): Keys to exclude. Defaults to ().

    Returns:
        (dict): Dictionary of intersecting keys with matching shapes.
    c                    sD   i | ]\ } v rt  fd dD r|j  jkr |qS )c                 3   s    | ]}| vV  qd S r   r   rV   r<   r   r   r     r   z-intersect_dicts.<locals>.<dictcomp>.<genexpr>)allr   )rW   r/  dbr.  r<  r   
<dictcomp>  s   D z#intersect_dicts.<locals>.<dictcomp>)r   )dar?  r.  r   r>  r   intersect_dicts  s   rB  c                 C   s   t | tjjtjjfS )z
    Returns True if model is of type DP or DDP.

    Args:
        model (nn.Module): Model to check.

    Returns:
        (bool): True if model is DataParallel or DistributedDataParallel.
    )r\   r   parallelDataParallelDistributedDataParallelr   r   r   r   is_parallel"  s   
rF  c                 C   s   t | r| jS | S )z
    De-parallelize a model: returns single-GPU model if model is of type DP or DDP.

    Args:
        model (nn.Module): Model to de-parallelize.

    Returns:
        (nn.Module): De-parallelized model.
    )rF  moduler   r   r   r   r   /  s   
r   r   d   c                    s    fddS )a  
    Returns a lambda function for sinusoidal ramp from y1 to y2 https://arxiv.org/pdf/1812.01187.pdf.

    Args:
        y1 (float, optional): Initial value. Defaults to 0.0.
        y2 (float, optional): Final value. Defaults to 1.0.
        steps (int, optional): Number of steps. Defaults to 100.

    Returns:
        (function): Lambda function for computing the sinusoidal ramp.
    c                    s.   t dt| tj    d d   S )Nr2   r3   r   )r   r  cospirX   stepsy1y2r   r   r   H  s   . zone_cycle.<locals>.<lambda>r   )rN  rO  rM  r   rL  r   	one_cycle<  s   rP  c                 C   s   t |  tj |  t|  tj|  tj|  |rAtr:tjddd dtj	j
_dtjd< t| tjd< dS td dS t  dS )a  
    Initialize random number generator (RNG) seeds https://pytorch.org/docs/stable/notes/randomness.html.

    Args:
        seed (int, optional): Random seed. Defaults to 0.
        deterministic (bool, optional): Whether to set deterministic algorithms. Defaults to False.
    T)	warn_onlyz:4096:8CUBLAS_WORKSPACE_CONFIGPYTHONHASHSEEDz3Upgrade to torch>=2.0.0 for deterministic training.N)randomseednpr    manual_seedr'   manual_seed_allrh   use_deterministic_algorithmsri   cudnndeterministicr`   ra   r]   r
   warningunset_deterministic)rU  r[  r   r   r   
init_seedsK  s   




r^  c                   C   s4   t d dt jj_tjdd tjdd dS )zAUnsets all the configurations applied for deterministic training.FrR  NrS  )r    rY  ri   rZ  r[  r`   ra   r   r   r   r   r   r]  e  s   

r]  c                   @   s,   e Zd ZdZdddZdd ZdddZdS )ModelEMAa  
    Updated Exponential Moving Average (EMA) implementation.

    Keeps a moving average of everything in the model state_dict (parameters and buffers).
    For EMA details see References.

    To disable EMA set the `enabled` attribute to `False`.

    Attributes:
        ema (nn.Module): Copy of the model in evaluation mode.
        updates (int): Number of EMA updates.
        decay (function): Decay function that determines the EMA weight.
        enabled (bool): Whether EMA is enabled.

    References:
        - https://github.com/rwightman/pytorch-image-models
        - https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
    H.?  r   c                    sL   t t| | _|| _ fdd| _| j D ]}|d qd| _dS )au  
        Initialize EMA for 'model' with given arguments.

        Args:
            model (nn.Module): Model to create EMA for.
            decay (float, optional): Maximum EMA decay rate. Defaults to 0.9999.
            tau (int, optional): EMA decay time constant. Defaults to 2000.
            updates (int, optional): Initial number of updates. Defaults to 0.
        c                    s    dt |     S )Nr2   )r  exprK  decaytaur   r   r     s    z#ModelEMA.__init__.<locals>.<lambda>FTN)	r   r   evalemaupdatesrd  r   r   r(   )selfr   rd  re  rh  r   r   rc  r   __init__  s   

zModelEMA.__init__c                 C   st   | j r6|  jd7  _| | j}t| }| j  D ]\}}|jjr5||9 }|d| || 	  7 }qdS dS )zp
        Update EMA parameters.

        Args:
            model (nn.Module): Model to update EMA from.
        r2   N)
r(   rh  rd  r   
state_dictrg  r   r   is_floating_pointdetach)ri  r   rw   msdr<   r/  r   r   r   update  s   zModelEMA.updater   process_groupreducerc                 C   s   | j rt| j||| dS dS )aZ  
        Updates attributes and saves stripped model with optimizer removed.

        Args:
            model (nn.Module): Model to update attributes from.
            include (tuple, optional): Attributes to include. Defaults to ().
            exclude (tuple, optional): Attributes to exclude. Defaults to ("process_group", "reducer").
        N)r(   r0  rg  )ri  r   r-  r.  r   r   r   update_attr  s   	zModelEMA.update_attrN)r`  ra  r   )r   rp  )r   
__module____qualname____doc__rj  ro  rs  r   r   r   r   r_  m  s
    
r_  best.ptfro   rh  returnc              
   C   s  zt j| t dd}t|tsJ dd|v sJ dW n ty< } ztd|  d|  i W  Y d}~S d}~ww t	 
 td	d
d}|drS|d |d< t|d drdt|d j|d _t|d drpd|d _|d   |d  D ]}d|_q|i t|di }dD ]}d||< qd|d< dd | D |d< i |||pi }	t |	|p|  tj|p| d }
td|  d|rd| dnd d|
dd |	S )a  
    Strip optimizer from 'f' to finalize training, optionally save as 's'.

    Args:
        f (str | Path): File path to model to strip the optimizer from. Defaults to 'best.pt'.
        s (str, optional): File path to save the model with stripped optimizer to. If not provided, 'f' will be overwritten.
        updates (dict, optional): A dictionary of updates to overlay onto the checkpoint before saving.

    Returns:
        (dict): The combined checkpoint dictionary.

    Examples:
        >>> from pathlib import Path
        >>> from ultralytics.utils.torch_utils import strip_optimizer
        >>> for f in Path("path/to/model/checkpoints").rglob("*.pt"):
        >>>    strip_optimizer(f)
    rP   )map_locationz%checkpoint is not a Python dictionaryr   z'model' missing from checkpointz	Skipping z!, not a valid Ultralytics model: Nz2AGPL-3.0 License (https://ultralytics.com/license)zhttps://docs.ultralytics.com)dater:  licensedocsrg  r   	criterionF
train_args)	optimizerbest_fitnessrg  rh  r   epochc                 S   s   i | ]\}}|t v r||qS r   )r	   )rW   r<   r/  r   r   r   r@    s    z#strip_optimizer.<locals>.<dictcomp>g    .AzOptimizer stripped from rU   z
 saved as r5   rI   r   MB)r    loadr)   r\   dictr;   r
   r\  r   now	isoformatr   r9   r   r   r~  halfr   r   r   r   saver`   pathgetsizer=   )rx  ro   rh  rX   emetadatar   r   r<   combinedmbr   r   r   strip_optimizer  sB   



0r  c                 C   sT   | d   D ]!}| D ]\}}|dkr&t|tjr&|jtju r&| ||< qq| S )a  
    Converts the state_dict of a given optimizer to FP16, focusing on the 'state' key for tensor conversions.

    Args:
        state_dict (dict): Optimizer state dictionary.

    Returns:
        (dict): Converted optimizer state dictionary with FP16 tensors.
    statestep)valuesr   r\   r    Tensorr   float32r  )rk  r  r<   r/  r   r   r   $convert_optimizer_state_dict_to_fp16  s   
 r  c              	   c   sZ    t dd}tj r(tj  z|V  W tj| |d< dS tj| |d< w |V  dS )a`  
    Monitor and manage CUDA memory usage.

    This function checks if CUDA is available and, if so, empties the CUDA cache to free up unused memory.
    It then yields a dictionary containing memory usage information, which can be updated by the caller.
    Finally, it updates the dictionary with the amount of memory reserved by CUDA on the specified device.

    Args:
        device (torch.device, optional): The CUDA device to query memory usage for. Defaults to None.

    Yields:
        (dict): A dictionary with a key 'memory' initialized to 0, which will be updated with the reserved memory.
    r   )memoryr  N)r  r    r'   r   empty_cachememory_reserved)r)   	cuda_infor   r   r   cuda_memory_usage  s   


&
r  
   c                    s  g }t |tjst|}tdddddddddddd	d
d	 t  tj	  t | t
r6| n| gD ]  | d _t |t
rK|n|gD ]}t|dr[||n|}t|drrt  tjrr jtju rr| n|}ddg d}}}	ztrtjt| gddd d d nd}
W n ty   d}
Y nw z+zd}t|D ]}t|A}t |	d< | }t |	d< zt |t
rtdd |D n|   t |	d< W n ty   td|	d< Y nw W d   n1 sw   Y  ||d d 7 }||	d |	d  d | 7 }||	d |	d  d | 7 }|rZt|$}tj jd |tt fdd|j  D |tj!d W d   n	1 sMw   Y  ||d d 7 }qdd  |fD \}}t |t"j#rxtdd |$ D nd}t|d|
d |d!|d"|d"t%|d	t%|d	 |&||
|||||g W n ty } zt| |&d W Y d}~nd}~ww W t  tj	  qNt  tj	  w q9|S )#a;  
    Ultralytics speed, memory and FLOPs profiler.

    Args:
        input (torch.Tensor | List[torch.Tensor]): Input tensor(s) to profile.
        ops (nn.Module | List[nn.Module]): Model or list of operations to profile.
        n (int, optional): Number of iterations to average. Defaults to 10.
        device (str | torch.device, optional): Device to profile on. Defaults to None.
        max_num_obj (int, optional): Maximum number of objects for simulation. Defaults to 0.

    Returns:
        (list): Profile results for each operation.

    Examples:
        >>> from ultralytics.utils.torch_utils import profile
        >>> input = torch.randn(16, 3, 640, 640)
        >>> m1 = lambda x: x * torch.sigmoid(x)
        >>> m2 = nn.SiLU()
        >>> profile(input, [m1, m2], n=100)  # profile over 100 iterations
    Paramsz>12sGFLOPszGPU_mem (GB)z>14szforward (ms)zbackward (ms)inputz>24soutputTr   r  r   )r   r   r   Fr   r   r3   r2   c                 s   r   r   )r   )rW   yir   r   r   r   K  r   zprofile.<locals>.<genexpr>nanNr  i  c                 3   s,    | ]} j d  |  j d |  V  qdS )r   N)r   )rW   ro   rK  r   r   r   X  s   * )r)   r   c                 s   s*    | ]}t |tjrt|jnd V  qdS )r   N)r\   r    r  tupler   rV   r   r   r   r   ]  r   c                 s   r   r   r   rV   r   r   r   r   ^  r   12z12.4gz>14.3fz14.4g)'r\   r    r)   ry   r
   r=   gccollectr'   r  r   r   r   r   r  r   float16r  r   r   r   r;   ranger  r|   r   backwardfloatrandnr   r   r~   tolistr  r   Moduler   r]   append)r  opsrt   r)   max_num_objr   r   tftbr  r   memr(  r  ys_ins_outr   r  r   rK  r   r     s   

..


(

(<
-r   c                   @   s"   e Zd ZdZdddZdd ZdS )	EarlyStoppinga  
    Early stopping class that stops training when a specified number of epochs have passed without improvement.

    Attributes:
        best_fitness (float): Best fitness value observed.
        best_epoch (int): Epoch where best fitness was observed.
        patience (int): Number of epochs to wait after fitness stops improving before stopping.
        possible_stop (bool): Flag indicating if stopping may occur next epoch.
    2   c                 C   s$   d| _ d| _|ptd| _d| _dS )z
        Initialize early stopping object.

        Args:
            patience (int, optional): Number of epochs to wait after fitness stops improving before stopping.
        r   r   infFN)r  
best_epochr  patiencepossible_stop)ri  r  r   r   r   rj  u  s   
zEarlyStopping.__init__c              
   C   s   |du rdS || j ks| j dkr|| _|| _ || j }|| jd k| _|| jk}|rBtd}t| d| j d| j d| j d	 |S )
a  
        Check whether to stop training.

        Args:
            epoch (int): Current epoch of training
            fitness (float): Fitness value of current epoch

        Returns:
            (bool): True if training should stop, False otherwise
        NFr   r2   zEarlyStopping: z:Training stopped early as no improvement observed in last z( epochs. Best results observed at epoch z@, best model saved as best.pt.
To update EarlyStopping(patience=z^) pass a new patience value, i.e. `patience=300` or use `patience=0` to disable EarlyStopping.)r  r  r  r  r   r
   r=   )ri  r  fitnessdeltastopprefixr   r   r   __call__  s$   

zEarlyStopping.__call__N)r  )r   rt  ru  rv  rj  r  r   r   r   r   r  j  s    

r  c                       s(   e Zd ZdZ fddZdd Z  ZS )FXModela}  
    A custom model class for torch.fx compatibility.

    This class extends `torch.nn.Module` and is designed to ensure compatibility with torch.fx for tracing and graph
    manipulation. It copies attributes from an existing model and explicitly sets the model attribute to ensure proper
    copying.

    Attributes:
        model (nn.Module): The original model's layers.
    c                    s    t    t| | |j| _dS )z
        Initialize the FXModel.

        Args:
            model (nn.Module): The original model to wrap for torch.fx compatibility.
        N)superrj  r0  r   )ri  r   r   r   r   rj    s   

zFXModel.__init__c                    s\   g | j D ]&}|jdkr"t|jtr|j n
 fdd|jD  |    q S )aa  
        Forward pass through the model.

        This method performs the forward pass through the model, handling the dependencies between layers and saving
        intermediate outputs.

        Args:
            x (torch.Tensor): The input tensor to the model.

        Returns:
            (torch.Tensor): The output tensor from the model.
        r   c                    s    g | ]}|d kr
 n| qS )r   r   )rW   jrX   r  r   r   rY     s     z#FXModel.forward.<locals>.<listcomp>)r   rx  r\   r   r  )ri  rX   r   r   r  r   forward  s   

,zFXModel.forward)r   rt  ru  rv  rj  r  __classcell__r   r   r  r   r    s    r  )r'   )r5   r   FT)FTr   )r   )r  Fr   )r   r   )r   )r   r  rH  )r   F)rw  r5   Nr   )r  Nr   )Vr  r  r`   rT  r{   
contextlibr   copyr   r   pathlibr   typingr   numpyrV  r    torch.distributeddistributedr   torch.nnr   torch.nn.functional
functionalr!  ultralyticsr   r6   r   r	   r
   r   r   r   r   r   ultralytics.utils.checksr   r   ImportErrorr   r*   rh   	TORCH_2_4TORCHVISION_0_10TORCHVISION_0_11TORCHVISION_0_13TORCHVISION_0_18r\  r   r   r&   boolr]   r,   r8   rF   ry   r|   r   r   r   r   r   r   r   r
  r  r'  r0  r;  rB  rF  r   rP  r^  r]  r_  r  r  r  r  r   r  r  r  r   r   r   r   <module>   s   (





f"
*
"
%"




$D<
Q6