
    FPh_                     &   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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mZmZmZ d dlmZ 	 d dlZ eej8                  d      Z! eej8                  d	      Z"ed
e#fd       Z$d Z%d Z&d+dZ'd Z(d Z)d Z*d,dZ+d Z,d Z-d Z.d-dZ/d-dZ0d Z1d.dZ2d Z3d/dZ4d Z5d0dZ6d Z7d Z8d1d Z9d2d!Z: G d" d#      Z;d3d$ee<e
f   d%e<d&dfd'Z=d4d(Z> G d) d*      Z?y# e $ r dZY w xY w)5    N)contextmanager)deepcopy)Path)Union)DEFAULT_CFG_DICTDEFAULT_CFG_KEYSLOGGER__version__)check_versionz1.9.0z2.0.0
local_rankc              #   
  K   t         j                  j                         xr t         j                  j                         }|r| dvrt	        j
                  | g       d |r| dk(  rt	        j
                  dg       yyyw)zcDecorator to make all processes in distributed training wait for each local_master to do something.)r   )
device_idsNr   )torchdistributedis_availableis_initializeddistbarrier)r   initializeds     hC:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\ultralytics/utils/torch_utils.pytorch_distributed_zero_firstr      si      ##002Yu7H7H7W7W7YKz0-	zQ$ '{s   BBc                      d } | S )zXApplies 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 )zNApplies appropriate torch decorator for inference mode based on torch version.)	TORCH_1_9r   is_inference_mode_enabledinference_modeno_grad)fns    r   decoratez&smart_inference_mode.<locals>.decorate-   s>    88:IKIE((KBOO5==KBOO     )r    s    r   smart_inference_moder#   *   s    P Or!   c                      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      S )z=Return a string with system CPU information, i.e. 'Apple M2'.r   N)	brand_rawhardware_rawarch_string_raw      unknownz(R) zCPU z@ )cpuinfoget_cpu_infogetreplace)r,   kinfostrings       r   r-   r-   7   sx    6A!DXXaddlad!!!A$PYZF>>%$,,VR8@@rJJr!   c                    t        | t        j                        r| S dt         dt	        j
                          dt        j                   d}t        |       j                         } dD ]  }| j                  |d      }  | dk(  }| dv }|s|rd	t        j                  d
<   n!| r| dk(  rd} t        j                  j                  d
d      }| t        j                  d
<   t        j                  j                         r:t        j                  j                         t        | j                  dd            k\  st!        j"                  |       t        j                  j                         dk(  rdnd}	t%        d|  dt        j                  j                          dt        j                  j                          d| d|	 
      |s|st        j                  j                         r| r| j'                  d      nd}
t        |
      }|dkD  r7|dkD  r2||z  dk7  r*t%        d| d| d||z  |z   d||z  |z  |z    d| d      dt        |      dz   z  }t)        |
      D ]T  \  }}t        j                  j+                  |      }||dk(  rdn| d| d|j,                   d|j.                  d z  d!d"z  }V d#}nW|rBt0        r<t        j2                  j4                  j                         r|d$t7                d%z  }d&}n|d't7                d%z  }d}|r't!        j"                  |r|n|j9                                t        j                  |      S )(a  
    Selects the appropriate PyTorch device based on the provided arguments.

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

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

    Returns:
        (torch.device): Selected device.

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

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

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

    Note:
        Sets the 'CUDA_VISIBLE_DEVICES' environment variable for specifying which GPUs to use.
    zUltralytics YOLOvu    🚀 Python-z torch- )zcuda:none()[]'r4   r+   cpu)mpszmps:0z-1CUDA_VISIBLE_DEVICEScuda0N,r   z}See https://pytorch.org/get-started/locally/ for up-to-date torch install instructions if no CUDA devices are seen by torch.
zInvalid CUDA 'device=z' requested. Use 'device=cpu' or pass valid CUDA device(s) if available, i.e. 'device=0' or 'device=0,1,2,3' for Multi-GPU.

torch.cuda.is_available(): z
torch.cuda.device_count(): z%
os.environ['CUDA_VISIBLE_DEVICES']: 
r(   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 (, i   z.0fzMiB)
zcuda:0zMPS (z)
r<   zCPU ()
isinstancer   devicer
   platformpython_versionstrlowerr/   osenvironr.   r>   r   device_countlenr	   r1   
ValueErrorsplit	enumerateget_device_propertiesnametotal_memory	TORCH_2_0backendsr<   r-   rstrip)rE   batchnewlineverbosesremover;   r<   visibleinstalldevicesnspaceidpargs                    r   select_devicere   A   s&   D &%,,'
K=h6M6M6O5PPWX]XiXiWjjklA[ F?+ @
E/C
$
$C
c-1

)*	VF**..!7>-3

)*

'')ejj.E.E.G3v~~^aceOfKg.gKKN=BZZ=T=T=VZ[=[:ac 4VH == >CZZ=T=T=V<W<UZZ=T=T=V<WEgYb 'y* + + suzz668'-&,,s#3Lq5UQY519>wug-OPQsR_`eij`jmn`n_o p'',zA~'9&::ijkillmo p ps1vz"g&DAq

003A!q&Be,E!BqvvhbSZA[\_@``fggA ' 	u~~11>>@	u\^$C((	u\^$C((Aahhj1<<r!   c                      t         j                  j                         rt         j                  j                          t	        j                         S )zPyTorch-accurate time.)r   r>   r   synchronizetimer"   r!   r   	time_syncri      s.    zz 

 99;r!   c           
         t        j                  | j                  | j                  | j                  | j
                  | j                  | j                  | j                  d      j                  d      j                  | j                  j                        }| j                  j                         j                  | j                  d      }t        j                   |j                  j#                  t        j$                  |j&                  |j(                  z                     }|j                  j+                  t        j,                  ||      j                  |j                  j.                               | j0                  Dt        j2                  | j                  j5                  d      | j                  j                        n| j0                  }|j0                  |j                  j7                  |j8                        j#                  t        j$                  |j(                  |j&                  z               z
  }|j0                  j+                  t        j,                  ||j;                  dd            j;                  d      |z          |S )z\Fuse Conv2d() and BatchNorm2d() layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/.T)kernel_sizestridepaddingdilationgroupsbiasFr   r   rE   r(   )nnConv2din_channelsout_channelsrk   rl   rm   rn   ro   requires_grad_toweightrE   cloneviewr   diagdivsqrtepsrunning_varcopy_mmshaperp   zerossizemulrunning_meanreshape)convbn	fusedconvw_convw_bnb_convb_bns          r   fuse_conv_and_bnr      s   		$**++&*&6&6!%"&,,#'==!%#% &4^E%:22dkk>P>P;Q  [[ %%d&7&7<F::biimmEJJrvv/F$GHID588D&166y7G7G7M7MNO MQIIL]U[[))!,T[[5G5GHcgclclF77RYY]]2??377

2>>TVTZTZCZ8[\\DNN$r1(=>FFrJTQRr!   c                 2   t        j                  | j                  | j                  | j                  | j
                  | j                  | j                  | j                  | j                  d	      j                  d      j                  | j                  j                        }| j                  j                         j                  | j                  d      }t!        j"                  |j                  j%                  t!        j&                  |j(                  |j*                  z                     }|j                  j-                  t!        j.                  ||      j                  |j                  j0                               | j2                  Dt!        j4                  | j                  j7                  d      | j                  j                        n| j2                  }|j2                  |j                  j9                  |j:                        j%                  t!        j&                  |j*                  |j(                  z               z
  }|j2                  j-                  t!        j.                  ||j=                  dd            j=                  d      |z          |S )z0Fuse ConvTranspose2d() and BatchNorm2d() layers.T)rk   rl   rm   output_paddingrn   ro   rp   Fr   r(   rq   )rr   ConvTranspose2drt   ru   rk   rl   rm   r   rn   ro   rv   rw   rx   rE   ry   rz   r   r{   r|   r}   r~   r   r   r   r   rp   r   r   r   r   r   )deconvr   
fuseddconvw_deconvr   r   r   s          r   fuse_deconv_and_bnr      s   ##F$6$6$*$7$7060B0B+1==,2NN393H3H-3__+1==)-/ 0>~e/DRRH\H\E]  }}""$))&*=*=rBH::biimmEJJrvv/F$GHIDEHHT8499*:K:K:Q:QRS QWP[P[PcU[[++A.v}}7K7KLioititF77RYY]]2??377

2>>TVTZTZCZ8[\\DOO%((4A)>?GGKdRSr!   c                    |syt        |       }t        |       }t        t        | j	                                     }|rt        j                  dddddddddd	d
ddddddddd       t        | j                               D ]  \  }\  }}	|j                  dd      }t        j                  d|||	j                  |	j                         t        |	j                        |	j                         |	j                         |	j                  fz          t!        | |      }
 t#        | dd              rdnd}|
rd|
ddnd}t#        | dd      xs t#        | di       j%                  dd      }t'        |      j(                  j                  dd      xs d}t        j                  | d| d| d | d!| d"|        ||||
fS )#z_
    Model information.

    imgsz may be int or list, i.e. imgsz=640 or imgsz=[640, 320].
    Nlayerz>5r4   rR   z>40gradientz>9
parametersz>12r   z>20muz>10sigmazmodule_list.r+   z)%5g %40s %9s %12g %20s %10.3g %10.3g %10sis_fusedc                       y)NFr"   r"   r!   r   <lambda>zmodel_info.<locals>.<lambda>   s    Ur!   z (fused)rC   .1fz GFLOPs	yaml_fileyamlyoloYOLOModelz summaryz: z	 layers, z parameters, z
 gradients)get_num_paramsget_num_gradientsrM   listmodulesr	   r1   rP   named_parametersr/   requires_gradnumelr   meanstddtype	get_flopsgetattrr.   r   stem)modeldetailedrY   imgszn_pn_gn_lra   rR   rc   flopsfusedfsr   
model_names                  r   
model_infor      s    

C
E
"C
d5==?#
$Crl!F3<qBqc8J!GTW=XYZ^_bYccdelmpdqr	t%e&<&<&>?LAya<<3DKKCD!//1779d177mQVVXWXW\W\W^`a`g`ghi j @
 eU#EC'%]CEJ2E$)2eC[	 rB{B/b75&"3M3Q3QR]_a3bIi%%--ff=HJ
KK:,hugRuIcU-PSuT^_a^bcd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Nr   .0xs     r   	<genexpr>z!get_num_params.<locals>.<genexpr>   s     5"4Qqwwy"4   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   r   z$get_num_gradients.<locals>.<genexpr>   s     H"4Qqwwy"4s   ))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 )	a  
    Return model info dict with useful model information.

    Example:
        YOLOv8n info for loggers
        ```python
        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   )ProfileModelsrq   z
model/name   )zmodel/parameterszmodel/GFLOPs	inferencezmodel/speed_PyTorch(ms))argsprofileultralytics.utils.benchmarksr   lastrE   popr   r   roundr   	validatorspeed)trainerr   resultss      r   model_info_for_loggersr      s     ||>w~~FNNPQRSL! !/w}} =!)GMM":A>@ */w/@/@/F/F{/SUV)WG%&Nr!   c                    	 t        |       } t        | j                               }t        | d      r-t	        t        | j                  j	                               d      nd}t        j                  d|j                  d   ||f|j                        }t        r+t        j                  t        |       |gd      d   dz  d	z  nd}t        |t              r|n||g}||d   z  |z  |d   z  |z  S # t         $ r Y yw xY w)
zReturn a YOLO model's FLOPs.rl       r(   rq   FinputsrY   r       eAr)   )de_parallelnextr   hasattrmaxintrl   r   emptyr   rE   thopr   r   rD   r   	Exception)r   r   rc   rl   imr   s         r   r   r     s    	E"!!#$5<UH5MS))+,b1SU[[!QWWQZ8JZ^Xe_bT5I!LsRUVVde#E40uenuQx&(583f<< s   C-C0 0	C<;C<c                 R   t         rt        |       } t        | j                               }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  }t!        |t"              r|n||g}||d   z  |z  |d   z  |z  }|S y# 1 sw Y   YxY w)z'Compute model FLOPs (thop alternative).rl   r   r)   r(   rq   T)
with_flopsNc              3   4   K   | ]  }|j                     y wr   )r   r   s     r   r   z0get_flops_with_torch_profiler.<locals>.<genexpr>&  s     9%8AGG%8s   r   r   )rT   r   r   r   r   r   r   rl   r   r   r   rE   profilerr   r   key_averagesrD   r   )r   r   rc   rl   r   profr   s          r   get_flops_with_torch_profilerr     s    E"!!#$6=eX6N#c%,,**,-r2TVZ[[[[!QWWQZ8J^^##t#4"I 59T%6%6%899C?#E40uena 6)E!H4v= 54s   <	DD&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                  fv sd|_         y)z*Initialize model weights to random values.gMbP?gQ?TN)r   typerr   rs   BatchNorm2dr~   momentum	Hardswish	LeakyReLUReLUReLU6SiLUinplace)r   mts      r   initialize_weightsr   -  sq    ]]_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 )zScales and pads an image tensor of shape img(bs,3,y,x) based on given ratio and grid size gs, optionally
    retaining the original shape.
          ?r)   NbilinearF)r   modealign_cornersc              3   Z   K   | ]"  }t        j                  |z  z        z   $ y wr   )mathceil)r   r   gsratios     r   r   zscale_img.<locals>.<genexpr>D  s(     ?1		!e)b.)B.s   (+r   r(   gS㥛?)value)r   r   Finterpolatepad)imgr  
same_shaper  hwrZ   s    ` `   r   	scale_imgr  :  s     |
99QR=DAq	QYQY(A
--!*E
JC?A?155q!ad(Aq1Q4x0>>r!   c                     t        |t        j                        rt        |j	                               }t        j                  | |z        |z  S )z'Returns nearest x divisible by divisor.)rD   r   Tensorr   r   r  r  )r   divisors     r   make_divisibler  H  s8    '5<<(gkkm$99Q[!G++r!   c                     |j                   j                         D ]7  \  }}t        |      r||vs|j                  d      s||v r+t	        | ||       9 y)zdCopies attributes from object 'b' to object 'a', with options to include/exclude certain attributes._N)__dict__itemsrM   
startswithsetattr)abincludeexcluder0   vs         r   	copy_attrr  O  sK    

  "1LQg-!,,s2CqG|Aq!	 #r!   c                  Z    t        d t        t        j                        D              dz
  S )zYReturn second-most (for maturity) recently supported ONNX opset by this version of torch.c              3   B   K   | ]  }d |v st        |dd         yw)symbolic_opset   N)r   )r   r0   s     r   r   z#get_latest_opset.<locals>.<genexpr>Z  s%     N$4q8HA8Ms1RS6{$4s   	r(   )r   varsr   onnxr"   r!   r   get_latest_opsetr&  X  s"    ND$4NNQRRRr!   c                     | j                         D ci c]?  \  }|v st        fd|D              s |j                  |   j                  k(  s=|A c}}S c c}}w )zjReturns a dictionary of intersecting keys with matching shapes, excluding 'exclude' keys, using da values.c              3   &   K   | ]  }|v 
 y wr   r"   )r   r   r0   s     r   r   z"intersect_dicts.<locals>.<genexpr>_  s     :Ww!1A:ws   )r  allr   )dadbr  r0   r  s      ` r   intersect_dictsr,  ]  sW    XXZsZTQ17s:Ww:W7W\]\c\cgijkglgrgr\rAqDZssss   AAAAc                 ~    t        | t        j                  j                  t        j                  j                  f      S )z+Returns True if model is of type DP or DDP.)rD   rr   parallelDataParallelDistributedDataParallelr   s    r   is_parallelr1  b  s(    ebkk668[8[\]]r!   c                 4    t        |       r| j                  S | S )zODe-parallelize a model: returns single-GPU model if model is of type DP or DDP.)r1  moduler   s    r   r   r   g  s    &u-5<<858r!   c                       fdS )zaReturns a lambda function for sinusoidal ramp from y1 to y2 https://arxiv.org/pdf/1812.01187.pdf.c                 t    dt        j                  | t         j                  z  z        z
  dz  z
  z  z   S )Nr(   r)   )r  cospi)r   stepsy1y2s    r   r   zone_cycle.<locals>.<lambda>n  s3    q488AK%$788A="r'JROr!   r"   )r9  r:  r8  s   ```r   	one_cycler;  l  s	    OOr!   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        j                  d       dt        j                  j                  _        y)	zeInitialize random number generator (RNG) seeds https://pytorch.org/docs/stable/notes/randomness.html.T)	warn_onlyz:4096:8CUBLAS_WORKSPACE_CONFIGPYTHONHASHSEEDuB   WARNING ⚠️ Upgrade to torch>=2.0.0 for deterministic training.FN)randomseednpr   manual_seedr>   manual_seed_allrT   use_deterministic_algorithmsrU   cudnndeterministicrJ   rK   rH   r	   warning)rA  rG  s     r   
init_seedsrI  q  s    
KKIINN4	d	JJ4 	JJt$..ttD15ENN  .4=BJJ01+.t9BJJ'(NN_`**51-2*r!   c                   &    e Zd ZdZddZd ZddZy)ModelEMAa^  Updated Exponential Moving Average (EMA) from https://github.com/rwightman/pytorch-image-models
    Keeps a moving average of everything in the model state_dict (parameters and buffers)
    For EMA details see https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
    To disable EMA set the `enabled` attribute to `False`.
    c                     t        t        |            j                         | _        || _        fd| _        | j                  j                         D ]  }|j                  d        d| _        y)zCreate EMA.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updatesrO  r   rv   enabled)selfr   rO  rP  rS  rc   s     ``  r   __init__zModelEMA.__init__  sW    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)zUpdate EMA parameters.r(   N)
rT  rS  rO  r   
state_dictrR  r  r   is_floating_pointdetach)rU  r   rb   msdr0   r  s         r   updatezModelEMA.update  s    <<LLAL

4<<(Ae$//1C++-335177,,FA!a%3q6==?22A 6 r!   c                 N    | j                   rt        | j                  |||       yy)zCUpdates attributes and saves stripped model with optimizer removed.N)rT  r  rR  )rU  r   r  r  s       r   update_attrzModelEMA.update_attr  s     <<dhhw8 r!   N)gH.?i  r   )r"   )process_groupreducer)__name__
__module____qualname____doc__rV  r\  r^  r"   r!   r   rK  rK    s    
39r!   rK  frZ   returnc           	         t        j                  | t        j                  d            }d|vrt        j                  d|  d       yt        |d   d      r t        |d   j                        |d   _        d|v ri t        |d   nd}|j                  d	      r|d	   |d<   d
D ]  }d||<   	 d|d<   |d   j                          |d   j                         D ]	  }d|_         |j                         D ci c]  \  }}|t        v s|| c}}|d<   t        j                  ||xs |        t         j"                  j%                  |xs |       dz  }t        j                  d|  d|rd| dnd d|dd       yc c}}w )a'  
    Strip optimizer from 'f' to finalize training, optionally save as 's'.

    Args:
        f (str): file path to model to strip the optimizer from. Default is 'best.pt'.
        s (str): file path to save the model with stripped optimizer to. If not provided, 'f' will be overwritten.

    Returns:
        None

    Example:
        ```python
        from pathlib import Path
        from ultralytics.utils.torch_utils import strip_optimizer

        for f in Path('path/to/weights').rglob('*.pt'):
            strip_optimizer(f)
        ```
    r;   )map_locationr   z	Skipping z , not a valid Ultralytics model.Nr   
train_argsrR  )	optimizerbest_fitnessrR  rS  r   epochFg    .AzOptimizer stripped from r@   z
 saved as r+   r4   r   MB)r   loadrE   r	   r1   r   dictr   r   r.   halfr   r   r  r   saverJ   pathgetsize)re  rZ   r   r   r0   rc   r  mbs           r   strip_optimizerru    sx   ( 	

15<<#67Aais"BCDqz6"qz/'
6Ba6G22!L/2TDuuU|uX'
:! ;AgJgJOOwZ""$ %(,

N1=M8Mq!tNAlO	JJq!&q	a	 3	&B
KK*1#QAA3a/@2.NaPRSVxWYZ[	 Os   :F F c                    g }t        |t        j                        st        |      }t	        j
                  dddddddddddd	d
d	       t        | t              r| n| gD ]  }|j                  |      }d|_        t        |t              r|n|gD ]O  }t        |d      r|j                  |      n|}t        |d      rFt        |t        j                        r,|j                  t        j                  u r|j                         n|}ddg d}	}}	 t        r"t        j                  ||gd      d   dz  dz  nd}
	 t#        |      D ]  }t%               |	d<    ||      }t%               |	d<   	 t        |t              rt'        d |D              n|j'                         j)                          t%               |	d<   ||	d   |	d   z
  dz  |z  z  }||	d   |	d   z
  dz  |z  z  } t        j,                  j/                         r!t        j,                  j1                         dz  nd}d |fD        \  }}t        |t2        j4                        r t'        d |j7                         D              nd}t	        j
                  |d|
d|d|d|dt9        |      d	t9        |      d	       |j;                  ||
|||||g       t        j,                  j=                          R  |S # t         $ r d}
Y w xY w# t         $ r t+        d      |	d<   Y [w xY w# t         $ r0}t	        j
                  |       |j;                  d       Y d}~d}~ww xY w)aU  
    Ultralytics speed, memory and FLOPs profiler.

    Example:
        ```python
        from ultralytics.utils.torch_utils import profile

        input = torch.randn(16, 3, 640, 640)
        m1 = lambda x: x * torch.sigmoid(x)
        m2 = nn.SiLU()
        profile(input, [m1, m2], n=100)  # profile over 100 iterations
        ```
    Paramsz>12sGFLOPszGPU_mem (GB)z>14szforward (ms)zbackward (ms)inputz>24soutputTrw   rp  r   )r   r   r   Fr   r   r)   r(   c              3   <   K   | ]  }|j                           y wr   )r   )r   yis     r   r   zprofile.<locals>.<genexpr>  s     2"RVVXr   nani  c              3   ~   K   | ]5  }t        |t        j                        rt        |j                        nd  7 yw)r   N)rD   r   r  tupler   r   s     r   r   zprofile.<locals>.<genexpr>  s/     ibh]^Au||1LuQWW~RXXbhs   ;=c              3   <   K   | ]  }|j                           y wr   r   r   s     r   r   zprofile.<locals>.<genexpr>  s     :>a	>r   12z12.4gz>14.3fz14.4gN)rD   r   rE   re   r	   r1   r   rw   r   r   r  r   float16rp  r   r   r   rangeri   r   backwardfloatr>   r   memory_reservedrr   Moduler   rH   appendempty_cache)ry  opsr_   rE   r   r   r   tftbr   r   r  ymems_ins_outrc   es                     r   r   r     s*    Gfell+v&
KK8D/(40EnUYEZ[jkoZp4.$1 2 !-UE7:DDL"3-C58A '4 0VaA#Av.:a3NSTSZSZ^c^k^kSkqrA1iABSWQsEB1EKaO]^%qA$;AaD!A$;AaD,6@D6I222qUUW``b({! 1Q4!A$;$.22B1Q4!A$;$.22B " =BJJ<S<S<Uejj002S8[\icdfgbhie>HBII>VC:1<<>::\]qfU5M#fbZ5zRUVZR[\`Qabefkblmqarst5#r2tUCD JJ""$= 9 ;D N3   % ,$U|!,  %At$$%sP   *K00L 4ALD	L 0K?>K?L	L L	L  	M)&MMc                       e Zd ZdZddZd Zy)EarlyStoppingzkEarly stopping class that stops training when a specified number of epochs have passed without improvement.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   infFN)rk  
best_epochr  patiencepossible_stop)rU  r  s     r   rV  zEarlyStopping.__init__  s+       0E%L"r!   c           	      .   |y|| j                   k\  r|| _        || _         || j                  z
  }|| j                  dz
  k\  | _        || j                  k\  }|r=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(   z;Stopping training 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.)rk  r  r  r  r	   r1   )rU  rl  fitnessdeltastops        r   __call__zEarlyStopping.__call__  s     ?d'''#DO 'D'"t}}q'89%KKUVZVcVcUd e::>//9J K<<@MM? K\] ^ r!   N)2   )ra  rb  rc  rd  rV  r  r"   r!   r   r  r    s    u
#r!   r  )r+   r   FT)FT  )r  )r   Fr   )r"   r"   )r"   )r  r   d   )r   F)zbest.ptr+   )
   N)@r  rJ   rF   r@  rh   
contextlibr   copyr   pathlibr   typingr   numpyrB  r   torch.distributedr   r   torch.nnrr   torch.nn.functional
functionalr  ultralytics.utilsr   r   r	   r
   ultralytics.utils.checksr   r   ImportErrorr   rT   r   r   r#   r-   re   ri   r   r   r   r   r   r   r   r   r   r  r  r  r&  r,  r1  r   r;  rI  rK  rH   ru  r   r  r"   r!   r   <module>r     sV    	    %           U U 2 %++W5	%++W5	 %S % %
KSl02 86
I
4 
?,S
t
^
9
P
3* 9  9F(\uS$Y' (\ (\T (\V6r( (k  Ds   D DD