
    |hA                        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mZ d dlmZmZmZ d dlZd dlZd dlmZ d dlmZ d dlmc 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( d d
l)m*Z*  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      Z0 e(e$d      Z1 e(e$d      Z2e%r% e(ej:                  d      r e!jf                  d       ede4fd       Z5d Z6d?de7de8fdZ9e jt                  d        Z;e jt                  d        Z<d@dZ=d Z>d Z?d  Z@dAd!ZAd" ZBd# ZCd$ ZDdBd%ZEdBd&ZFd' ZGdCd(ZHdDd)ZId* ZJdEd+ZKd, ZLd- ZMdFd.ZNdGd/ZOd0 ZP G d1 d2      ZQdHd3ee8ef   d4e8d5ee8ef   d6ee8ef   fd7ZRd8 ZSedId9       ZTdJd:ZU G d; d<      ZV G d= d>ej                        ZXy)K    N)contextmanager)deepcopy)datetime)Path)AnyDictUnion)__version__)DEFAULT_CFG_DICTDEFAULT_CFG_KEYSLOGGERNUM_THREADSPYTHON_VERSIONTORCHVISION_VERSIONWINDOWScolorstr)check_version)
torch_loadz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              #   p  K   t        j                         xr t        j                         }|xr t        j                         dk(  }|r1| dvr-|rt        j                  | g      nt        j                          d |r4| dk(  r.|rt        j                  | g      nt        j                          yyyw)ziEnsure 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_idss      \/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/utils/torch_utils.pytorch_distributed_zero_firstr"   3   s      ##%?$*=*=*?K:d..0F:Gz018-dlln	zQ18-dlln '{s   B4B6c                      d } | S )zVApply torch.inference_mode() decorator if torch>=1.9.0 else torch.no_grad() decorator.c                     t         rt        j                         r| S  t        rt        j                         |       S t        j                         |       S )zLApply appropriate torch decorator for inference mode based on torch version.)	TORCH_1_9torchis_inference_mode_enabledinference_modeno_grad)fns    r!   decoratez&smart_inference_mode.<locals>.decorateC   s>    88:IKIE((KBOO5==KBOO     )r+   s    r!   smart_inference_moder.   @   s    P Or,   enableddevicec                     t         r!t        j                  j                  ||       S t        j                  j                  j                  |       S )aI  
    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.

    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autocastcuda)r/   r0   s     r!   r4   r4   M   s:    . yy!!&'!::zz~~&&w//r,   c                  J   ddl m}  d| vry	 ddl}d}|j                         }|j	                  |d   |v r|d   n|d   |v r|d   n|d   d      }|j                  d	d
      j                  dd
      j                  dd
      | d<   | j	                  dd      S # t        $ r Y w xY w)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.utilsr7   cpuinfoget_cpu_infogetreplace	Exception)r7   rA   kinfostrings        r!   rB   rB   j   s     3))	>A'')DXXaddlad!!RSTURVXabF+1>>%+D+L+LVUW+X+`+`aegi+jZ( 
I66  		s   A8B 	B"!B"c                     t         j                  j                  |       }|j                   d|j                  dz  ddS )zGReturn a string with system GPU information, i.e. 'Tesla T4, 15102MiB'., i   z.0fMiB)r&   r5   get_device_propertiesnametotal_memory)index
propertiess     r!   get_gpu_inforQ   |   s>     11%8Joob!8!8G!DS IMMr,   c                 f   t        | t        j                        st        |       j	                  d      r| S dt
         dt         dt        j
                   d}t        |       j                         } dD ]  }| j                  |d      }  d| v rd	d
l	m
} | j                  d      } |       j                  |j                  d      d      }t        t        |            D ],  }	||	   dk(  s|rt        |j!                  d	            nd||	<   . dj#                  d |D              } | dk(  }
| dv }|
s|rdt$        j&                  d<   nU| rR| dk(  rd} d| v r1dj#                  | j                  d      D cg c]  }|s|	 c}      } t$        j&                  j)                  dd      }| t$        j&                  d<   t        j*                  j-                         r9t        j*                  j/                         t        | j                  d            k\  st1        j2                  |       t        j*                  j/                         d	k(  rdnd}t5        d|  dt        j*                  j-                          dt        j*                  j/                          d| d| 
      |
s|st        j*                  j-                         r| r| j                  d      nd}t        |      }|dkD  rQ|dk  rt5        d| d|dz   d      |d	k\  r2||z  d	k7  r*t5        d | d!| d"||z  |z   d#||z  |z  |z    d$| d      dt        |      dz   z  }t7        |      D ]#  \  }	}||	d	k(  rdn| d%| d&t9        |	       d'z  }% d(}nW|rBt:        r<t        j<                  j>                  j-                         r|d)tA                d'z  }d*}n|d+tA                d'z  }d}|d,v rt        jB                  tD               |r't1        j2                  |r|n|jG                                t        j                  |      S c c}w )-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'. Auto-selects the first available GPU, or CPU if no GPU is available.
        batch (int, optional): Batch size being used in your model.
        newline (bool, optional): If True, adds a newline at the end of the log string.
        verbose (bool, optional): If True, logs the device information.

    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')

    Notes:
        Sets the 'CUDA_VISIBLE_DEVICES' environment variable for specifying which GPUs to use.
    )tpuintelzUltralytics u    🚀 Python-z torch- )zcuda:none()[]'rU   r?   z-1r   )GPUInfo,g?)countmin_memory_fractionc              3   &   K   | ]	  }|s|  y wNr-   ).0ps     r!   	<genexpr>z select_device.<locals>.<genexpr>   s     0a!0s   cpu>   mps:0mpsCUDA_VISIBLE_DEVICESr5   0Nz}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']: 
r<   zuAutoBatch with batch<1 not supported for Multi-GPU training, please specify a valid batch size multiple of GPU count z, i.e. batch=   .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 (rg   zCPU (>   re   rg   )$
isinstancer&   r0   str
startswithr
   r   lowerrD   ultralytics.utils.autodevicer\   splitselect_idle_gpur^   rangelenpopjoinosenvironrC   r5   r   device_countr   rG   
ValueError	enumeraterQ   	TORCH_2_0backendsrg   rB   set_num_threadsr   rstrip)r0   batchnewlineverbosesremover\   partsselectedire   rg   xvisibleinstalldevicesnspacedargs                       r!   select_devicer      s#   @ &%,,'3v;+A+ABR+S
{m=0@HYHYGZZ[\A[ F? ,+, v~8 S!9,,5;;t3DZ],^s5z" 	DAQx43;3x||A/a	D 0U00
E/C
$
$C
c-1

)*	VF&=XX&,,s*;AQqqABF**..!7>-3

)*

'')ejj.E.E.G3v||\_O`Ka.aKKN ::**,14 	  'x 00 16

0G0G0I/J/

0G0G0I/J8	)  suzz668'-&,,s#3Lq5qy OOPcQ^_`cd_d^eefh  zeai1n eW$FqcW\`aWadeWeVf g#qj1nq011`ab`ccdf  s1vz"g& 	LDAq!q&Be,E!B|A6GsKKA	L	u~~11>>@	u\^$C((	u\^$C((
nk*Aahhj1<<g Bs   6P.>P.c                      t         j                  j                         rt         j                  j                          t	        j                         S )zReturn PyTorch-accurate time.)r&   r5   r   synchronizetimer-   r,   r!   	time_syncr      s.    zz 

 99;r,   c           
      &   t        j                  | j                  | j                  | j                  | j
                  | j                  | j                  | j                  d      j                  d      j                  | j                  j                        }| j                  j                  | j                  d      }t        j                  |j                  j!                  t        j"                  |j$                  |j&                  z                     }|j                  j)                  t        j*                  ||      j                  |j                  j,                               | j.                  Wt        j0                  | j                  j,                  d   | j                  j2                  | j                  j                        n| j.                  }|j.                  |j                  j5                  |j6                        j!                  t        j"                  |j&                  |j$                  z               z
  }|j.                  j)                  t        j*                  ||j9                  dd            j9                  d      |z          |S )z'Fuse Conv2d() and BatchNorm2d() layers.T)kernel_sizestridepaddingdilationgroupsbiasFr   r   )dtyper0   r<   )nnConv2din_channelsout_channelsr   r   r   r   r   requires_grad_toweightr0   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_bns          r!   fuse_conv_and_bnr      s    			((;;LL]];;		
 
		DKK	   [[d//4F::biimmEJJrvv/F$GHID588D&166y7G7G7M7MNO
 99 	DKK%%a(0A0A$++J\J\]YY 
 77RYY]]2??377

2>>TVTZTZCZ8[\\DNN$r1(=>FFrJTQRr,   c                    t        j                  | j                  | j                  | j                  | j
                  | j                  | j                  | j                  | j                  d	      j                  d      j                  | j                  j                        }| j                  j                  | j                  d      }t        j                   |j                  j#                  t        j$                  |j&                  |j(                  z                     }|j                  j+                  t        j,                  ||      j                  |j                  j.                               | j0                  Bt        j2                  | j                  j.                  d   | j                  j                        n| j0                  }|j0                  |j                  j5                  |j6                        j#                  t        j$                  |j(                  |j&                  z               z
  }|j0                  j+                  t        j,                  ||j9                  dd            j9                  d      |z          |S )z0Fuse ConvTranspose2d() and BatchNorm2d() layers.T)r   r   r   output_paddingr   r   r   Fr   r<   r0   )r   ConvTranspose2dr   r   r   r   r   r   r   r   r   r   r   r0   r   r&   r   r   r   r   r   r   r   r   r   r   r   r   r   )deconvr   
fuseddconvw_deconvr   r   r   s          r!   fuse_deconv_and_bnr     s    	**==NN!00__==
	
 
		FMM  	! " }}!!&"5"5r:H::biimmEJJrvv/F$GHIDEHHT8499*:K:K:Q:QRS RXQ\Q\QdU[[,,Q/8L8LMjpjujuF77RYY]]2??377

2>>TVTZTZCZ8[\\DOO%((4A)>?GGKdRSr,   c                 ,   |syt        |       }t        |       }t        d      j                  d | j	                         D              }t        |      }|rdddddd	d
ddddd	dddd}t        j                  |       t        |j                               D ]A  \  }	\  }
}|
j                  dd      }
|j                  j                  }t        |j                        r|j                         D ]  \  }}t        j                  |	d|
 d| d|d	|j                  d|j!                         dt#        t%        |j&                              d	|j)                         d|j+                         dt#        |j,                        j                  dd      d	        	t        j                  |	d|
d|d	ddddt#        g       d	dddddd	       D t/        | |      } t1        | dd              rdnd}|rd|d d!nd}t1        | d"d      xs t1        | d#i       j3                  d"d      }t5        |      j6                  j                  d$d%      xs d&}t        j                  | 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.
        verbose (bool, optional): Whether to print model information.
        imgsz (int | list, optional): Input image size.

    Returns:
        n_l (int): Number of layers.
        n_p (int): Number of parameters.
        n_g (int): Number of gradients.
        flops (float): GFLOPs.
    Ncollectionsc              3   \   K   | ]$  \  }}t        |j                        d k(  s||f & yw)r   N)ru   _modules)rb   r   ms      r!   rd   zmodel_info.<locals>.<genexpr>Q  s-     2tda_bcdcmcm_nrs_sAq62ts    ,	,layerz>5rM   z>40typez>20gradientz>10
parametersz>12r   musigmazmodule_list.r?   z>5grl   z>12gz>10.3gztorch.z>15Fr   -is_fusedc                       y)NFr-   r-   r,   r!   <lambda>zmodel_info.<locals>.<lambda>b  s    r,   z (fused)rJ   .1fz GFLOPs	yaml_fileyamlyoloYOLOModelz summaryz: r]   z	 layers, z parameters, z
 gradients)get_num_paramsget_num_gradients
__import__OrderedDictnamed_modulesru   r   rG   r|   itemsrD   	__class____name___parametersnamed_parametersrequires_gradnumelrn   listr   meanstdr   	get_flopsgetattrrC   r   stem)modeldetailedr   imgszn_pn_glayersn_lhr   mnr   mtpnrc   flopsfusedfsr   
model_names                       r!   
model_infor   =  s4     

C
E
"C&222teFYFYF[2ttF
f+Crl6#,vcl:c2B<PSBTU\]`TabfgjaklstwkxyA#FLLN3 		uJAwANB/B%%B1==!//1 EBKKS'RD",s!3Bs8AOOc;RSTSZSZS\]aRbcfgklmlslsgtcuvybz{|  |B  |B  |D  EK  {L  MN  MR  MR  MT  U[  L\  ]`  ab  ah  ah  ]i  ]q  ]q  rz  |~  ]  @C  \D  E
 qgbXbXec]1T(3r7SV-X[\_W`adeh`ijmnqirst		u eU#EC'%]CEJ2E$)2eC[	 rB{B/b75&"3M3Q3QR]_a3bIi%%--ff=HJ
KK:,hugRAwiAwmTWXYSZZdegdhijS%r,   c                 B    t        d | j                         D              S )z6Return the total number of parameters in a YOLO model.c              3   <   K   | ]  }|j                           y wra   r   rb   r   s     r!   rd   z!get_num_params.<locals>.<genexpr>l  s     5Qqwwy5   sumr   r   s    r!   r   r   j  s    5%"2"2"4555r,   c                 B    t        d | j                         D              S )zEReturn the total number of parameters with gradients in a YOLO model.c              3   V   K   | ]!  }|j                   s|j                          # y wra   )r   r   r   s     r!   rd   z$get_num_gradients.<locals>.<genexpr>q  s     HQqwwyHs   ))r   r   s    r!   r   r   o  s    H%"2"2"4HHHr,   c                 x   | j                   j                  rHddlm}  || j                  g| j
                        j                         d   }|j                  d       n5t        | 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  lastr0   runrv   r   r   roundr   	validatorspeed)trainerr  resultss      r!   model_info_for_loggersr  t  s    ( ||>w~~FJJLQOL! !/w}} =!)GMM":A>
 */w/@/@/F/F{/SUV)WG%&Nr,   c                    	 ddl }|sy	 t        |       } t        | j	                               }t        |t              s||g}	 t        | d      r-t        t        | j                  j                               d      nd}t        j                  d|j                  d   ||f|j                        }|j                  t!        |       |gd	      d   d
z  dz  }||d   z  |z  |d   z  |z  S # t        $ r d}Y w xY w# t"        $ r] t        j                  d|j                  d   g||j                        }|j                  t!        |       |gd	      d   d
z  dz  cY S w xY w# t"        $ r Y yw xY 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, optional): Input image size.

    Returns:
        (float): The model FLOPs in billions.
    r   N        r       r<   r   Finputsr       eAr=   )thopImportErrorde_parallelnextr   rm   r   hasattrmaxintr   r&   emptyr   r0   r  r   rE   )r   r   r  rc   r   imr   s          r!   r   r     sv    E"!!#$%&ENE		Z9@9QSU\\--/0"5WYFaVV<QXXNBLL%"uLMaPSVVYZZE58#f,uQx7&@@!  "  	Za4e4QXXFB<<e<LQORUUXYYY	Z  sB   C+ 8E% B'C< +C98C9<A#E"E% !E""E% %	E10E1c                    t         syt        |       } t        | j                               }t	        |t
              s||g}	 t        | d      r-t        t        | j                  j                               d      nddz  }t        j                  d|j                  d   ||f|j                        }t        j                  j                  d      5 } | |       d	d	d	       t!        d
 j#                         D              dz  }||d   z  |z  |d   z  |z  }|S # 1 sw Y   BxY w# t$        $ r t        j                  d|j                  d   g||j                        }t        j                  j                  d      5 } | |       d	d	d	       n# 1 sw Y   nxY wt!        d j#                         D              dz  }Y |S w xY w)a!  
    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, optional): Input image size.

    Returns:
        (float): The model's FLOPs in billions.
    r  r   r  r=   r<   r   T)
with_flopsNc              3   4   K   | ]  }|j                     y wra   r   r   s     r!   rd   z0get_flops_with_torch_profiler.<locals>.<genexpr>       9AGG9   r  r   c              3   4   K   | ]  }|j                     y wra   r$  r   s     r!   rd   z0get_flops_with_torch_profiler.<locals>.<genexpr>  r%  r&  )r}   r  r  r   rm   r   r  r  r  r   r&   r  r   r0   profilerr  r   key_averagesrE   )r   r   rc   r   r   profr   s          r!   get_flops_with_torch_profilerr+    s    EU AeT"@6=eX6N#c%,,**,-r2TVZ[[[[!QWWQZ8J^^##t#4 	"I	9T%6%6%899C?a 6)E!H4v= L	 	  @[[!QWWQZ0%0B^^##t#4 	"I	 	 	9T%6%6%899C?L@sD   BD' 	D?D' D$ D' 'AG	F	GF	*GGc                 Z   | j                         D ]  }t        |      }|t        j                  u r!|t        j                  u rd|_        d|_        B|t        j                  t        j                  t        j                  t        j                  t        j                  hv sd|_         y)z*Initialize model weights to random values.gMbP?gQ?TN)modulesr   r   r   BatchNorm2dr   momentum	Hardswish	LeakyReLUReLUReLU6SiLUinplace)r   r   ts      r!   initialize_weightsr7    sv    ]]_ G		>".. AEAJ2<<rww"''JJAIr,   c           	         dk(  r| S | j                   dd \  }}t        |z        t        |z        f}t        j                  | |dd      } |sfd||fD        \  }}t        j                  | d||d	   z
  d||d   z
  gd
      S )a  
    Scale and pad an image tensor, optionally maintaining aspect ratio and padding to gs multiple.

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

    Returns:
        (torch.Tensor): Scaled and padded image tensor.
          ?r=   NbilinearF)sizemodealign_cornersc              3   Z   K   | ]"  }t        j                  |z  z        z   $ y wra   )mathceil)rb   r   gsratios     r!   rd   zscale_img.<locals>.<genexpr>  s'     ?1		!e)b.)B.?s   (+r   r<   gS㥛?)value)r   r  Finterpolatepad)imgrB  
same_shaperA  r   wr   s    ` `   r!   	scale_imgrJ    s     |
99QR=DAq	QYQY(A
--!*E
JC?A?155q!ad(Aq1Q4x0>>r,   c                     |j                   j                         D ]7  \  }}t        |      r||vs|j                  d      s||v r+t	        | ||       9 y)a  
    Copy attributes from object 'b' to object 'a', with options to include/exclude certain attributes.

    Args:
        a (Any): Destination object to copy attributes to.
        b (Any): Source object to copy attributes from.
        include (tuple, optional): Attributes to include. If empty, all attributes are included.
        exclude (tuple, optional): Attributes to exclude.
    _N)__dict__r   ru   ro   setattr)abincludeexcluderF   vs         r!   	copy_attrrT    sR     

  " 1LQg-!,,s2CqG|Aq!	r,   c                      t         r,t        d t        t        j                        D              dz
  S t        j                  j
                  j                  dd      d   } dddddd	j                  | 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              3   B   K   | ]  }d |v st        |dd         yw)symbolic_opset   N)r  )rb   rF   s     r!   rd   z#get_latest_opset.<locals>.<genexpr>   s#     R1<LPQ<Q3qv;Rs   	r<   rl   r      rX        )z1.12z1.11z1.10z1.9z1.8)r2   r  varsr&   onnxproducer_versionrsplitrC   )versions    r!   get_latest_opsetra    sg     RUZZ(8RRUVVVjj))00a8;GBr"EII'SUVVr,   c                     | j                         D ci c]?  \  }|v st        fd|D              s |j                  |   j                  k(  s=|A c}}S c c}}w )aQ  
    Return 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.

    Returns:
        (dict): Dictionary of intersecting keys with matching shapes.
    c              3   &   K   | ]  }|v 
 y wra   r-   )rb   r   rF   s     r!   rd   z"intersect_dicts.<locals>.<genexpr>2  s     :W!1A::Ws   )r   allr   )dadbrR  rF   rS  s      ` r!   intersect_dictsrg  &  sX      XXZssTQ17s:Ww:W7W\]\c\cgijkglgrgr\rAqDssss   AAAAc                 ~    t        | t        j                  j                  t        j                  j                  f      S )z
    Return 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.
    )rm   r   parallelDataParallelDistributedDataParallelr   s    r!   is_parallelrl  5  s*     ebkk668[8[\]]r,   c                 4    t        |       r| j                  S | S )z
    De-parallelize a model: return 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.
    )rl  moduler   s    r!   r  r  B  s     'u-5<<858r,   c                       fdS )aR  
    Return a lambda function for sinusoidal ramp from y1 to y2 https://arxiv.org/pdf/1812.01187.pdf.

    Args:
        y1 (float, optional): Initial value.
        y2 (float, optional): Final value.
        steps (int, optional): Number of steps.

    Returns:
        (function): Lambda function for computing the sinusoidal ramp.
    c                     t        dt        j                  | t        j                  z  z        z
  dz  d      z
  z  z   S )Nr<   r=   r   )r  r?  cospi)r   stepsy1y2s    r!   r   zone_cycle.<locals>.<lambda>[  s=    S!dhhq477{U':;;q@!DRPSUU r,   r-   )rt  ru  rs  s   ```r!   	one_cyclerv  O  s     VUr,   c                 .   t        j                  |        t        j                   j                  |        t        j                  |        t        j
                  j	                  |        t        j
                  j                  |        |rt        rft        j                  dd       dt        j                  j                  _        dt        j                  d<   t        |       t        j                  d<   yt        j                   d       yt#                y)z
    Initialize random number generator (RNG) seeds https://pytorch.org/docs/stable/notes/randomness.html.

    Args:
        seed (int, optional): Random seed.
        deterministic (bool, optional): Whether to set deterministic algorithms.
    T)	warn_onlyz:4096:8CUBLAS_WORKSPACE_CONFIGPYTHONHASHSEEDz3Upgrade to torch>=2.0.0 for deterministic training.N)randomseednpr&   manual_seedr5   manual_seed_allr}   use_deterministic_algorithmsr~   cudnndeterministicrx   ry   rn   r   warningunset_deterministic)r|  r  s     r!   
init_seedsr  ^  s     KKIINN4	d	JJ4 	JJt$..ttD15ENN  .4=BJJ01+.t9BJJ'(NNPQr,   c                      t        j                  d       dt         j                  j                  _        t
        j                  j                  dd       t
        j                  j                  dd       y)z@Unset all the configurations applied for deterministic training.Fry  Nrz  )r&   r  r~   r  r  rx   ry   rv   r-   r,   r!   r  r  x  sH    	&&u-).ENN&JJNN,d3JJNN#T*r,   c                   &    e Zd ZdZddZd ZddZy)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
    c                     t        t        |            j                         | _        || _        fd| _        | j                  j                         D ]  }|j                  d        d| _        y)a@  
        Initialize EMA for 'model' with given arguments.

        Args:
            model (nn.Module): Model to create EMA for.
            decay (float, optional): Maximum EMA decay rate.
            tau (int, optional): EMA decay time constant.
            updates (int, optional): Initial number of updates.
        c                 B    dt        j                  |  z        z
  z  S )Nr<   )r?  exp)r   decaytaus    r!   r   z#ModelEMA.__init__.<locals>.<lambda>  s     uDHHaR#X,>(>? r,   FTN)	r   r  evalemaupdatesr  r   r   r/   )selfr   r  r  r  rc   s     ``  r!   __init__zModelEMA.__init__  s^     K./446?
$$& 	$AU#	$r,   c                    | j                   r| xj                  dz  c_        | j                  | j                        }t        |      j	                         }| j
                  j	                         j                         D ]=  \  }}|j                  j                  s||z  }|d|z
  ||   j                         z  z  }? yy)zp
        Update EMA parameters.

        Args:
            model (nn.Module): Model to update EMA from.
        r<   N)
r/   r  r  r  
state_dictr  r   r   is_floating_pointdetach)r  r   r   msdrF   rS  s         r!   updatezModelEMA.update  s     <<LLAL

4<<(Ae$//1C++-335 3177,,FA!a%3q6==?22A3 r,   c                 N    | j                   rt        | j                  |||       yy)a  
        Update attributes and save stripped model with optimizer removed.

        Args:
            model (nn.Module): Model to update attributes from.
            include (tuple, optional): Attributes to include.
            exclude (tuple, optional): Attributes to exclude.
        N)r/   rT  r  )r  r   rQ  rR  s       r!   update_attrzModelEMA.update_attr  s"     <<dhhw8 r,   N)gH.?i  r   )r-   )process_groupreducer)r   
__module____qualname____doc__r  r  r  r-   r,   r!   r  r    s    &"3$
9r,   r  fr   r  returnc           	         	 t        | t        j                  d            }t        |t              sJ d       d|v sJ d       	 t        j                         j                         t        d	d
d}|j                  d      r|d   |d<   t        |d   d      r t	        |d   j                        |d   _        t        |d   d      r
d|d   _        |d   j!                          |d   j#                         D ]	  }d|_         i t&        |j                  di       }dD ]  }d||<   	 d|d<   |j)                         D 	ci c]  \  }}	|t*        v s||	 c}	}|d<   i |||xs i }
t        j,                  |
|xs |        t.        j0                  j3                  |xs |       dz  }t        j4                  d|  d|rd| dnd d|dd       |
S # t
        $ r'}t        j                  d|  d|        i cY d}~S d}~ww xY wc c}	}w )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.
        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)
    re   )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docsr  r  	criterionF
train_args)	optimizerbest_fitnessr  r  r   epochg    .AzOptimizer stripped from r]   z
 saved as r?   rU   r   MB)r   r&   r0   rm   dictrE   r   r  r   now	isoformatr
   rC   r  r  r  halfr   r   r   r   r   saverx   pathgetsizerG   )r  r   r  r   emetadatarc   r  rF   rS  combinedmbs               r!   strip_optimizerr    s   &qu||E':;!T"K$KK"!|>>>| ((*G.	H 	uuU|uX'
qz6"qz/'
qz;'#'
gJOOwZ""$    ;:!%%b"9:D: !AgJ(,

N1=M8Mq!tNAlO 4(3a3GMr3H	JJxa 	a	 3	&B
KK*1#QAA3a/@2.NaPRSVxWYZ[OG  1#%FqcJK	6 Os*   AG HH	HG?9H?Hc                    | d   j                         D ]k  }|j                         D ]V  \  }}|dk7  st        |t        j                        s'|j
                  t        j                  u sD|j                         ||<   X m | S )a
  
    Convert 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   rm   r&   Tensorr   float32r  )r  r  rF   rS  s       r!   $convert_optimizer_state_dict_to_fp16r    st     G$++- $KKM 	$DAqF{z!U\\:qww%--?W668a	$$
 r,   c              #   B  K   t        d      }t        j                  j                         rFt        j                  j	                          	 | t        j                  j                  |       |d<   y| y# t        j                  j                  |       |d<   w xY ww)aN  
    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.

    Yields:
        (dict): A dictionary with a key 'memory' initialized to 0, which will be updated with the reserved memory.
    r   )memoryr  N)r  r&   r5   r   empty_cachememory_reserved)r0   	cuda_infos     r!   cuda_memory_usager    sv      AIzz 

 	EO"'**"<"<V"DIh #(**"<"<V"DIhs   A	BA8 (B8$BBc                    	 ddl }g }t        |t        j                        st        |      }t        j                  ddddddddd	dd
ddd       t        j                          t        j                  j                          t        | t              r| n| gD ]  j                  |      d_        t        |t              r|n|gD ]  }t        |d      r|j                  |      n|}t        |d      rFt        t        j                         r,j"                  t        j$                  u r|j'                         n|}ddg d}
}	}	 |r'|j)                  t+        |      gd      d   dz  dz  nd}	 d}t/        |      D ]D  }t1        |      5 }t3               |
d<    |      }t3               |
d<   	 t        |t              rt5        d |D              n|j5                         j7                          t3               |
d<   ddd       |d   dz  z  }||
d   |
d   z
  dz  |z  z  }|	|
d   |
d   z
  dz  |z  z  }	|st1        |      5 }t        j:                  j<                  d   |t?        t5        fd|j@                  jC                         D                    |t        jD                         ddd       ||d   dz  z  }G d fD        \  }}t        |tF        jH                        r t5        d |jK                         D              nd}t        j                  |d|d|d |d!|	d!tM        |      dtM        |      d       |jO                  |||||	||g       t        j                          t        j                  j                            |S # t        $ r d}Y w xY w# t,        $ r d}Y Nw xY w# t,        $ r t9        d      |
d<   Y w xY w# 1 sw Y   xY w# 1 sw Y   ?xY w# t,        $ r0}t        j                  |       |jO                  d       Y d}~d}~ww xY w# t        j                          t        j                  j                          w xY w)"a  
    Ultralytics speed, memory and FLOPs profiler.

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

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

    Examples:
        >>> from ultralytics.utils.torch_utils import profile_ops
        >>> input = torch.randn(16, 3, 640, 640)
        >>> m1 = lambda x: x * torch.sigmoid(x)
        >>> m2 = nn.SiLU()
        >>> profile_ops(input, [m1, m2], n=100)  # profile over 100 iterations
    r   NParamsz>12sGFLOPszGPU_mem (GB)z>14szforward (ms)zbackward (ms)inputz>24soutputTr   r  )r   r   r   Fr  r  r=   r<   c              3   <   K   | ]  }|j                           y wra   )r   )rb   yis     r!   rd   zprofile_ops.<locals>.<genexpr>d  s      6b 6r   nanr  i  c              3   h   K   | ])  }j                   d    |z  j                   d   |z  z   + yw)r   N)r   )rb   r   r   s     r!   rd   zprofile_ops.<locals>.<genexpr>q  s/     'iRSqQWWR[1_(M'is   /2)r0   r   c              3   ~   K   | ]5  }t        |t        j                        rt        |j                        nd  7 yw)r   N)rm   r&   r  tupler   r   s     r!   rd   zprofile_ops.<locals>.<genexpr>v  s,     i]^Au||1LuQWW~RXXis   ;=c              3   <   K   | ]  }|j                           y wra   r   r   s     r!   rd   zprofile_ops.<locals>.<genexpr>w  s     :a	:r   12z12.4gz>14.3fz14.4g)(r  r  rm   r&   r0   r   r   rG   gccollectr5   r  r   r   r   r  r  r   float16r  r  r   rE   rt   r  r   r   backwardfloatrandnr   r  r   tolistr  r   Moduler   rn   append)r  opsr   r0   max_num_objr  r  r   tftbr6  r   memrL  r  ys_ins_outrc   r  r   s                       @r!   profile_opsr  -  s(   * Gfell+v&
KKD/(4(=nT=RSbcgRh4.$	) JJL	JJ -UE7 /)DDL"3-C5 ,	)A '4 0VaA#Av.:a3NSTSZSZ^c^k^kSkqrA1iAB]aXa[!eLQORUUXYYgh#)q 9A*62 	0i({!aD({!0:DQ:MS 6A 66STYY[ddf#,;AaD	0 9X.44C1Q4!A$;$.22B1Q4!A$;$.22B".v6 )!KK !
 + #C'iWXW_W_WfWfWh'i$i j'-&+mm y2S88/90 jcdfgbhie>HBII>VC:1<<>::\]qfU5M#fbZ5zRUVZR[\`Qabefkblmqarst5#r2tUCD
 



&&(Y,	)/)` Ny  *    ) 0#(<AaD0	0 	0   %At$$% 



&&(s   N) +N;<P#O+	<AO	=PPA)O8	;B4P)N87N8;O
	O
O($O+	'O((O+	+O50P8P=P	P>&P94Q9P>>Q4Q5c                       e Zd ZdZddZd Zy)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.
    c                 V    d| _         d| _        |xs t        d      | _        d| _        y)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)r  r  s     r!   r  zEarlyStopping.__init__  s+       0E%L"r,   c           
      f   |y|| j                   kD  s| j                   dk(  r|| _        || _         || j                  z
  }|| j                  dz
  k\  | _        || j                  k\  }|rJt	        d      }t        j                  | 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
        Fr   r<   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   rG   )r  r  fitnessdeltastopprefixs         r!   __call__zEarlyStopping.__call__  s     ?T&&&$*;*;q*@#DO 'D'"t}}q'89%/0FKK(TUYUbUbTc d226//1B C448MM? CTU r,   N)2   )r   r  r  r  r  r  r-   r,   r!   r  r    s    
#r,   r  c                   (     e Zd ZdZ fdZd Z x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                 \    t         |           t        | |       |j                  | _        y)z
        Initialize the FXModel.

        Args:
            model (nn.Module): The original model to wrap for torch.fx compatibility.
        N)superr  rT  r   )r  r   r   s     r!   r  zFXModel.__init__  s%     	$[[
r,   c                     g }| j                   D ]w  }|j                  dk7  rMt        |j                  t              r||j                     n#|j                  D cg c]  }|dk(  r|n||    c}} ||      }|j	                  |       y |S c c}w )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   )r   r  rm   r  r  )r  r   r  r   js        r!   forwardzFXModel.forward  s      	Assby(c2AaccFYZY\Y\8]TUa2g1Q49O8]!AHHQK	  9^s   B)r   r  r  r  r  r  __classcell__)r   s   @r!   r  r    s    	
!r,   r  )r5   )r?   r   FT)FT  )r  )r9  Fr  )r-   r-   )r-   )r  r9  d   )r   F)zbest.ptr?   Nra   )
   Nr   )Y	functoolsr  r?  rx   r{  r   
contextlibr   copyr   r   pathlibr   typingr   r   r	   numpyr}  r&   torch.distributeddistributedr   torch.nnr   torch.nn.functional
functionalrD  ultralyticsr
   r@   r   r   r   r   r   r   r   r   ultralytics.utils.checksr   ultralytics.utils.patchesr   r%   r2   r}   	TORCH_2_4TORCHVISION_0_10TORCHVISION_0_11TORCHVISION_0_13TORCHVISION_0_18r  r  r"   r.   boolrn   r4   	lru_cacherB   rQ   r   r   r   r   r   r   r   r  r   r+  r7  rJ  rT  ra  rg  rl  r  rv  r  r  r  r  r  r  r  r  r  r  r-   r,   r!   <module>r     sf    	  	   %    # #        #	 	 	 3 0 %++W5	5,,h7
%++W5	%++W5	 !4h?  !4h?  !4h?  !4h? 
}U..	:FNN	B 	MS 	M 	M
0d 0C 0: 7 7" N NodD>* Z6
I
D'TD
?."Wt
^
9V4+A9 A9H:uS$Y' : :4PSUXPX> :eijmorjres :z$  2Sl3 3l,bii ,r,   