
    FPh                     t   d dl Z d dlmZ d dlmZ d dl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mZmZmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& d dl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z- d dl.m/Z/m0Z0m1Z1 d dl2m3Z3m4Z4m5Z5m6Z6 d dl7m8Z8 d d	l9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZA 	 d dlBZB G d
 dej                        ZE G d deE      ZF G d deF      ZG G d deF      ZH G d deE      ZI G d deF      ZJ G d dej                        ZLe j                  d d       ZNd ZOd!dZPd!dZQd"dZRd ZSd ZTd ZUy# eC$ r dZBY w xY w)#    N)deepcopy)Path)AIFIC1C2C3C3TRSPPSPPF
BottleneckBottleneckCSPC2fC3GhostC3xClassifyConcatConvConv2ConvTransposeDetectDWConvDWConvTranspose2dFocusGhostBottleneck	GhostConvHGBlockHGStemPoseRepC3RepConvRTDETRDecoderSegment)DEFAULT_CFG_DICTDEFAULT_CFG_KEYSLOGGERcolorstremojis	yaml_load)check_requirementscheck_suffix
check_yaml)v8ClassificationLossv8DetectionLoss
v8PoseLossv8SegmentationLoss)feature_visualization)fuse_conv_and_bnfuse_deconv_and_bninitialize_weightsintersect_dictsmake_divisible
model_info	scale_img	time_syncc                   r     e Zd ZdZd ZddZddZd Zd ZddZ	ddZ
dd	Z fd
ZddZddZd Z xZS )	BaseModelz]The BaseModel class serves as a base class for all the models in the Ultralytics YOLO family.c                 z    t        |t              r | j                  |g|i |S  | j                  |g|i |S )a&  
        Forward pass of the model on a single scale. Wrapper for `_forward_once` method.

        Args:
            x (torch.Tensor | dict): The input image tensor or a dict including image tensor and gt labels.

        Returns:
            (torch.Tensor): The output of the network.
        )
isinstancedictlosspredict)selfxargskwargss       _C:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\ultralytics/nn/tasks.pyforwardzBaseModel.forward   sD     a499Q0000t||A////    c                 N    |r| j                  |      S | j                  |||      S )a  
        Perform a forward pass through the network.

        Args:
            x (torch.Tensor): The input tensor to the model.
            profile (bool):  Print the computation time of each layer if True, defaults to False.
            visualize (bool): Save the feature maps of the model if True, defaults to False.
            augment (bool): Augment image during prediction, defaults to False.

        Returns:
            (torch.Tensor): The last output of the model.
        )_predict_augment_predict_once)r@   rA   profile	visualizeaugments        rD   r?   zBaseModel.predict,   s-     ((++!!!Wi88rF   c                    g g }}| j                   D ]  }|j                  dk7  rMt        |j                  t              r||j                     n#|j                  D cg c]  }|dk(  r|n||    c}}|r| j	                  |||        ||      }|j                  |j                  | j                  v r|nd       |st        ||j                  |j                  |        |S c c}w )a  
        Perform a forward pass through the network.

        Args:
            x (torch.Tensor): The input tensor to the model.
            profile (bool):  Print the computation time of each layer if True, defaults to False.
            visualize (bool): Save the feature maps of the model if True, defaults to False.

        Returns:
            (torch.Tensor): The last output of the model.
        Nsave_dir
modelfr<   int_profile_one_layerappendisaver0   type)r@   rA   rJ   rK   ydtmjs           rD   rI   zBaseModel._predict_once=   s     B2Assby(c2AaccFYZY\Y\8]Y\TUa2g1Q49OY\8]''1b1!AHH!##*Q5%ayI   9^s   C"c                 ~    t        j                  d| j                  j                   d       | j	                  |      S )zFPerform augmentations on input image x and return augmented inference.   WARNING ⚠️ zW does not support augmented inference yet. Reverting to single-scale inference instead.)r%   warning	__class____name__rI   )r@   rA   s     rD   rH   zBaseModel._predict_augmentU   s>    )@)@(A BF G 	H!!!$$rF   c           	         || j                   d   k(  xr t        |t              }t        r4t        j                  ||r|j                         n|gd      d   dz  dz  nd}t               }t        d      D ]  } ||r|j                         n|        |j                  t               |z
  dz         || j                   d   k(  r!t        j                  d	d
ddd
ddd
d       t        j                  |d   dd|dd|j                  dd|j                          |r+t        j                  t        |      dddd
ddd
d       yy)a  
        Profile the computation time and FLOPs of a single layer of the model on a given input. Appends the results to
        the provided list.

        Args:
            m (nn.Module): The layer to be profiled.
            x (torch.Tensor): The input data to the layer.
            dt (list): A list to store the computation time of the layer.

        Returns:
            None
        rN   F)inputsverboser   g    eA   
   d   z	time (ms)z>10s GFLOPsparamsz  modulez10.2f10.0f  -z  TotalN)rR   r<   listthoprJ   copyr8   rangerV   r%   infonprY   sum)r@   r\   rA   r[   cflopst_s           rD   rU   zBaseModel._profile_one_layer[   s1    B7Jq$$7^bQA1'=uMaPSVVYZZhiKrA!affh# 
		9;?c)*

1KK;t,Aht_Aht_HUVr"venAeE]!ADD<r!&&JKKK3r75/3t*Ac$ZwGH rF   c                    | j                         sL| j                  j                         D ]  }t        |t        t
        t        f      rnt        |d      rbt        |t
              r|j                          t        |j                  |j                        |_
        t        |d       |j                  |_        t        |t              rNt        |d      rBt!        |j"                  |j                        |_        t        |d       |j                  |_        t        |t$              s|j                          |j                  |_         | j'                  |       | S )z
        Fuse the `Conv2d()` and `BatchNorm2d()` layers of the model into a single layer, in order to improve the
        computation efficiency.

        Returns:
            (nn.Module): The fused model is returned.
        bn)re   )is_fusedrR   modulesr<   r   r   r   hasattr
fuse_convsr1   convr{   delattrforward_fuserE   r   r2   conv_transposer    rs   )r@   re   r\   s      rD   fusezBaseModel.fuset   s     }}ZZ'')a$v!67GAt<L!!U+-affadd;AFAt$ !AIa/GAt4D'9!:J:JADD'QA$At$ !AIa)LLN !AI * IIgI&rF   c                     t        d t        j                  j                         D              t	        fd| j                         D              |k  S )aN  
        Check if the model has less than a certain threshold of BatchNorm layers.

        Args:
            thresh (int, optional): The threshold number of BatchNorm layers. Default is 10.

        Returns:
            (bool): True if the number of BatchNorm layers in the model is less than the threshold, False otherwise.
        c              3   0   K   | ]  \  }}d |v s|  yw)NormN ).0kvs      rD   	<genexpr>z%BaseModel.is_fused.<locals>.<genexpr>   s     D!4A!1!4s   c              3   6   K   | ]  }t        |        y wN)r<   )r   r   r{   s     rD   r   z%BaseModel.is_fused.<locals>.<genexpr>   s     =n:a$ns   )tuplenn__dict__itemsru   r}   )r@   threshr{   s     @rD   r|   zBaseModel.is_fused   s>     D!2!2!4DD=dlln==FFrF   c                      t        | |||      S )a^  
        Prints model information.

        Args:
            detailed (bool): if True, prints out detailed information about the model. Defaults to False
            verbose (bool): if True, prints out the model information. Defaults to False
            imgsz (int): the size of the image that the model will be trained on. Defaults to 640
        )detailedre   imgsz)r6   )r@   r   re   r   s       rD   rs   zBaseModel.info   s     $7%PPrF   c                     t         |   |      } | j                  d   }t        |t        t
        f      rE ||j                        |_         ||j                        |_         ||j                        |_        | S )a  
        Applies a function to all the tensors in the model that are not parameters or registered buffers.

        Args:
            fn (function): the function to apply to the model

        Returns:
            (BaseModel): An updated BaseModel object.
        rN   )	super_applyrR   r<   r   r"   strideanchorsstrides)r@   fnr\   ra   s      rD   r   zBaseModel._apply   sa     w~b!JJrNa&'*+!((|AH199AI199AIrF   c           	      Z   t        |t              r|d   n|}|j                         j                         }t	        || j                               }| j                  |d       |rGt        j                  dt        |       dt        | j                  j                                d       yy)z
        Load the weights into the model.

        Args:
            weights (dict | torch.nn.Module): The pre-trained weights to be loaded.
            verbose (bool, optional): Whether to log the transfer progress. Defaults to True.
        rR   F)strictzTransferred /z items from pretrained weightsN)
r<   r=   float
state_dictr4   load_state_dictr%   rs   lenrR   )r@   weightsre   rR   csds        rD   loadzBaseModel.load   s     %/w$= 7kkm&&(c4??#45S/KK,s3xj#djj6K6K6M2N1OOmno rF   c                     t        | d      s| j                         | _        || j                  |d         n|}| j                  ||      S )z
        Compute loss.

        Args:
            batch (dict): Batch to compute loss on
            preds (torch.Tensor | List[torch.Tensor]): Predictions.
        	criterionimg)r~   init_criterionr   rE   )r@   batchpredss      rD   r>   zBaseModel.loss   sG     t[)!002DN.3mU5\*~~eU++rF   c                     t        d      )z0Initialize the loss criterion for the BaseModel.z4compute_loss() needs to be implemented by task heads)NotImplementedErrorr@   s    rD   r   zBaseModel.init_criterion   s    !"XYYrF   FFF)FFT)rg   )FTi  r   )rb   
__module____qualname____doc__rE   r?   rI   rH   rU   r   r|   rs   r   r   r>   r   __classcell__ra   s   @rD   r:   r:      sG    g09"0%I26G	Q$p,ZrF   r:   c                   L     e Zd ZdZd fd	Z fdZedd       Zd Zd Z	 xZ
S )	DetectionModelzYOLOv8 detection model.c           
      p   	 t         
           t        |t              r|n
t	        |       _         j
                  j                  d|      x} j
                  d<   |rI| j
                  d   k7  r7t        j                  d j
                  d    d|        | j
                  d<   t        t         j
                        ||      \   _         _        t         j
                  d         D ci c]  }||  c} _         j
                  j                  dd       _         j                  d   	t        	t         t"        t$        f      rd	} j                  	_        	 fd
}t'        j(                   |t'        j*                  d|||            D cg c]  }||j,                  d   z   c}      	_        	j.                   _        	j1                          nt'        j2                  dg       _        t5                |r& j                          t        j                  d       yyc c}w c c}w )zKInitialize the YOLOv8 detection model with the given config and parameters.chncOverriding model.yaml nc=	 with nc=r   re   inplaceTrN      c                 z    t        t        t        f      rj                  |       d   S j                  |       S )Nr   )r<   r"   r   rE   )rA   r\   r@   s    rD   <lambda>z)DetectionModel.__init__.<locals>.<lambda>   s4    jWdO6TQ 2 iZ^ZfZfghZi irF           N)r   __init__r<   r=   yaml_model_loadyamlgetr%   rs   parse_modelr   rR   rX   rr   namesr   r   r"   r   torchtensorzerosshaper   	bias_initTensorr3   )r@   cfgr   r   re   rW   srE   rA   r\   ra   s   `        @rD   r   zDetectionModel.__init__   s   %c40Coc6J	  $yy}}T266TYYt_"		$'KK3DIIdO3DIbTRS DIIdO +HTYY,?BPW X
DI).tyy)?@)?AaA3i)?@
yy}}Y5 JJrNa&'401AAIiG||gekkRSUWYZ\]F^>_$`>_Q_>_$`aAH((DKKKM,,t,DK 	4 IIKKKO # A %as   2H.H3c           	         |j                   dd }g d}g d}g }t        ||      D ]~  \  }}t        |r|j                  |      n||t	        | j
                  j                                     }t        
| !  |      d   }	| j                  |	|||      }	|j                  |	        | j                  |      }t        j                  |d      dfS )zXPerform augmentations on input image x and return augmented inference and train outputs.r   N)r   g(\?gq=
ףp?)N   N)gsr   rN   )r   zipr7   fliprT   r   maxr   r?   _descale_predrV   _clip_augmentedr   cat)r@   rA   img_sizer   rS   rZ   sifixiyira   s             rD   rH   zDetectionModel._predict_augment   s    7723<!QiFB166":B3t{{?P;QRB$Q'B##BB9BHHRL	  
   #yyB%%rF   c                     | ddddfxx   |z  cc<   | j                  ddd| j                  |   dz
  f|      \  }}}}|dk(  r	|d   |z
  }n|dk(  r|d   |z
  }t        j                  ||||f|      S )zGDe-scale predictions following augmented inference (inverse operation).N   r   rf   r   r   )splitr   r   r   )	pflipsscaler   dimrA   rZ   whclss	            rD   r   zDetectionModel._descale_pred  s     	
!RaR%EAq!''#,*: ;SA1b#A:aAaZaAyy!QC#..rF   c                 z   | j                   d   j                  t        d t              D              }d}|d   j                  d   |z  t        d t        |      D              z  }|d   dd| f   |d<   |d   j                  d   |z  t        fdt        |      D              z  }|d   d|df   |d<   |S )	z$Clip YOLO augmented inference tails.rN   c              3   &   K   | ]	  }d |z    ywr   Nr   r   rA   s     rD   r   z1DetectionModel._clip_augmented.<locals>.<genexpr>  s     *	1Q	   r   r   c              3   &   K   | ]	  }d |z    ywr   r   r   s     rD   r   z1DetectionModel._clip_augmented.<locals>.<genexpr>  s     'A1Qr   .Nc              3   4   K   | ]  }d dz
  |z
  z    yw)r   r   Nr   )r   rA   nls     rD   r   z1DetectionModel._clip_augmented.<locals>.<genexpr>  s     (MHqrAvz):Hs   )rR   r   ru   rr   r   )r@   rZ   gerW   r   s        @rD   r   zDetectionModel._clip_augmented  s    ZZ^*b	**qTZZ^q C'Aa'A$AAtC1"H~!rU[[_!S(ME!H(M%MM"c12g"rF   c                     t        |       S )z5Initialize the loss criterion for the DetectionModel.)r-   r   s    rD   r   zDetectionModel.init_criterion"  s    t$$rF   )zyolov8n.yamlr   NT)r   )rb   r   r   r   r   rH   staticmethodr   r   r   r   r   s   @rD   r   r      s/    !@& / /	%rF   r   c                   *     e Zd ZdZd fd	Zd Z xZS )SegmentationModelzYOLOv8 segmentation model.c                 ,    t         |   ||||       y)zFInitialize YOLOv8 segmentation model with given config and parameters.r   r   r   re   Nr   r   r@   r   r   r   re   ra   s        rD   r   zSegmentationModel.__init__*  s    SRB@rF   c                     t        |       S )z8Initialize the loss criterion for the SegmentationModel.)r/   r   s    rD   r   z SegmentationModel.init_criterion.  s    !$''rF   )zyolov8n-seg.yamlr   NTrb   r   r   r   r   r   r   r   s   @rD   r   r   '  s    $A(rF   r   c                   *     e Zd ZdZd fd	Zd Z xZS )	PoseModelzYOLOv8 pose model.c                     t        |t              st        |      }t        |      r=t	        |      t	        |d         k7  r#t        j                  d|d    d|        ||d<   t        | !  ||||       y)zInitialize YOLOv8 Pose model.	kpt_shapez Overriding model.yaml kpt_shape=z with kpt_shape=r   N)	r<   r=   r   anyro   r%   rs   r   r   )r@   r   r   r   data_kpt_shapere   ra   s         rD   r   zPoseModel.__init__6  sx    #t$!#&C~4#74K@P;Q#QKK:3{;K:LL\]k\lmn-CSRB@rF   c                     t        |       S )z0Initialize the loss criterion for the PoseModel.)r.   r   s    rD   r   zPoseModel.init_criterion?  s    $rF   )zyolov8n-pose.yamlr   NNNTr   r   s   @rD   r  r  3  s    A rF   r  c                   @     e Zd ZdZd fd	Zd Zed        Zd Z xZ	S )ClassificationModelzYOLOv8 classification model.c                 J    t         |           | j                  ||||       y)zNInit ClassificationModel with YAML, channels, number of classes, verbose flag.N)r   r   
_from_yamlr   s        rD   r   zClassificationModel.__init__G  s     RW-rF   c                    t        |t              r|n
t        |      | _        | j                  j	                  d|      x}| j                  d<   |rJ|| j                  d   k7  r8t        j                  d| j                  d    d|        || j                  d<   n)|s'| j                  j	                  dd      st        d      t        t        | j                        ||      \  | _
        | _        t        j                  dg      | _        t        | j                  d         D ci c]  }||  c}| _        | j                          yc c}w )	zBSet YOLOv8 model configurations and define the model architecture.r   r   r   r   NzFnc not specified. Must specify nc in model.yaml or function arguments.r   r   )r<   r=   r   r   r   r%   rs   
ValueErrorr   r   rR   rX   r   r   r   rr   r   )r@   r   r   r   re   rW   s         rD   r  zClassificationModel._from_yamlL  s   %c40Coc6J	  $yy}}T266TYYt_"		$'KK3DIIdO3DIbTRS DIIdODIIMM$5eff +HTYY,?BPW X
DIllA3').tyy)?@)?AaA3i)?@
		 As   &E
c                 J   t        t        | d      r| j                  n| j                               d   \  }}t	        |t
              rJ|j                  j                  |k7  r0t        j                  |j                  j                  |      |_        yyt	        |t        j                        r<|j                  |k7  r,t        | |t        j                  |j                  |             yyt	        |t        j                        r|D cg c]  }t        |       }}t        j                  |v rY|j                  t        j                        }||   j                  |k7  r't        j                  ||   j                  |      ||<   yyt        j                  |v r|j                  t        j                        }||   j                   |k7  rTt        j                  ||   j"                  |||   j$                  ||   j&                  ||   j(                  du      ||<   yyyyc c}w )zIUpdate a TorchVision classification model to class count 'n' if required.rR   rN   N)bias)ro   r~   rR   named_childrenr<   r   linearout_featuresr   Linearin_featuressetattr
SequentialrY   indexConv2dout_channelsin_channelskernel_sizer   r  )rR   r   namer\   rA   typesrW   s          rD   reshape_outputsz#ClassificationModel.reshape_outputs\  s    wug'>EYY[\]_`aa"xx$$*99QXX%9%92> +299%~~#tRYYq}}b%AB $2==)&'(aT!WaE(yyE!KK		*Q4$$*99QqT%5%5r:AaD +e#KK		*Q4$$*99QqT%5%5r1Q4;K;KQqT[[_`ab_c_h_hpt_tuAaD + $ *(s   H c                     t               S )z:Initialize the loss criterion for the ClassificationModel.)r,   r   s    rD   r   z"ClassificationModel.init_criterionq  s    #%%rF   )zyolov8n-cls.yamlr   NT)
rb   r   r   r   r   r  r   r  r   r   r   s   @rD   r
  r
  D  s+    &.
  v v(&rF   r
  c                   :     e Zd ZdZd fd	Zd ZddZddZ xZS )	RTDETRDetectionModela  
    RTDETR (Real-time DEtection and Tracking using Transformers) Detection Model class.

    This class is responsible for constructing the RTDETR architecture, defining loss functions, and facilitating both
    the training and inference processes. RTDETR is an object detection and tracking model that extends from the
    DetectionModel base class.

    Attributes:
        cfg (str): The configuration file path or preset string. Default is 'rtdetr-l.yaml'.
        ch (int): Number of input channels. Default is 3 (RGB).
        nc (int, optional): Number of classes for object detection. Default is None.
        verbose (bool): Specifies if summary statistics are shown during initialization. Default is True.

    Methods:
        init_criterion: Initializes the criterion used for loss calculation.
        loss: Computes and returns the loss during training.
        predict: Performs a forward pass through the network and returns the output.
    c                 ,    t         |   ||||       y)a^  
        Initialize the RTDETRDetectionModel.

        Args:
            cfg (str): Configuration file name or path.
            ch (int): Number of input channels.
            nc (int, optional): Number of classes. Defaults to None.
            verbose (bool, optional): Print additional information during initialization. Defaults to True.
        r   Nr   r   s        rD   r   zRTDETRDetectionModel.__init__  s     	SRB@rF   c                 6    ddl m}  || j                  d      S )z;Initialize the loss criterion for the RTDETRDetectionModel.r   )RTDETRDetectionLossT)r   use_vfl)ultralytics.models.utils.lossr%  r   )r@   r%  s     rD   r   z#RTDETRDetectionModel.init_criterion  s    E"dggt<<rF   c                    t        | d      s| j                         | _        |d   }t        |      }|d   }t	        |      D cg c]#  }||k(  j                         j                         % }}|d   j                  |j                  t        j                        j                  d      |d   j                  |j                        |j                  |j                  t        j                        j                  d      |d	}|| j                  ||
      n|}| j                  r|n|d   \  }	}
}}}|d\  }}n<t        j                  |	|d   d      \  }}	t        j                  |
|d   d      \  }}
t        j                  |j!                  d      |	g      }	t        j                  |j!                  d      |
g      }
| j                  |	|
f||||      }t        |j#                               t        j$                  dD cg c]  }||   j'                          c}|j                        fS c c}w c c}w )a]  
        Compute the loss for the given batch of data.

        Args:
            batch (dict): Dictionary containing image and label data.
            preds (torch.Tensor, optional): Precomputed model predictions. Defaults to None.

        Returns:
            (tuple): A tuple containing the total loss and main three losses in a tensor.
        r   r   	batch_idxr   )dtyperN   bboxes)device)r   r+  r)  	gt_groups)r   r   r  dn_num_splitrf   )r   r   )	dn_bboxes	dn_scoresdn_meta)	loss_giou
loss_class	loss_bbox)r~   r   r   r   rr   ru   itemtor,  r   longviewr?   trainingr   r   	unsqueezevalues	as_tensordetach)r@   r   r   r   bsr)  rW   r-  targets
dec_bboxes
dec_scores
enc_bboxes
enc_scoresr1  r/  r0  r>   r   s                     rD   r>   zRTDETRDetectionModel.loss  s    t[)!002DNElX+&	<A"IFIqi1n))+002I	F<??3::UZZ?@EEbIHo((

(;"cjj

CHHL"	$ 5:MS0uKO==%^cde^f?
J
J?#- Iy$)KK
GN<SYZ$[!Iz$)KK
GN<SYZ$[!IzYY
 4 4Q 7DE
YY
 4 4Q 7DE
~~z:6%(1(1&-	  / 4;;=!5??Nv3wNvDGNN4DNv3w:=**$F F 	F1 G0 4xs   (H6H;
c                 D   g g }}| j                   dd D ]  }|j                  dk7  rMt        |j                  t              r||j                     n#|j                  D 	cg c]  }	|	dk(  r|n||	    c}	}|r| j	                  |||        ||      }|j                  |j                  | j                  v r|nd       |st        ||j                  |j                  |        | j                   d   }
 |
|
j                  D 	cg c]  }	||	   	 c}	|      }|S c c}	w c c}	w )a]  
        Perform a forward pass through the model.

        Args:
            x (torch.Tensor): The input tensor.
            profile (bool, optional): If True, profile the computation time for each layer. Defaults to False.
            visualize (bool, optional): If True, save feature maps for visualization. Defaults to False.
            batch (dict, optional): Ground truth data for evaluation. Defaults to None.
            augment (bool, optional): If True, perform data augmentation during inference. Defaults to False.

        Returns:
            (torch.Tensor): Model's output tensor.
        NrN   rO   rQ   )r@   rA   rJ   rK   r   rL   rZ   r[   r\   r]   heads              rD   r?   zRTDETRDetectionModel.predict  s    B2CRAssby(c2AaccFYZY\Y\8]Y\TUa2g1Q49OY\8]''1b1!AHH!##*Q5%ayI ! zz"~'1!A$'/ 9^ (s   DD)zrtdetr-l.yamlr   NTr   )FFNF)	rb   r   r   r   r   r   r>   r?   r   r   s   @rD   r"  r"  v  s    &
A=+FZrF   r"  c                   *     e Zd ZdZ fdZddZ xZS )EnsemblezEnsemble of models.c                 "    t         |           y)z!Initialize an ensemble of models.Nr   )r@   ra   s    rD   r   zEnsemble.__init__  s    rF   c           	      v    | D cg c]  } |||||      d    }}t        j                  |d      }|dfS c c}w )z2Function generates the YOLO network's final layer.r   rf   N)r   r   )r@   rA   rL   rJ   rK   modulerZ   s          rD   rE   zEnsemble.forward  sF    EIJT6VAw3A6TJ IIaO$w	 Ks   6r   )rb   r   r   r   r   rE   r   r   s   @rD   rG  rG    s    rF   rG  c              #   0  K   | si } ddl }ddl}	 | j                         D ]#  \  }}|j                  |      |j                  |<   % d | D ]  }||j                  v s|j                  |=   y# | D ]  }||j                  v s|j                  |=   w xY ww)a  
    Context manager for temporarily adding or modifying modules in Python's module cache (`sys.modules`).

    This function can be used to change the module paths during runtime. It's useful when refactoring code,
    where you've moved a module from one location to another, but you still want to support the old import
    paths for backwards compatibility.

    Args:
        modules (dict, optional): A dictionary mapping old module paths to new module paths.

    Example:
        ```python
        with temporary_modules({'old.module.path': 'new.module.path'}):
            import old.module.path  # this will now import new.module.path
        ```

    Note:
        The changes are only in effect inside the context manager and are undone once the context manager exits.
        Be aware that directly manipulating `sys.modules` can lead to unpredictable results, especially in larger
        applications or libraries. Use this function with caution.
    r   N)	importlibsysr   import_moduler}   )r}   rL  rM  oldnews        rD   temporary_modulesrQ    s     . 
%HC(66s;CKK ( 	 Cckk!KK$ 7Cckk!KK$ s(   B:A. 
BB.BBBc           
         ddl m} t        | d        ||       }	 t        dddd      5  t	        j
                  |d	
      |fcddd       S # 1 sw Y   yxY w# t        $ r}|j                  dk(  rt        t        d|  d            |t        j                  d|  d|j                   d|j                   d       t        |j                         t	        j
                  |d	
      |fcY d}~S d}~ww xY w)a  
    This function attempts to load a PyTorch model with the torch.load() function. If a ModuleNotFoundError is raised,
    it catches the error, logs a warning message, and attempts to install the missing module via the
    check_requirements() function. After installation, the function again attempts to load the model using torch.load().

    Args:
        weight (str): The file path of the PyTorch model.

    Returns:
        (dict): The loaded PyTorch model.
    r   )attempt_download_assetz.pt)filesuffixzultralytics.utilszultralytics.models.yolozultralytics.data)zultralytics.yolo.utilszultralytics.yolo.v8zultralytics.yolo.datacpu)map_locationNmodelsu   ERROR ❌️ ar   appears to be an Ultralytics YOLOv5 model originally trained with https://github.com/ultralytics/yolov5.
This model is NOT forwards compatible with YOLOv8 at https://github.com/ultralytics/ultralytics.
Recommend fixes are to train a new model using the latest 'ultralytics' package or to run a command with an official YOLOv8 model, i.e. 'yolo predict model=yolov8n.pt'r_   z appears to require 'zK', which is not in ultralytics requirements.
AutoInstall will run now for 'z' but this feature will be removed in the future.
Recommend fixes are to train a new model using the latest 'ultralytics' package or to run a command with an official YOLOv8 model, i.e. 'yolo predict model=yolov8n.pt')ultralytics.utils.downloadsrS  r*   rQ  r   r   ModuleNotFoundErrorr  	TypeErrorr'   r%   r`   r)   )weightrS  rT  r   s       rD   torch_safe_loadr]  "  s
    CfU+!&)D:*='@); = > ::d7=	> > >  :66Xvh /k l mn
 tuu 	0EaffX N::;&& Bkl 	m 	166"zz$U3T99:s;   A A	A AA A 	C7$BC2,C72C7c           
      b   t               t        | t              r| n| gD ]  }t        |      \  }}d|v ri t        |d   nd}|j                  d      xs |d   j                  |      j                         }||_        ||_	        t        |      |_        t        |d      st        j                  dg      |_        j!                  |r*t        |d      r|j#                         j%                         n|j%                                 j'                         D ]  }t)        |      }	|	t*        j,                  t*        j.                  t*        j0                  t*        j2                  t*        j4                  t6        t8        fv r||_        o|	t*        j<                  u st        |d      rd|_         tA              d	k(  rd
   S tC        jD                  d|  d       dD ]  }
tG        |
tI        d   |
              t        jJ                  t        j                  D cg c]  }|j                  jM                          c}            jO                            j                  _        tQ        fdD              s"J dD cg c]  }|jR                   c}        S c c}w c c}w )zWLoads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a.
train_argsNemarR   r         @@r   recompute_scale_factorr   rN   zEnsemble created with 
)r   r   r   r   c              3   V   K   | ]   }d    j                   |j                   k(   " yw)r   N)r   )r   r\   ensembles     rD   r   z'attempt_load_weights.<locals>.<genexpr>n  s#     8x!x{~~%xs   &)zModels differ in class counts )*rG  r<   ro   r]  r#   r   r6  r   rB   pt_pathguess_model_tasktaskr~   r   r   r   rV   r   evalr}   rY   r   	Hardswish	LeakyReLUReLUReLU6SiLUr   r"   r   Upsamplerb  r   r%   rs   r  getattrargmaxr   rT   allr   )r   r,  r   r   wckptrB   rR   r\   rx   r   re  s              @rD   attempt_load_weightsru  J  s>    zH"7D1Wy@!!$a=IT=Q9"9d<&89W[%1DM55f=CCE 
%e,
uh' <<.EL 	tv8N

))+TYT^T^T`a A  Gr||RWWbhhQXYYAI"++ga1I&J'+A$   8}| KK(	45"!WXa[!45 #u||ELLRZ9[RZQ!((,,.RZ9[,\]aacdkkHO8x88u<Zjr[sjref\]\`\`jr[sZt:uu8O :\[ss   $!J'	J,c           	      x   t        |       \  }} i t        |j                  di       }|j                  d      xs |d   j                  |      j	                         }|j                         D ci c]  \  }}|t        v s|| c}}|_        | |_        t        |      |_
        t        |d      st        j                  dg      |_        |r*t        |d      r|j                         j!                         n|j!                         }|j#                         D ]  }	t%        |	      }
|
t&        j(                  t&        j*                  t&        j,                  t&        j.                  t&        j0                  t2        t4        fv r||	_        o|
t&        j8                  u st        |	d      rd|	_         ||fS c c}}w )	zLoads a single model weights.r_  r`  rR   r   ra  r   rb  N)r]  r#   r   r6  r   r   r$   rB   rf  rg  rh  r~   r   r   r   r   ri  r}   rY   r   rj  rk  rl  rm  rn  r   r"   r   ro  rb  )r\  r,  r   r   rt  rB   rR   r   r   r\   rx   s              rD   attempt_load_one_weightrw  r  sW   "6*LD&??488L"#=?DXXe_-W11&9??AE $(::<I<41a18H3H!Q$<IEJEM!%(EJ5(#||SE*#'GE6,BEJJL

E ]]_Gr||RWWbhhQXYYAI"++ga1I&J'+A$  $;# Js   1F6F6c                 ~
    ddl }t        d      } fddD        \  }}} fddD        \  }}	}
|rQ j                  d      }|s5t        |j	                               d   }t        j                  d	| d
       ||   \  }}	}|r9t        |      t        _	        |r#t        j                  t        d       d|        |r)t        j                  dddddddddddddd       gg g d   }}}t         d    d   z         D ]  \  \  }}dv rt        t        j                  dd       nt!                  t              D ]e  \  }}t#        |t$              st'        j(                  t*              5  |t-               v rt-               |   n|j/                  |      |<   ddd       g |dkD  rt1        t3        ||z        d      n|x}}t4        t        t6        t8        t:        t<        t>        t@        tB        tD        tF        tH        tJ        tL        tN        tP        tR        t        jT                  tV        tX        tZ        fv ry|   d   }}||k7  rt]        t_        ||      |	z  d       }||gdd tF        tH        tJ        tL        tN        tP        tR        tX        tZ        f	v r0ja                  d!|       d}ntb        u r
|   gntd        tf        fv r6|   d   d   }}}|||gd!d tf        u rىja                  d"|       d}nĉt        jh                  u r|   gntj        u rtm        fd#|D              }ntn        tp        tr        fv rJju                  |D cg c]  }|   	 c}       tp        u rQt]        t_        d!   |      |	z  d       d!<   n1tv        u r$ja                  d|D cg c]  }|   	 c}       n|   }|dkD  r%t        jx                  fd$t{        |      D         n  }t%              d d% j}                  d&d      }tm        d' |j                         D              _@        ||c|_A        |_B        |_C        |rDt        j                  dt%        |      d|dj                  d(d|dt%              d       |j                  fd)t#        |t              r|gn|D               |ju                  |       dk(  rg ju                  |        t        jx                  | t        |      fS # 1 sw Y   xY wc c}w c c}w )*z8Parse a YOLO model.yaml dictionary into a PyTorch model.r   Ninfc              3   @   K   | ]  }j                  |        y wr   r   r   rA   ds     rD   r   zparse_model.<locals>.<genexpr>  s     H)GAquuQx)Gs   )r   
activationscalesc              3   B   K   | ]  }j                  |d         yw)g      ?Nr{  r|  s     rD   r   zparse_model.<locals>.<genexpr>  s     h6gquuQ}6gs   )depth_multiplewidth_multipler  r   u6   WARNING ⚠️ no model scale passed. Assuming scale='z'.zactivation:ri   rc  r   z>3fromz>20nrk   z>10rm   rJ  z<45	argumentsz<30rN   backbonerE  znn.r   r      rf   r   c              3   (   K   | ]	  }|     y wr   r   )r   rA   r   s     rD   r   zparse_model.<locals>.<genexpr>  s     &AqRUA   c              3   (   K   | ]	  }    y wr   r   )r   ry   rB   r\   s     rD   r   zparse_model.<locals>.<genexpr>  s     8x!QXxr  r   z	__main__.c              3   <   K   | ]  }|j                           y wr   )numelr   s     rD   r   zparse_model.<locals>.<genexpr>  s     6o1779os   rl   c              3   4   K   | ]  }|d k7  s	|z    yw)rN   Nr   )r   rA   rW   s     rD   r   zparse_model.<locals>.<genexpr>  s     Q$DabAE$Ds   

)Gastr   r   r   keysr%   r`   ri  r   default_actrs   r&   	enumeraterp  r   r   globalsr<   str
contextlibsuppressr  localsliteral_evalr   roundr   r   r   r   r   r
   r   r   r   r   r   r   r   r   r	   r   ConvTranspose2dr   r   r   r5   mininsertr   r   r   BatchNorm2dr   ru   r   r"   r   rV   r!   r  rr   replace
parametersrt   rW   rS   rY   extendrT   sorted)r}  r   re   r  max_channelsr   actr  depthwidthr  r   layersrX   c2rS   r  r]   an_c1cmrA   m_rx   rB   rW   r\   s   ``                       @@@rD   r   r     s    <LH)GHOBVh6ghE5)g&++-(+ENNSTYSZZ\]^%+E]"ul
9KK8M231SE:;bBs|C8HS>HS>R]^aQbcd
B2r"v"DF'*&	(AB?Aq!T(-
GEHHae$	!dODAq!S!((4-.&(]fhqk@P@PQR@SDG 54 $
 ./UU1u9%q)9B4	:X[]acikpBRw@R@RTegjlqs sUDGBRx#CL$9E$A1E&T!"X&D]BCT7COOAq!$YqE>D>D67##AQaBBB*ab*DG|Aq!".. qE7D&[&A&&B67D))KK*1A*+G|(T!Wl)Ce)KQOQ-KK1-1aBqE1-.AB=>UR]]8uQx894F1RL  b16bmmo66AbdBGKK1R&QRGADD<r!CTSVXYQ:a+=QC1$DQQb6B
		"e Cf ==&!6$<//_ 548 + .s   .T(8T5
T:(T2c                    ddl }t        |       } | j                  d dD        v ra|j                  dd| j                        }t	        j
                  d| j                   d| d	       | j                  || j                  z         } |j                  d
dt        |             }t        |d      xs t        |       }t        |      }t        |       |d<   t        |       |d<   |S )z%Load a YOLOv8 model from a YAML file.r   Nc              3   :   K   | ]  }d D ]  }d| | d   yw))   r  yolov6Nr   r|  s      rD   r   z"yaml_model_load.<locals>.<genexpr>  s%     Fgv!uQCs!_v_gs   nsmlxz(\d+)([nslmx])6(.+)?$z	\1\2-p6\3uG   WARNING ⚠️ Ultralytics YOLO P6 models now use -p6 suffix. Renaming z to .z(\d+)([nslmx])(.+)?$z\1\3F)hardr   	yaml_file)rer   stemsubr%   r`   	with_namerU  r  r+   r(   guess_model_scale)pathr  new_stemunified_pathr  r}  s         rD   r   r     s    :DyyFgFF662L$))L`aeajaj`kkopxoyyz{|~~h456617CIFL<e4H
48HI)A"4(AgJYAkNHrF   c                     t        j                  t              5  ddl}|j	                  dt        |       j                        j                  d      cddd       S # 1 sw Y   yxY w)a  
    Takes a path to a YOLO model's YAML file as input and extracts the size character of the model's scale. The function
    uses regular expression matching to find the pattern of the model scale in the YAML file name, which is denoted by
    n, s, m, l, or x. The function returns the size character of the model scale as a string.

    Args:
        model_path (str | Path): The path to the YOLO model's YAML file.

    Returns:
        (str): The size character of the model's scale, which can be n, s, m, l, or x.
    r   Nzyolov\d+([nslmx])r   r   )r  r  AttributeErrorr  searchr   r  group)
model_pathr  s     rD   r  r    sK     
		^	,yy-tJ/?/D/DEKKAN 
-	,	, s   8AA%c                    d }t        | t              r+t        j                  t              5   ||       cddd       S t        | t
        j                        rdD ]4  }t        j                  t              5  t        |      d   cddd       c S  dD ]7  }t        j                  t              5   |t        |            cddd       c S  | j                         D ]J  }t        |t              r yt        |t              r yt        |t              r yt        |t              sJ y	 t        | t        t        f      rqt        |       } d
| j                  v sd| j                   v ryd| j                  v sd| j                   v ryd| j                  v sd	| j                   v ry	d| j                   v ryt#        j$                  d       y# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   XxY w)ac  
    Guess the task of a PyTorch model from its architecture or configuration.

    Args:
        model (nn.Module | dict): PyTorch model or model configuration in YAML format.

    Returns:
        (str): Task of the model ('detect', 'segment', 'classify', 'pose').

    Raises:
        SyntaxError: If the task of the model could not be determined.
    c                 d    | d   d   d   j                         }|dv ry|dk(  ry|dk(  ry|dk(  ryy	)
zGuess from YAML dictionary.rE  rN   r   )classify
classifierr   fcr  detectsegmentposeN)lower)r   r\   s     rD   cfg2taskz"guess_model_task.<locals>.cfg2task  sL    KOB%%'77=	>; rF   N)z
model.argszmodel.model.argszmodel.model.model.argsrh  )z
model.yamlzmodel.model.yamlzmodel.model.model.yamlr  r  r  r  z-segz-clsz-poseu   WARNING ⚠️ Unable to automatically guess model task, assuming 'task=detect'. Explicitly define task for your model, i.e. 'task=detect', 'segment', 'classify', or 'pose'.)r<   r=   r  r  	Exceptionr   Moduleri  r}   r   r"   r   r   r  r   r  partsr%   r`   )rR   r  rA   r\   s       rD   rg  rg    s   
 %  +E? ,+ %#KA$$Y/Awv 0/ L LA$$Y/Q( 0/ L A!V$Aw' Ax(!At$ ! %#t%UUZZ9#;uzz!Z5;;%>

"f&;$ NN r sK ,+ 0/ 0/s#   G7G0G"GG	"G,	r   )NTFr   )Vr  rq   r   pathlibr   r   torch.nnr   ultralytics.nn.modulesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   ultralytics.utilsr#   r$   r%   r&   r'   r(   ultralytics.utils.checksr)   r*   r+   ultralytics.utils.lossr,   r-   r.   r/   ultralytics.utils.plottingr0   ultralytics.utils.torch_utilsr1   r2   r3   r4   r5   r6   r7   r8   rp   ImportErrorr  r:   r   r   r  r
  r"  
ModuleListrG  contextmanagerrQ  r]  ru  rw  r   r   r  rg  r   rF   rD   <module>r     s2       < < < < < < < < f e Q Q h h <] ] ]
}Z		 }Z@I%Y I%X	( 	(   "/&) /&dm> m`r}} & %% %%P%:P%P6K0\$$AQ  Ds   D- -D76D7