Ë
    FêñiÖ¢  ã                  óÈ  — 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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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&m'Z' d d
l(m)Z) d dl*m+Z+ d dl,m-Z-  e)e$d«      Z. e)e$d«      Z/ e)e$d«      Z0 e)e$d«      Z1 e)e$d«      Z2 e)e$d«      Z3 e)e$d«      Z4 e)e$d«      Z5 e)e$d«      Z6 e)e$d«      Z7 e)e$d«      Z8 e)e%d«      Z9 e)e%d«      Z: e)e%d«      Z; e)e%d«      Z<e&r e)e$d«      r e!jz                  d«       e	d?d„«       Z>d„ Z?d@dAd „Z@ej‚                  d!„ «       ZBej‚                  d"„ «       ZCdBd#„ZDd$„ ZEd%„ ZFd&„ ZGdCd'„ZHd(„ ZId)„ ZJd*„ ZKdDd+„ZLdDd,„ZMd-„ ZNdEd.„ZOdFd/„ZPdGd0„ZQd1„ ZRdHd2„ZSdId3„ZTdJd4„ZUd5„ ZV G d6„ d7«      ZWdKdLd8„ZXd9„ ZYe	dMd:„«       ZZdNd;„Z[ G d<„ d=«      Z\	 	 	 	 dO	 	 	 	 	 	 	 	 	 	 	 	 	 dPd>„Z]y)Qé    )ÚannotationsN)Úcontextmanager)Údeepcopy)Údatetime)ÚPath)ÚAny)Ú__version__)	ÚDEFAULT_CFG_DICTÚDEFAULT_CFG_KEYSÚLOGGERÚNUM_THREADSÚPYTHON_VERSIONÚTORCH_VERSIONÚTORCHVISION_VERSIONÚWINDOWSÚcolorstr)Úcheck_version)ÚCPUInfo)Ú
torch_loadz1.9.0z1.10.0z1.11.0z1.13.0z2.0.0z2.1.0z2.3.0z2.4.0z2.8.0z2.9.0z2.10.0z0.10.0z0.11.0z0.13.0z0.18.0z==2.4.0z™Known 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/15049c              #  ó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)Ú
local_rankÚinitializedÚuse_idss      ú_/var/www/pod-logistic/pod-ai/venv/lib/python3.12/site-packages/ultralytics/utils/torch_utils.pyÚtorch_distributed_zero_firstr#   >   s‹   è ø€ ô ×#Ñ#Ó%Ò?¬$×*=Ñ*=Ó*?€KØÒ:œd×.Ñ.Ó0°FÑ:€Gá�z¨Ñ0Ù18Œ�‰  Õ-¼d¿l¹l»nøÛ	Ù�z Q’Ù18Œ�‰  Õ-¼d¿l¹l»nùð '€{ùs   ‚B4B6c                 ó   — d„ } | S )zXApply torch.inference_mode() decorator if torch>=1.10.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Ú
TORCH_1_10Úinference_modeÚno_grad)Úfns    r"   Údecoratez&smart_inference_mode.<locals>.decorateN   s>   € åœ×8Ñ8Ô:ØˆIàL­J”E×(Ñ(ÓLÈRÓPÐP¼E¿M¹MÓLÈRÓPÐPó    © )r-   s    r"   Úsmart_inference_moder0   K   s   € òQð €Or.   c                ó¢   — t         r!t        j                  j                  || ¬«      S t        j                  j                  j                  | «      S )aH  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.

    Examples:
        >>> with autocast(enabled=True):
        ...     # Your mixed precision operations here
        ...     pass

    Notes:
        - For PyTorch versions 1.13 and newer, it uses `torch.amp.autocast`.
        - For older versions, it uses `torch.cuda.amp.autocast`.
    )Úenabled)Ú
TORCH_1_13r'   ÚampÚautocastÚcuda)r2   Údevices     r"   r5   r5   X   s:   € õ, Ü�y‰y×!Ñ! &°'Ð!Ó:Ð:ä�z‰z�~‰~×&Ñ& wÓ/Ð/r.   c                 óˆ   — ddl m}  d| vr	 t        j                  «       | 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_infoÚunknown)Úultralytics.utilsr:   r   ÚnameÚ	ExceptionÚgetr9   s    r"   Úget_cpu_inforA   t   sO   € õ 3àÐ)Ñ)ð	Ü+2¯<©<«>Ð˜ZÑ(ð ×Ñ 
¨IÓ6Ð6øô ò 	Ùð	ús   Œ5 µ	AÁ A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'   r6   Úget_device_propertiesr>   Útotal_memory)ÚindexÚ
propertiess     r"   Úget_gpu_inforI   �   s>   € ô —‘×1Ñ1°%Ó8€JØ�o‰oÐ˜b ×!8Ñ!8¸GÑ!DÀSÐ IÈÐMÐMr.   c                óZ
  — t        | t        j                  «      st        | «      j	                  d«      r| S dt
        › dt        › dt        › d�}t        | «      j                  «       } dD ]  }| j                  |d«      } Œ | j	                  d«      �r:	 d	d
l
}t        t        d«      rt        j                  j                  «       st        d| › d�«      ‚| dd
 }|dk(  rd	}nB|j	                  d«      r"|dd
 j!                  «       rt#        |dd
 «      }nt        d| › d�«      ‚t        j                  j%                  «       }||k\  rt        d| › d|› d�«      ‚t        j                  j'                  |«       |r;t)        j*                  |› d|› dt        j                  j-                  |«      › d�«       t        j                  d|› �«      S d| v r™d	dlm}	 | j3                  d«      }
 |	«       j5                  |
j7                  d«      d¬«      }t9        t;        |
«      «      D ],  }|
|   dk(  sŒ|rt        |j=                  d	«      «      nd|
|<   Œ. dj?                  d„ |
D «       «      } | dk(  }| dv }|s|rdt@        jB                  d <   �nU| �rR| d!k(  rd"} d| v r1dj?                  | j3                  d«      D �cg c]  }|sŒ|‘Œ	 c}«      } t@        jB                  jE                  d d
«      }| t@        jB                  d <   t        jF                  j                  «       r9t        jF                  j%                  «       t;        | j3                  d«      «      k\  sŒt)        j*                  |«       t        jF                  j%                  «       d	k(  rd#nd}t        d$| › d%t        jF                  j                  «       › d&t        jF                  j%                  «       › d'|› d(|› �
«      ‚|sw|sut        jF                  j                  «       rW| r| j3                  d«      nd"}dt;        |«      z  }tI        |«      D ]#  \  }}||d	k(  rdn|› d)|› dtK        |«      › d�z  }Œ% d*}nW|rBtL        r<t        jN                  jP                  j                  «       r|d+tS        «       › d�z  }d,}n|d-tS        «       › d�z  }d}|d.v rt        jT                  tV        «       |r't)        j*                  |r|n|jY                  «       «       t        j                  |«      S # t        $ r t        d| › d�«      ‚w xY wc c}w )/aj  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 include 'cpu', 'cuda', '0',
            '0,1,2,3', 'mps', 'npu', 'npu:0', or '-1' for auto-select. Defaults to auto-selecting the first available
            GPU, or CPU if no GPU is available.
        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.

    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ÚintelÚvulkanzUltralytics u    ðŸš€ Python-z torch-ú )zcuda:Únoneú(ú)ú[ú]ú'rN   Ú Únpur   NzInvalid NPU 'device=z;'. Install 'torch_npu' at https://github.com/Ascend/pytorchz)' requested. Ascend NPU is not available.é   ú:é   z' format. Use 'npu' or 'npu:0'.z' requested. Only z NPU(s) available.zNPU:z (z)
znpu:z-1)ÚGPUInfoú,gš™™™™™É?)ÚcountÚmin_memory_fractionc              3  ó&   K  — | ]	  }|sŒ|–— Œ y ­w©Nr/   )Ú.0Úps     r"   ú	<genexpr>z select_device.<locals>.<genexpr>Ñ   s   è ø€ Ò0 ªaœ!Ñ0ùs   ‚ŠÚcpu>   úmps:0ÚmpsÚCUDA_VISIBLE_DEVICESr6   Ú0z}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']: ú
zCUDA:zcuda:0zMPS (re   zCPU (>   rc   re   )-Ú
isinstancer'   r7   ÚstrÚ
startswithr	   r   r   ÚlowerÚreplaceÚ	torch_npuÚImportErrorÚ
ValueErrorÚhasattrrV   r   ÚisdigitÚintÚdevice_countÚ
set_devicer   ÚinfoÚget_device_nameÚultralytics.utils.autodevicerZ   ÚsplitÚselect_idle_gpur\   ÚrangeÚlenÚpopÚjoinÚosÚenvironr@   r6   Ú	enumeraterI   Ú	TORCH_2_0Úbackendsre   rA   Úset_num_threadsr   Úrstrip)r7   ÚnewlineÚverboseÚsÚremovern   ÚsuffixÚidxÚnrZ   ÚpartsÚselectedÚirc   re   ÚxÚvisibleÚinstallÚdevicesÚspaceÚdÚargs                         r"   Úselect_devicer—   ˆ   s¿  € ô6 �&œ%Ÿ,™,Ô'¬3¨v«;×+AÑ+AÐB\Ô+]Øˆà
”{�m =´Ð0@ÀÌÀÐVWÐX€AÜ�‹[×ÑÓ €FØ?ò ,ˆØ—‘ ¨Ó+‰ð,ð ×Ñ˜Õð	yÛô ”u˜eÔ$¬E¯I©I×,BÑ,BÔ,DÜÐ3°F°8Ð;dÐeÓfÐfð ˜˜�ˆØ�RŠ<Ø‰CØ×Ñ˜sÔ#¨¨q¨r¨
×(:Ñ(:Ô(<Ü�f˜Q˜R�j“/‰CäÐ3°F°8Ð;ZÐ[Ó\Ð\ä�I‰I×"Ñ"Ó$ˆØ�!Š8ÜÐ3°F°8Ð;MÈaÈSÐPbÐcÓdÐdä�	‰	×Ñ˜SÔ!ÙÜ�K‰K˜1˜#˜T #  b¬¯©×)BÑ)BÀ3Ó)GÐ(HÈÐLÔMÜ�|‰|˜d 3 %˜LÓ)Ð)ð ˆv�~Ý8ð —‘˜SÓ!ˆÙ“9×,Ñ,°5·;±;¸tÓ3DÐZ]Ð,Ó^ˆÜ”s˜5“zÓ"ò 	DˆAØ�Q‰x˜4ÓÙ3;œ3˜xŸ|™|¨A›Ô/À��a’ð	Dð —‘Ñ0 UÔ0Ó0ˆà
�E‰/€CØ
Ð$Ð
$€CÙ
‰cØ-/Œ�
‰
Ð)Ó*Ú	Ø�VÒØˆFØ�&‰=Ø—X‘X¨&¯,©,°sÓ*;ÖA QºqšqÒAÓBˆFÜ—*‘*—.‘.Ð!7¸Ó>ˆØ-3Œ�
‰
Ð)Ñ*Ü—
‘
×'Ñ'Ô)¬e¯j©j×.EÑ.EÓ.GÌ3ÈvÏ|É|Ð\_ÓO`ÓKaÒ.aÜ�K‰K˜ŒNô —:‘:×*Ñ*Ó,°Ò1ñ4ð ð	 ô Ø'¨ xð 00ô 16·
±
×0GÑ0GÓ0IÐ/JØ/´·
±
×0GÑ0GÓ0IÐ/JØ8¸¸	ÀØ�)ðóð ñ ‘sœuŸz™z×6Ñ6Ô8Ù'-�&—,‘,˜sÔ#°3ˆØ”c˜!“f‘ˆÜ˜gÓ&ò 	L‰DˆAˆqØ˜!˜qš&‘B eÐ,¨E°!°°B´|ÀA³Ð6GÀsÐKÑK‰Að	Là‰Ù	•œuŸ~™~×1Ñ1×>Ñ>Ô@à	ˆu”\“^Ð$ CÐ(Ñ(ˆØ‰à	ˆu”\“^Ð$ CÐ(Ñ(ˆØˆà
ˆnÑÜ×ÑœkÔ*ÙÜ�‰™‘A a§h¡h£jÔ1Ü�<‰<˜ÓÐøôg ò 	yÜÐ3°F°8Ð;vÐwÓxÐxð	yüòX Bs   ÂT Ê8T(Ë T(ÔT%c                 ó¢   — t         j                  j                  «       rt         j                  j                  «        t	        j                  «       S )zReturn PyTorch-accurate time.)r'   r6   r   ÚsynchronizeÚtimer/   r.   r"   Ú	time_syncr›     s.   € ä‡z�z×ÑÔ Ü�
‰
×ÑÔ Ü�9‰9‹;Ðr.   c                ó  — | j                   j                  | j                  d«      }t        j                  |j                   j                  t        j                  |j                  |j                  z   «      «      «      }t        j                  ||«      j                  | j                   j                  «      | j                   _        | j                  €5t        j                  | j                  | j                   j                  ¬«      n| j                  }|j                  |j                   j                  |j                   «      j                  t        j                  |j                  |j                  z   «      «      z
  }t        j                  ||j#                  dd«      «      j#                  d«      |z   }| j                  €&| j%                  dt'        j(                  |«      «       n|| j                  _        | j+                  d«      S )a­  Fuse Conv2d and BatchNorm2d layers for inference optimization.

    Args:
        conv (nn.Conv2d): Convolutional layer to fuse.
        bn (nn.BatchNorm2d): Batch normalization layer to fuse.

    Returns:
        (nn.Conv2d): The fused convolutional layer with gradients disabled.

    Examples:
        >>> conv = nn.Conv2d(3, 16, 3)
        >>> bn = nn.BatchNorm2d(16)
        >>> fused_conv = fuse_conv_and_bn(conv, bn)
    r   ©r7   rY   ÚbiasF©ÚweightÚviewÚout_channelsr'   ÚdiagÚdivÚsqrtÚepsÚrunning_varÚmmÚshapeÚdatarž   Úzerosr7   ÚmulÚrunning_meanÚreshapeÚregister_parameterÚnnÚ	ParameterÚrequires_grad_)ÚconvÚbnÚw_convÚw_bnÚb_convÚb_bnÚ
fused_biass          r"   Úfuse_conv_and_bnrº     s`  € ð  �[‰[×Ñ˜d×/Ñ/°Ó4€FÜ�:‰:�b—i‘i—m‘m¤E§J¡J¨r¯v©v¸¿¹Ñ/FÓ$GÓHÓI€DÜ—x‘x  fÓ-×2Ñ2°4·;±;×3DÑ3DÓE€D‡K�KÔð KOÏ)É)ÐJ[ŒU�[‰[˜×*Ñ*°4·;±;×3EÑ3EÕFÐae×ajÑaj€FØ�7‰7�R—Y‘Y—]‘] 2§?¡?Ó3×7Ñ7¼¿
¹
À2Ç>Á>ÐTV×TZÑTZÑCZÓ8[Ó\Ñ\€DÜ—‘˜$ §¡¨r°1Ó 5Ó6×>Ñ>¸rÓBÀTÑI€Jà‡y�yÐØ×Ñ ¬¯©°ZÓ(@ÕAà#ˆ�	‰	Œà×Ñ˜uÓ%Ð%r.   c                ó  — | j                   j                  | j                  d«      }t        j                  |j                   j                  t        j                  |j                  |j                  z   «      «      «      }t        j                  ||«      j                  | j                   j                  «      | j                   _        | j                  €5t        j                  | j                  | j                   j                  ¬«      n| j                  }|j                  |j                   j                  |j                   «      j                  t        j                  |j                  |j                  z   «      «      z
  }t        j                  ||j#                  dd«      «      j#                  d«      |z   }| j                  €&| j%                  dt'        j(                  |«      «       n|| j                  _        | j+                  d«      S )að  Fuse ConvTranspose2d and BatchNorm2d layers for inference optimization.

    Args:
        deconv (nn.ConvTranspose2d): Transposed convolutional layer to fuse.
        bn (nn.BatchNorm2d): Batch normalization layer to fuse.

    Returns:
        (nn.ConvTranspose2d): The fused transposed convolutional layer with gradients disabled.

    Examples:
        >>> deconv = nn.ConvTranspose2d(16, 3, 3)
        >>> bn = nn.BatchNorm2d(3)
        >>> fused_deconv = fuse_deconv_and_bn(deconv, bn)
    r   r�   rY   rž   FrŸ   )Údeconvr´   Úw_deconvr¶   r·   r¸   r¹   s          r"   Úfuse_deconv_and_bnr¾   -  sa  € ð  �}‰}×!Ñ! &×"5Ñ"5°rÓ:€HÜ�:‰:�b—i‘i—m‘m¤E§J¡J¨r¯v©v¸¿¹Ñ/FÓ$GÓHÓI€DÜŸ™ $¨Ó1×6Ñ6°v·}±}×7JÑ7JÓK€F‡M�MÔð OUÏkÉkÐNaŒU�[‰[˜×,Ñ,°V·]±]×5IÑ5IÕJÐgm×grÑgr€FØ�7‰7�R—Y‘Y—]‘] 2§?¡?Ó3×7Ñ7¼¿
¹
À2Ç>Á>ÐTV×TZÑTZÑCZÓ8[Ó\Ñ\€DÜ—‘˜$ §¡¨r°1Ó 5Ó6×>Ñ>¸rÓBÀTÑI€Jà‡{�{ÐØ×!Ñ! &¬"¯,©,°zÓ*BÕCà%ˆ�‰Ôà× Ñ  Ó'Ð'r.   c                ó  — |syt        | «      }t        | «      }t        d«      j                  d„ | j	                  «       D «       «      }t        |«      }|�rzdd›dd›dd	›d
d›dd›dd	›dd›dd›�}t        j                  |«       t        |j                  «       «      D �].  \  }	\  }
}|
j                  dd«      }
|j                  j                  }t        |j                  «      r¸|j                  «       D ]¤  \  }}t        j                  |	d›|
› d|› �d›|d	›|j                  d›|j!                  «       d›t#        |j$                  «      d	›|j'                  «       d›|j)                  «       d›t+        |j,                  «      j                  dd«      d›�	«       Œ¦ Œÿt        j                  |	d›|
d›|d	›dd›dd›g d	›dd›dd›dd›�	«       �Œ1 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:
        (tuple): Tuple containing:
            - 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)r|   Ú_modules)r`   rŒ   Úms      r"   rb   zmodel_info.<locals>.<genexpr>b  s-   è ø€ Ò2t¹d¸aÀÔ_bÐcd×cmÑcmÓ_nÐrsÓ_s°A°q´6Ñ2tùs   ‚ ,£	,Úlayerz>5r>   z>40Útypez>20Úgradientz>10Ú
parametersz>12r©   ÚmuÚsigmazmodule_list.rU   z>5gú.z>12gz>10.3gztorch.z>15Fr   ú-Úis_fusedc                  ó   — y)NFr/   r/   r.   r"   ú<lambda>zmodel_info.<locals>.<lambda>s  s   � r.   z (fused)rC   ú.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_modulesr|   r   rv   r�   Úitemsrm   Ú	__class__Ú__name__Ú_parametersÚnamed_parametersÚrequires_gradÚnumelÚlistr©   ÚmeanÚstdrj   ÚdtypeÚ	get_flopsÚgetattrr@   r   Ústem)ÚmodelÚdetailedr‡   ÚimgszÚn_pÚn_gÚlayersÚn_lÚhr�   ÚmnrÃ   ÚmtÚpnra   ÚflopsÚfusedÚfsrÐ   Ú
model_names                       r"   Ú
model_infor÷   N  s"  € ñ  ØÜ
˜Ó
€CÜ
˜EÓ
"€CÜ˜Ó&×2Ñ2Ñ2tÀe×FYÑFYÓF[Ô2tÓt€FÜ
ˆf‹+€CÚØ�rˆl˜6 #˜, v¨c l°:¸cÐ2BÀ<ÐPSÐBTÐU\Ð]`ÐTaÐbfÐgjÐakÐlsÐtwÐkxÐyˆÜ�‰�AŒÜ# F§L¡L£NÓ3ó 		r‰JˆA‰w��AØ—‘˜N¨BÓ/ˆBØ—‘×%Ñ%ˆBÜ�1—=‘=Ô!Ø×/Ñ/Ó1ò ‘E�B˜Ü—K‘KØ˜S˜' R D¨¨"¨ ,¨sÐ!3°B°s°8¸A¿O¹OÈcÐ;RÐST×SZÑSZÓS\Ð]aÐRbÔcgÐhi×hoÑhoÓcpÐsvÐbwÐxy×x~Ñx~ó  yAð  BHð  xIð  JK÷  JOñ  JOó  JQð  RXð  IYô  Z]ð  ^_÷  ^eñ  ^eó  Zf÷  Znñ  Znð  owð  y{ó  Z|ð  }@ð  YAð  Bõñô
 —‘˜q ˜g b¨ X¨b°¨X°e¸c°]À1ÀTÀ(È2ÐPSÈ*ÐUXÐY\ÐT]Ð^aÐbeÐ]fÐgjÐknÐfoÐpÖqð		rô �e˜UÓ#€EØCœ' %¨±]ÓCÔE‰JÈ2€EÙ$)ˆ2ˆe�Cˆ[˜Ñ	 ¨r€BÜ˜˜{¨BÓ/Òb´7¸5À&È"Ó3M×3QÑ3QÐR]Ð_aÓ3b€IÜ�i“×%Ñ%×-Ñ-¨f°fÓ=ÒHÀ€JÜ
‡K�K�:�,˜h u g¨R°°A¨w°iÀÀA¸wÀmÐTWÐXYÐSZÐZdÐegÐdhÐ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r_   ©rà   ©r`   r�   s     r"   rb   z!get_num_params.<locals>.<genexpr>}  s   è ø€ Ò5˜Qˆq�w‰w�yÑ5ùó   ‚©ÚsumrÇ   ©rè   s    r"   rÕ   rÕ   {  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r_   )rß   rà   rû   s     r"   rb   z$get_num_gradients.<locals>.<genexpr>‚  s   è ø€ ÒH˜Q¸¿»ˆq�w‰w�yÑHùs   ‚)”)rý   rÿ   s    r"   rÖ   rÖ   €  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 )	aV  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/namerW   )zmodel/parameterszmodel/GFLOPsÚ	inferencezmodel/speed_PyTorch(ms))ÚargsÚprofileÚultralytics.utils.benchmarksr  Úlastr7   Úrunr}   rÕ   rè   Úroundrå   Ú	validatorÚspeed)Útrainerr  Úresultss      r"   Úmodel_info_for_loggersr  …  s—   € ð& ‡|�|×ÒÝ>á §¡ °w·~±~ÔF×JÑJÓLÈQÑOˆØ�‰�LÕ!ô !/¨w¯}©}Ó =Ü!¤)¨G¯M©MÓ":¸AÓ>ñ
ˆô */¨w×/@Ñ/@×/FÑ/FÀ{Ñ/SÐUVÓ)W€GÐ%Ñ&Ø€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 GFLOPs.

    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's GFLOPs (billions of floating point operations).
    r   Nç        Ústrideé    rY   r�   F©Úinputsr‡   ç    eÍÍAé   )Úthopro   Úunwrap_modelÚnextrÇ   ri   rá   rq   Úmaxrs   r  r'   Úemptyr©   r7   r  r   r?   )rè   rê   r  ra   r  Úimró   s          r"   rå   rå   ¦  sv  € ðÛñ ØðÜ˜UÓ#ˆÜ�×!Ñ!Ó#Ó$ˆÜ˜%¤Ô&Ø˜E�NˆEð		Zä9@ÀÈÔ9Q”Sœ˜UŸ\™\×-Ñ-Ó/Ó0°"Ô5ÐWYˆFÜ—‘˜a §¡¨¡¨V°VÐ<ÀQÇXÁXÔNˆBØ—L‘L¤¨%£¸"¸Àu�LÓMÈaÑPÐSVÑVÐYZÑZˆEØ˜5 ™8Ñ# fÑ,¨u°Q©xÑ7¸&Ñ@Ð@øô! ò ØŠðûô" ò 	Zä—‘˜a §¡¨¡Ð4¨eÑ4¸Q¿X¹XÔFˆBØ—<‘<¤¨£¸¸Àe�<ÓLÈQÑOÐRUÑUÐXYÑ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)a9  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 GFLOPs (billions of floating point operations).
    r  r  r  r  rY   r�   T)Ú
with_flopsNc              3  ó4   K  — | ]  }|j                   –— Œ y ­wr_   ©ró   rû   s     r"   rb   z0get_flops_with_torch_profiler.<locals>.<genexpr>ä  ó   è ø€ Ò9 �A—G•GÑ9ùó   ‚r  r   c              3  ó4   K  — | ]  }|j                   –— Œ y ­wr_   r!  rû   s     r"   rb   z0get_flops_with_torch_profiler.<locals>.<genexpr>ë  r"  r#  )r‚   r  r  rÇ   ri   rá   rq   r  rs   r  r'   r  r©   r7   Úprofilerr  rþ   Úkey_averagesr?   )rè   rê   ra   r  r  Úprofró   s          r"   Úget_flops_with_torch_profilerr(  Î  sœ  € õ ØÜ˜Ó€EÜˆU×ÑÓÓ €AÜ�eœTÔ"Ø˜�ˆð@ä6=¸eÀXÔ6N”#”c˜%Ÿ,™,×*Ñ*Ó,Ó-¨rÔ2ÐTVÐZ[Ñ[ˆÜ�[‰[˜!˜QŸW™W Q™Z¨°Ð8ÀÇÁÔJˆÜ�^‰^×#Ñ#¨tÐ#Ó4ð 	¸Ù�"ŒI÷	äÑ9 T×%6Ñ%6Ó%8Ô9Ó9¸CÑ?ˆØ˜˜a™Ñ  6Ñ)¨E°!©HÑ4°vÑ=ˆð €L÷	ð 	ûô ò @ä�[‰[˜!˜QŸW™W Q™ZÐ0¨%Ñ0¸¿¹ÔBˆÜ�^‰^×#Ñ#¨tÐ#Ó4ð 	¸Ù�"ŒI÷	÷ 	ñ 	úäÑ9 T×%6Ñ%6Ó%8Ô9Ó9¸CÑ?‰Ø€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)zHInitialize model weights, biases, and module settings to default values.gü©ñÒMbP?g¸…ëQ¸ž?TN)ÚmodulesrÅ   r°   ÚConv2dÚBatchNorm2dr¦   ÚmomentumÚ	HardswishÚ	LeakyReLUÚReLUÚReLU6ÚSiLUÚinplace)rè   rÃ   Úts      r"   Úinitialize_weightsr5  ï  sv   € à�]‰]‹_ò ˆÜ�‹GˆØ”—	‘	‰>ØØ”"—.‘.Ñ ØˆAŒEØˆA�JØ”2—<‘<¤§¡¬r¯w©w¼¿¹Ä"Ç'Á'ÐJÒJØˆA�Iñ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r_   )ÚmathÚceil)r`   r�   ÚgsÚratios     €€r"   rb   zscale_img.<locals>.<genexpr>  s'   øè ø€ Ò?°1”—	‘	˜!˜e™) b™.Ó)¨BÕ.Ñ?ùs   ƒ(+r   rY   gÏ÷Sã¥›Ü?)Úvalue)r©   rs   ÚFÚinterpolateÚpad)Úimgr@  Ú
same_shaper?  rï   Úwrˆ   s    ` `   r"   Ú	scale_imgrH  ü  s“   ù€ ð �‚|Øˆ
Ø�9‰9�Q�Rˆ=�D€A€qÜ	ˆQ�‰Y‹œ˜Q ™Y›Ð(€AÜ
�-‰-˜ !¨*ÀEÔ
J€CÙÜ?¸¸A¸Ô?‰ˆˆ1Ü�5‰5��q˜!˜a ™d™( A q¨1¨Q©4¡xÐ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Ú   r|   rk   Úsetattr)ÚaÚbÚincludeÚexcludeÚkÚvs         r"   Ú	copy_attrrS    sR   € ð —
‘
× Ñ Ó"ò ‰ˆˆ1Ü�ŒL˜Q gÑ-°!·,±,¸sÔ2CÀqÈGÁ|Øä�A�q˜!Õñ	r.   c                óÈ   ‡— | j                  «       D �‡�ci c]?  \  Š}‰|v sŒt        ˆfd„|D «       «      sŒ |j                  |‰   j                  k(  sŒ=‰|“ŒA c}}S c c}}w )aL  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r_   r/   )r`   r�   rQ  s     €r"   rb   z"intersect_dicts.<locals>.<genexpr>-  s   øè ø€ Ò:WÈ!¸1ÀA¼:Ñ:Wùs   ƒ)rÚ   Úallr©   )ÚdaÚdbrP  rQ  rR  s      ` r"   Úintersect_dictsrY  "  sX   ø€ ð  ŸX™X›Z×sÐs‘T�Q˜¨1°ª7´sÓ:WÈwÔ:WÕ7WÐ\]×\cÑ\cÐgiÐjkÑgl×grÑgrÓ\rˆAˆq‰DÓ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.
    )ri   r°   ÚparallelÚDataParallelÚDistributedDataParallelrÿ   s    r"   Úis_parallelr^  0  s*   € ô �eœbŸk™k×6Ñ6¼¿¹×8[Ñ8[Ð\Ó]Ð]r.   c                óþ   — 	 t        | d«      r1t        | j                  t        j                  «      r| j                  } n?t        | d«      r1t        | j
                  t        j                  «      r| j
                  } n| S Œ})aV  Unwrap compiled and parallel models to get the base model.

    Args:
        m (nn.Module): A model that may be wrapped by torch.compile (._orig_mod) or parallel wrappers such as
            DataParallel/DistributedDataParallel (.module).

    Returns:
        (nn.Module): The unwrapped base model without compile or parallel wrappers.
    Ú	_orig_modÚmodule)rq   ri   r`  r°   ÚModulera  )rÃ   s    r"   r  r  <  sY   € ð Ü�1�kÔ"¤z°!·+±+¼r¿y¹yÔ'IØ—‘‰AÜ�Q˜Ô!¤j°·±¼2¿9¹9Ô&EØ—‘‰AàˆHð r.   c                ó   ‡ ‡‡— ˆˆ ˆfd„S )aM  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 )NrY   r  r   )r  r=  ÚcosÚpi)r�   ÚstepsÚy1Úy2s    €€€r"   rÎ   zone_cycle.<locals>.<lambda>Z  s=   ø€ ”S˜!œdŸh™h q¬4¯7©7¡{°UÑ':Ó;Ñ;¸qÑ@À!ÓDÈÈRÉÑPÐSUÑU€ r.   r/   )rh  ri  rg  s   ```r"   Ú	one_cyclerj  O  s   ú€ õ VÐUr.   c                ó.  — t        j                  | «       t        j                   j                  | «       t        j                  | «       t        j
                  j	                  | «       t        j
                  j                  | «       |r‚t        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_seedr6   Úmanual_seed_allr‚   Úuse_deterministic_algorithmsrƒ   ÚcudnnÚdeterministicr   r€   rj   r   ÚwarningÚunset_deterministic)rp  rv  s     r"   Ú
init_seedsry  ]  s¯   € ô ‡K�K�ÔÜ‡I�I‡N�N�4ÔÜ	×Ñ�dÔÜ	‡J�J×Ñ˜4Ô Ü	‡J�J×Ñ˜tÔ$áÝÜ×.Ñ.¨t¸tÕDØ15ŒE�N‰N× Ñ Ô.Ø4=ŒB�J‰JÐ0Ñ1Ü+.¨t«9ŒB�J‰JÐ'Ò(ä�N‰NÐ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.Frm  Nrn  )r'   rt  rƒ   ru  rv  r   r€   r}   r/   r.   r"   rx  rx  v  sH   € ä	×&Ñ& uÔ-Ø).„E‡N�N×ÑÔ&Ü‡J�J‡N�NÐ,¨dÔ3Ü‡J�J‡N�NÐ# 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)a7  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 )NrY   )r=  Úexp)r�   ÚdecayÚtaus    €€r"   rÎ   z#ModelEMA.__init__.<locals>.<lambda>œ  s    ø€ ˜u¨¬D¯H©H°a°R¸#±XÓ,>Ñ(>Ñ?€ r.   FTN)	r   r  ÚevalÚemaÚupdatesr€  rÇ   r²   r2   )Úselfrè   r€  r�  r„  ra   s     ``  r"   Ú__init__zModelEMA.__init__‘  s^   ù€ ô œL¨Ó/Ó0×5Ñ5Ó7ˆŒØˆŒÜ?ˆŒ
Ø—‘×$Ñ$Ó&ò 	$ˆ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)zgUpdate EMA parameters.

        Args:
            model (nn.Module): Model to update EMA from.
        rY   N)
r2   r„  r€  r  Ú
state_dictrƒ  rÚ   rä   Úis_floating_pointÚdetach)r…  rè   r•   ÚmsdrQ  rR  s         r"   ÚupdatezModelEMA.update¡  sŸ   € ð �<Š<Ø�LŠL˜AÑ�LØ—
‘
˜4Ÿ<™<Ó(ˆAä˜uÓ%×0Ñ0Ó2ˆCØŸ™×+Ñ+Ó-×3Ñ3Ó5ò 3‘��1Ø—7‘7×,Ó,Ø˜‘F�AØ˜!˜a™% 3 q¡6§=¡=£?Ñ2Ñ2‘Añ3ð r.   c                óN   — | j                   rt        | j                  |||«       yy)a(  Copy attributes from model to EMA, with options to include/exclude certain attributes.

        Args:
            model (nn.Module): Model to copy attributes from.
            include (tuple, optional): Attributes to include.
            exclude (tuple, optional): Attributes to exclude.
        N)r2   rS  rƒ  )r…  rè   rO  rP  s       r"   Úupdate_attrzModelEMA.update_attr²  s"   € ð �<Š<Ü�d—h‘h  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|  c           	     ó  — 	 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)
    rc   )Ú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)ÚdateÚversionÚlicenseÚdocsrƒ  r  Ú	criterionFÚ
train_args)Ú	optimizerÚbest_fitnessrƒ  r„  Úscalerr   Úepochg    €„.AzOptimizer stripped from r[   z
 saved as rU   rN   rÏ   ÚMB)r   r'   r7   ri   Údictr?   r   rw  r   ÚnowÚ	isoformatr	   r@   rq   r  rš  ÚhalfrÇ   rß   r
   rÚ   r   Úsaver   ÚpathÚgetsizerv   )Úfrˆ   r„  r�   ÚeÚmetadatara   r  rQ  rR  ÚcombinedÚmbs               r"   Ústrip_optimizerr­  ¾  s  € ð$Ü�q¤u§|¡|°EÓ':Ô;ˆÜ˜!œTÔ"ÐKÐ$KÓKÐ"Ø˜!‰|Ð>Ð>Ó>‰|ô —‘“×(Ñ(Ó*ÜØGØ.ñ	€Hð 	‡u�uˆU„|Ø�u‘Xˆˆ'‰
Üˆq�‰z˜6Ô"Ü˜q ™zŸ™Ó/ˆˆ'‰
ŒÜˆq�‰z˜;Ô'Ø#ˆˆ'‰
ÔØ€g�J‡O�OÔØˆw‰Z×"Ñ"Ó$ò  ˆØˆ�ð ð ;ÔÐ: !§%¡%¨°bÓ"9Ð:€DØDò ˆØˆˆ!Šðà€A€g�JØ(,¯
©
«×N¡  1¸Ô=MÒ8M�q˜!‘tÓN€A€l�Oð 4�(Ð3˜aÐ3 G¢M¨rÐ3€HÜ	‡J�Jˆx˜š˜aÔ Ü	�‰�‰˜š˜aÓ	  3Ñ	&€BÜ
‡K�KÐ*¨1¨#¨QÁA°¸A¸3¸aÑ/@È2Ð.NÈaÐPRÐSVÈxÐWYÐZÔ[Ø€OøôG ò Ü�‰˜ 1 #Ð%FÀqÀcÐJÔKØ�	ûðüó6 Os*   ‚AG ÅHÅHÇ	HÇG?Ç9HÇ?Hc                ó  — | d   j                  «       D ]j  }|j                  «       D ]U  \  }}|dvsŒt        |t        j                  «      sŒ&|j
                  t        j                  u sŒC|j                  «       ||<   ŒW Œl | 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Ú
exp_avg_sq)ÚvaluesrÚ   ri   r'   ÚTensorrä   Úfloat32r¤  )rˆ  r¯  rQ  rR  s       r"   Ú$convert_optimizer_state_dict_to_fp16rµ  ú  s|   € ð ˜GÑ$×+Ñ+Ó-ò $ˆØ—K‘K“Mò 	$‰DˆAˆqØÐ.Ò.´:¸aÄÇÁÕ3NÐST×SZÑSZÔ^c×^kÑ^kÒSkØŸ6™6›8��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)aI  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'   r6   r   Úempty_cacheÚmemory_reserved)r7   Ú	cuda_infos     r"   Úcuda_memory_usager»    sv   è ø€ ô ˜A”€IÜ‡z�z×ÑÔ Ü�
‰
×ÑÔ ð	EØŠOä"'§*¡*×"<Ñ"<¸VÓ"DˆI�hÒà‹øô #(§*¡*×"<Ñ"<¸VÓ"DˆI�hÒü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!›|d›|d›�«       |jM                  |||||	||g«       t        j                  «        t        j                  j                  «        �ŒÁ �Œõ |S # t        $ r d}Y �Œžw xY w# t,        $ r d}Y �Œ<w 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                  |«       |jM                  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ÚoutputTÚtor¤  )r   r   r   Fr  r  r  rY   c              3  ó<   K  — | ]  }|j                  «       –— Œ y ­wr_   )rþ   )r`   Úyis     r"   rb   zprofile_ops.<locals>.<genexpr>Z  s   è ø€ Ò 6¨b §¡§Ñ 6ùrü   Únanr·  iè  c              3  óh   •K  — | ])  }‰j                   d    |z  ‰j                   d   |z  z  –— Œ+ y­w)r   éþÿÿÿN)r©   )r`   rˆ   r�   s     €r"   rb   zprofile_ops.<locals>.<genexpr>g  s/   øè ø€ Ò'iÐRS¨¯©°©°q©¸Q¿W¹WÀR¹[È1¹_Õ(MÑ'iùs   ƒ/2)r7   rä   c              3  ó~   K  — | ]5  }t        |t        j                  «      rt        |j                  «      nd –— Œ7 y­w)rá   N)ri   r'   r³  Útupler©   rû   s     r"   rb   zprofile_ops.<locals>.<genexpr>l  s,   è ø€ ÒiÐ]^´¸A¼u¿|¹|Ô1Lœu Q§W¡Wœ~ÐRXÓXÑiùs   ‚;=c              3  ó<   K  — | ]  }|j                  «       –— Œ y ­wr_   rú   rû   s     r"   rb   zprofile_ops.<locals>.<genexpr>m  s   è ø€ Ò: a˜Ÿ™Ÿ	Ñ:ùrü   Ú12z12.4gz>14.3fz14.4g)'r  ro   ri   r'   r7   r—   r   rv   ÚgcÚcollectr6   r¸  rá   rÁ  rß   rq   r³  rä   Úfloat16r¤  r  r   r?   r{   r»  r›   rþ   ÚbackwardÚfloatÚrandnr©   rs   r  Útolistr´  r°   rb  rÇ   Úappend)r¿  ÚopsrŒ   r7   Úmax_num_objr  r  rÃ   ÚtfÚtbr4  ró   ÚmemrJ  rº  ÚyÚs_inÚs_outra   r©  r�   s                       @r"   Úprofile_opsrÛ  $  s  ø€ ð(Ûð €GÜ�fœeŸl™lÔ+Ü˜vÓ&ˆÜ
‡K�KØ�Dˆ/˜( 4˜¨¸Ð(=¸nÈTÐ=RÐSbÐcgÐRhØ�4ˆ.˜ $˜ð	)ôô ‡J�J„LÜ	‡J�J×ÑÔÜ  ¬Ô-‰U°E°7ó /)ˆØ�D‰D�‹LˆØˆŒÜ" 3¬Ô-‘°C°5ó ,	)ˆAÜ '¨¨4Ô 0�—‘�V”°aˆAÜ# A vÔ.´:¸aÄÇÁÔ3NÐST×SZÑSZÔ^c×^kÑ^kÑSk�—‘”ÐqrˆAØ˜1ši�A�ˆBðÙ]a˜Ÿ™¤X¨a£[¸!¸Àe˜ÓLÈQÑOÐRUÑUÐXYÒYÐgh�ð#)Ø�Ü˜q›ó 9�AÜ*¨6Ó2ð 	0°iÜ(›{˜˜!™Ù˜a›D˜Ü(›{˜˜!™ð0Ü:DÀQÌÔ:MœSÑ 6°AÔ 6Ô6ÐST×YÑYÓ[×dÑdÔfÜ#,£;˜A˜a™D÷	0ð ˜9 XÑ.°Ñ4Ñ4�CØ˜1˜Q™4 ! A¡$™;¨$Ñ.°Ñ2Ñ2�BØ˜1˜Q™4 ! A¡$™;¨$Ñ.°Ñ2Ñ2�BÚ"Ü.¨vÓ6ð ¸)Ü!ŸK™KØ !§¡¨¡
Ø +Ü #¤CÓ'iÐWX×W_ÑW_×WfÑWfÓWhÔ'iÓ$iÓ jØ'-Ü&+§m¡mõ÷ð ˜y¨Ñ2°SÑ8Ñ8šð/9ñ0 jÐcdÐfgÐbhÔi‘��eÜ>HÈÌBÏIÉIÔ>V”CÑ:¨1¯<©<«>Ô:Ô:Ð\]�Ü—‘˜q ˜f U¨5 M°#°f°¸bÀ¸ZÈÈ5ÀzÐRVÐY]ÐQ^Ð_dÐgkÐ^lÐmÔnØ—‘  5¨#¨r°2°t¸UÐCÔDô
 —
‘
”Ü—
‘
×&Ñ&Ö(òY,	)ð/)ð` €Nøôy ò Ø‹ðûô* ò Ø“ðûô  )ò 0ä#(¨£<˜A˜aœDð0ú÷	0ñ 	0ú÷ñ ûô ò %Ü—‘˜A”Ø—‘˜t×$Ñ$ûð%ûô —
‘
”Ü—
‘
×&Ñ&Õ(ús¤   ƒN Å+N)Å<O3Æ#O	Æ<AN;È	=O3ÉO3ÉA)O&	Ê;B"O3ÎN&Î%N&Î)N8Î7N8Î;OÏO	ÏOÏO	ÏO#ÏO3Ï&O0Ï+O3Ï3	P,Ï<&P'Ð"P/Ð'P,Ð,P/Ð/4Q#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+   € ð  ˆÔØˆŒØ Ò0¤E¨%£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 )	zý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   rY   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   rv   )r…  rŸ  ÚfitnessÚdeltaÚstopÚprefixs         r"   Ú__call__zEarlyStopping.__call__Ž  sÉ   € ð ˆ?Øà�T×&Ñ&Ò&¨$×*;Ñ*;¸qÒ*@Ø#ˆDŒOØ 'ˆDÔØ˜Ÿ™Ñ'ˆØ" t§}¡}°qÑ'8Ñ9ˆÔØ˜Ÿ™Ñ%ˆÙÜÐ/Ó0ˆFÜ�K‰KØ�(ÐTÐUY×UbÑUbÐTcð d2Ø26·/±/Ð1Bð C4Ø48·M±M°?ð CTðUôð ˆr.   N)é2   )rÜ   r‘  r’  r“  r†  rè  r/   r.   r"   rÝ  rÝ  y  s   „ ñó	#ór.   rÝ  c           
     ót  — t        t        d«      r|s| S |du rd}t        d«      }t        j                  |› d|› d�«       |dk(  rt        j
                  |› d|› d	�«       d
}t        j                  «       }	 t        j                  | |d¬«      } t        j                  «       |z
  }	d}
|rút        j                  dd|||¬«      }|r|j                  dk(  r|j                  «       }t        j                  «       }t        j                  «       5  |r?|j                  dv r1t        j                  |j                  «      5   | |«      }ddd«       n | |«      }ddd«       |j                  dk(  rt        j                  j!                  |«       t        j                  «       |z
  }
|	|
z   }|r&t        j                  |› d|d›d|	d›d|
d›d�«       | S t        j                  |› d|	d›d�«       | S # t        $ r&}t        j
                  |› d|› �«       | cY d}~S d}~ww xY w# 1 sw Y   ŒÓxY w# 1 sw Y   Œ×xY w)u  Compile a model with torch.compile and optionally warm up the graph to reduce first-iteration latency.

    This utility attempts to compile the provided model using the inductor backend. If compilation is unavailable or
    fails, the original model is returned unchanged. An optional warmup performs a single forward pass on a dummy input
    to prime the compiled graph and measure compile/warmup time.

    Args:
        model (torch.nn.Module): Model to compile.
        device (torch.device): Inference device used for warmup and autocast decisions.
        imgsz (int, optional): Square input size to create a dummy tensor with shape (1, 3, imgsz, imgsz) for warmup.
        use_autocast (bool, optional): Whether to run warmup under autocast on CUDA or MPS devices.
        warmup (bool, optional): Whether to execute a single dummy forward pass to warm up the compiled model.
        mode (bool | str, optional): torch.compile mode. True â†’ "default", False â†’ no compile, or a string like
            "default", "reduce-overhead", "max-autotune-no-cudagraphs".

    Returns:
        (torch.nn.Module): Compiled model if compilation succeeds, otherwise the original unmodified model.

    Examples:
        >>> device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
        >>> # Try to compile and warm up a model with a 640x640 input
        >>> model = attempt_compile(model, device=device, imgsz=640, use_autocast=True, warmup=True)

    Notes:
        - If the current PyTorch build does not provide torch.compile, the function returns the input model immediately.
        - Warmup runs under torch.inference_mode and may use torch.autocast for CUDA/MPS to align compute precision.
        - CUDA devices are synchronized after warmup to account for asynchronous kernel execution.
    ÚcompileTÚdefaultzcompile:z starting torch.compile with 'z	' mode...zmax-autotunez mode='zB' not recommended, using mode='max-autotune-no-cudagraphs' insteadzmax-autotune-no-cudagraphsÚinductor)r:  Úbackendz. torch.compile failed, continuing uncompiled: Nr  rY   rW   r�   r6   >   re   r6   z complete in rÏ   zs (compile zs + warmup zs)z compile complete in zs (no warmup))rq   r'   r   r   rv   rw  rš   Úperf_counterrë  r?   r«   rÅ   r¤  r*   r5   r6   r™   )rè   r7   rê   Úuse_autocastÚwarmupr:  rç  Út0r©  Ú	t_compileÚt_warmÚdummyÚt1rJ  Útotals                  r"   Úattempt_compilerø  ¬  s#  € ôH ”5˜)Ô$©DØˆàˆt�|ØˆÜ�jÓ!€FÜ
‡K�K�6�(Ð8¸¸¸iÐHÔIØˆ~ÒÜ�‰˜&˜ ¨¨Ð.pÐqÔrØ+ˆÜ	×	Ñ	Ó	€BðÜ—‘˜e¨$¸
ÔCˆô ×!Ñ!Ó# bÑ(€Ià€FÙä—‘˜A˜q %¨°vÔ>ˆÙ˜FŸK™K¨6Ò1Ø—J‘J“LˆEÜ×ÑÓ ˆÜ×!Ñ!Ó#ñ 	!Ù §¡¨Ñ >Ü—^‘^ F§K¡KÓ0ñ %Ù˜e›�A÷%ð %ñ ˜%“L�÷	!ð �;‰;˜&Ò Ü�J‰J×"Ñ" 6Ô*Ü×"Ñ"Ó$ rÑ)ˆà˜Ñ€EÙÜ�‰�v�h˜m¨E°#¨;°kÀ)ÈCÀÐP[Ð\bÐcfÐ[gÐgiÐjÔkð €Lô 	�‰�v�hÐ3°I¸c°?À-ÐPÔQØ€Løô7 ò Ü�‰˜&˜Ð!OÐPQÈsÐSÔTØ�ûðú÷%ð %ú÷	!ð 	!úsB   Á8G0 Ä0H.Ä>	H"ÅH.Ç0	HÇ9HÈHÈHÈ"H+	È'H.È.H7)r   rs   )r6   )r2   Úboolr7   rj   )rU   FT)FTé€  )rú  )r7  Fr  )r/   r/   )r/   )rÃ   ú	nn.ModuleÚreturnrû  )r  r7  éd   )r   F)zbest.ptrU   N)r¨  z
str | Pathrˆ   rj   r„  zdict[str, Any] | Nonerü  zdict[str, Any]r_   )é
   Nr   )rú  FFrì  )rè   útorch.nn.Moduler7   ztorch.devicerê   rs   rð  rù  rñ  rù  r:  z
bool | strrü  rÿ  )^Ú
__future__r   Ú	functoolsrË  r=  r   ro  rš   Ú
contextlibr   Úcopyr   r   Úpathlibr   Útypingr   Únumpyrq  r'   Útorch.distributedÚdistributedr   Útorch.nnr°   Útorch.nn.functionalÚ
functionalrB  Úultralyticsr	   r=   r
   r   r   r   r   r   r   r   r   Úultralytics.utils.checksr   Úultralytics.utils.cpur   Úultralytics.utils.patchesr   r&   r)   Ú
TORCH_1_11r3   r‚   Ú	TORCH_2_1Ú	TORCH_2_3Ú	TORCH_2_4Ú	TORCH_2_8Ú	TORCH_2_9Ú
TORCH_2_10ÚTORCHVISION_0_10ÚTORCHVISION_0_11ÚTORCHVISION_0_13ÚTORCHVISION_0_18rw  r#   r0   r5   Ú	lru_cacherA   rI   r—   r›   rº   r¾   r÷   rÕ   rÖ   r  rå   r(  r5  rH  rS  rY  r^  r  rj  ry  rx  r|  r­  rµ  r»  rÛ  rÝ  rø  r/   r.   r"   ú<module>r     s’  ðõ #ã Û 	Û Û 	Û Û Ý %Ý Ý Ý Ý ã Û Ý  Ý ß Ð å #÷
÷ 
õ 
õ 3Ý )Ý 0ñ ˜-¨Ó1€	Ù˜=¨(Ó3€
Ù˜=¨(Ó3€
Ù˜=¨(Ó3€
Ù˜-¨Ó1€	Ù˜-¨Ó1€	Ù˜-¨Ó1€	Ù˜-¨Ó1€	Ù˜-¨Ó1€	Ù˜-¨Ó1€	Ù˜=¨(Ó3€
Ù Ð!4°hÓ?Ð Ù Ð!4°hÓ?Ð Ù Ð!4°hÓ?Ð Ù Ð!4°hÓ?Ð Ù
‰}˜]¨IÔ6Ø€F‡N�Nð	Bôð ò	Mó ð	Mò
ô0ð8 ×Ññ	7ó ð	7ð ×ÑñNó ðNózòzò&òB(óB* òZ6ò
Iò
óB%óPòB
ó?ó,ó tò	^óó&Vóò2+÷=9ñ =9ô@9òxð" òó ðó0R÷j0ñ 0ðl ØØØ ðLØðLàðLð ðLð ð	Lð
 ðLð ðLð ôLr.   