
    hh                     ,   d Z ddlZddlZddlmZmZmZmZ ddlZddl	m
Z
 ddlm
c mZ ddlmZmZ ddlmZmZmZmZ ddlmZmZ ddlmZmZmZmZmZmZm Z  dd	l!m"Z"m#Z# dd
l$m%Z%m&Z&m'Z' ddl(m)Z)m*Z* dZ+ G d de
jX                        Z- G d de-      Z. G d de-      Z/ G d de-      Z0 G d de
jX                        Z1 G d de-      Z2 G d de
jX                        Z3 G d de-      Z4 G d de4      Z5 G d d e
jX                        Z6 G d! d"e-      Z7y)#zModel head modules.    N)ListOptionalTupleUnion)	constant_xavier_uniform_)
TORCH_1_10	dist2bbox	dist2rboxmake_anchors)fuse_conv_and_bnsmart_inference_mode   )DFLSAVPEBNContrastiveHeadContrastiveHeadProtoResidual	SwiGLUFFN)ConvDWConv)MLPDeformableTransformerDecoder!DeformableTransformerDecoderLayer)bias_init_with_problinear_init)	DetectSegmentPoseClassifyOBBRTDETRDecoder	v10DetectYOLOEDetectYOLOESegmentc            
           e Zd ZdZdZdZdZdZdZdZ	 e
j                  d      Z e
j                  d      ZdZdZddedef fdZd	ee
j(                     d
eee
j(                     ef   fdZd	ee
j(                     d
eeef   fdZd	ee
j(                     d
e
j(                  fdZd Zdde
j(                  de
j(                  ded
e
j(                  fdZedde
j(                  deded
e
j(                  fd       Z xZS )r   a  
    YOLO Detect head for object detection models.

    This class implements the detection head used in YOLO models for predicting bounding boxes and class probabilities.
    It supports both training and inference modes, with optional end-to-end detection capabilities.

    Attributes:
        dynamic (bool): Force grid reconstruction.
        export (bool): Export mode flag.
        format (str): Export format.
        end2end (bool): End-to-end detection mode.
        max_det (int): Maximum detections per image.
        shape (tuple): Input shape.
        anchors (torch.Tensor): Anchor points.
        strides (torch.Tensor): Feature map strides.
        legacy (bool): Backward compatibility for v3/v5/v8/v9 models.
        xyxy (bool): Output format, xyxy or xywh.
        nc (int): Number of classes.
        nl (int): Number of detection layers.
        reg_max (int): DFL channels.
        no (int): Number of outputs per anchor.
        stride (torch.Tensor): Strides computed during build.
        cv2 (nn.ModuleList): Convolution layers for box regression.
        cv3 (nn.ModuleList): Convolution layers for classification.
        dfl (nn.Module): Distribution Focal Loss layer.
        one2one_cv2 (nn.ModuleList): One-to-one convolution layers for box regression.
        one2one_cv3 (nn.ModuleList): One-to-one convolution layers for classification.

    Methods:
        forward: Perform forward pass and return predictions.
        forward_end2end: Perform forward pass for end-to-end detection.
        bias_init: Initialize detection head biases.
        decode_bboxes: Decode bounding boxes from predictions.
        postprocess: Post-process model predictions.

    Examples:
        Create a detection head for 80 classes
        >>> detect = Detect(nc=80, ch=(256, 512, 1024))
        >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
        >>> outputs = detect(x)
    FN,  r   ncchc                 n    t                    | _        t        |       _        d _        | j
                  dz  z    _        t        j                   j                         _	        t        d|d   dz   j
                  dz  f      t        |d   t         j                  d            ct        j                   fd|D               _         j                  rt        j                   fd|D              nt        j                   fd|D               _         j
                  dkD  rt#         j
                        nt        j$                          _         j(                  rIt+        j,                   j                         _        t+        j,                   j                          _        y	y	)
z
        Initialize the YOLO detection layer with specified number of classes and channels.

        Args:
            nc (int): Number of classes.
            ch (tuple): Tuple of channel sizes from backbone feature maps.
              r   d   c           
   3      K   | ]S  }t        j                  t        |d       t        d       t        j                  dj                  z  d             U yw)   r-   r   N)nn
Sequentialr   Conv2dreg_max).0xc2selfs     Y/var/www/html/dev/engine/venv/lib/python3.12/site-packages/ultralytics/nn/modules/head.py	<genexpr>z"Detect.__init__.<locals>.<genexpr>]   sJ      !
cdBMM$q"a.$r2q/299RT\\IY[\;]^!
s   AAc           
   3      K   | ]P  }t        j                  t        |d       t        d       t        j                  j                  d             R ywr0   r   Nr1   r2   r   r3   r)   r5   r6   c3r8   s     r9   r:   z"Detect.__init__.<locals>.<genexpr>a   sE     phi"--QARQSUW[W^W^`aIbcp   AAc              3   2  K   | ]  }t        j                  t        j                  t        ||d       t        |d            t        j                  t        d       t        d            t        j                  j
                  d              ywr<   )r1   r2   r   r   r3   r)   r>   s     r9   r:   z"Detect.__init__.<locals>.<genexpr>c   su        MM&Aq/42q>BMM&R"3T"b!_EIIb$''1-s   BBr   N)super__init__r)   lennlr4   notorchzerosstridemaxminr1   
ModuleListcv2legacycv3r   Identitydflend2endcopydeepcopyone2one_cv2one2one_cv3)r8   r)   r*   r7   r?   	__class__s   `  @@r9   rC   zDetect.__init__N   sI    	b't||a''kk$''*b"Q%1*dllQ&678#beSRUEV:WB== !
hj!
 

 {{ MMpmopp    	 )-q(83t||$bkkm<<#}}TXX6D#}}TXX6D     r6   returnc                 `   | j                   r| j                  |      S t        | j                        D ]I  }t	        j
                   | j                  |   ||          | j                  |   ||         fd      ||<   K | j                  r|S | j                  |      }| j                  r|S ||fS )HConcatenate and return predicted bounding boxes and class probabilities.r   )rR   forward_end2endrangerE   rG   catrM   rO   training
_inferenceexport)r8   r6   iys       r9   forwardzDetect.forwardr   s    <<''**tww 	HA99kdhhqk!A$/!QqT1BCQGAaD	H==HOOAKKq+aV+rX   c           
         |D cg c]  }|j                          }}t        | j                        D cg c]F  }t        j                   | j
                  |   ||          | j                  |   ||         fd      H }}t        | j                        D ]I  }t        j                   | j                  |   ||          | j                  |   ||         fd      ||<   K | j                  r||dS | j                  |      }| j                  |j                  ddd      | j                  | j                        }| j                  r|S |||dfS c c}w c c}w )av  
        Perform forward pass of the v10Detect module.

        Args:
            x (List[torch.Tensor]): Input feature maps from different levels.

        Returns:
            outputs (dict | tuple): Training mode returns dict with one2many and one2one outputs.
                Inference mode returns processed detections or tuple with detections and raw outputs.
        r   )one2manyone2oner      )detachr]   rE   rG   r^   rU   rV   rM   rO   r_   r`   postprocesspermutemax_detr)   ra   )r8   r6   xix_detachrb   rg   rc   s          r9   r\   zDetect.forward_end2end~   sK    +,,BBIIK,,hmnrnunuhv
cdEII*t''*8A;79L9I9I!9LXVW[9YZ\]^
 
 tww 	HA99kdhhqk!A$/!QqT1BCQGAaD	H== !g66OOG$QYYq!Q/twwGKKqMaaG)L%MM -
s   EAEc           
          |d   j                   }t        j                  |D cg c]"  }|j                  |d   | j                  d      $ c}d      }| j
                  dk7  rM| j                  s| j                   |k7  r2d t        || j                  d      D        \  | _	        | _
        || _         | j                  r?| j
                  dv r1|ddd| j                  d	z  f   }|dd| j                  d	z  df   }n.|j                  | j                  d	z  | j                  fd
      \  }}| j                  r| j
                  dv r|d   }|d   }t        j                  ||||g|j                         j#                  d
d	d
      }	| j                  | j                  d   |	z  z  }
| j%                  | j'                  |      |
z  | j                  j)                  d      |
ddddf   z        }n| j                  r| j
                  dk(  r| j%                  | j'                  |      | j                  z  | j                  j)                  d      | j                  z  d      }|j+                  d
d      |j-                         j/                  ddd
      fS | j%                  | j'                  |      | j                  j)                  d            | j                  z  }t        j                  ||j-                         fd
      S c c}w )aM  
        Decode predicted bounding boxes and class probabilities based on multiple-level feature maps.

        Args:
            x (List[torch.Tensor]): List of feature maps from different detection layers.

        Returns:
            (torch.Tensor): Concatenated tensor of decoded bounding boxes and class probabilities.
        r   rh   imxc              3   @   K   | ]  }|j                  d d        ywr   r   N	transposer5   r6   s     r9   r:   z$Detect._inference.<locals>.<genexpr>   s     )g!++a*;)g         ?>   pbtfjstfliteedgetpusaved_modelNr-   r   >   r{   r|   r0   deviceF)xywh)shaperG   r^   viewrF   formatdynamicr   rI   anchorsstridesra   r4   splitr)   tensorr   reshapedecode_bboxesrQ   	unsqueezeru   sigmoidrk   )r8   r6   r   rm   x_catboxclsgrid_hgrid_w	grid_sizenormdboxs               r9   r`   zDetect._inference   s    !

		AFb27758TWWb9FJ;;%T\\TZZ55H)g\RSUYU`U`beEf)g&DL$,DJ;;4;;*\\-T\\A---.C4<<!+--.C{{DLL1$4dgg#>BHC;;4;;*?? 1XF1XFffff%EcjjYaabcefhijI<<4;;q>I#=>D%%dhhsmd&:DLL<R<RST<UX\]^`bab`b]bXc<cdD[[T[[E1%%,dll.D.DQ.G$,,.V]b & D >>!Q')>)>q!Q)GGG%%dhhsmT\\5K5KA5NORVR^R^^Dyy$.227 Gs   'K;c                    | }t        |j                  |j                  |j                        D ]q  \  }}}d|d   j                  j
                  dd t        j                  d|j                  z  d|z  dz  z        |d   j                  j
                  d|j                   s | j                  rt        |j                  |j                  |j                        D ]q  \  }}}d|d   j                  j
                  dd t        j                  d|j                  z  d|z  dz  z        |d   j                  j
                  d|j                   s yy)BInitialize Detect() biases, WARNING: requires stride availability.      ?rp   N     rh   )ziprM   rO   rI   biasdatamathlogr)   rR   rU   rV   r8   mabss        r9   	bias_initzDetect.bias_init   s    155!%%2 	JGAq!!$AbEJJOOA&*hhq144x37q./H&IAbEJJOOFadd#	J <<q}}ammQXXF N1a%("

"*.((1qtt8sQw1n3L*M"

!$$'N rX   bboxesr   r   c                 Z    t        |||xr | j                  xs | j                   d      S )z'Decode bounding boxes from predictions.r   )r   dim)r
   rR   xyxy)r8   r   r   r   s       r9   r   zDetect.decode_bboxes   s)    t/WT\\=VTYY8W]^__rX   predsrl   c                 X   | j                   \  }}}| j                  d|gd      \  }}|j                  d      j                  t	        ||            d   j                  d      }|j                  d|j                  ddd            }|j                  d|j                  dd|            }|j                  d      j                  t	        ||            \  }}t        j                  |      d   }	t        j                  ||	||z  f   |d   ||z  d   j                         gd      S )a%  
        Post-process YOLO model predictions.

        Args:
            preds (torch.Tensor): Raw predictions with shape (batch_size, num_anchors, 4 + nc) with last dimension
                format [x, y, w, h, class_probs].
            max_det (int): Maximum detections per image.
            nc (int, optional): Number of classes.

        Returns:
            (torch.Tensor): Processed predictions with shape (batch_size, min(max_det, num_anchors), 6) and last
                dimension format [x, y, w, h, max_class_prob, class_index].
        r-   rp   r   r   )r   index).N)r   r   amaxtopkrK   r   gatherrepeatflattenrG   aranger^   float)
r   rl   r)   
batch_sizer   _boxesscoresr   rb   s
             r9   rj   zDetect.postprocess   s    "'
GQQG4v#((Wg)>?BLLRP%,,q!Q*?@1ELLAr,BCq)..s7G/DELL$Y/yy%5B;/	1BURZQZD[DaDaDcdjlmmrX   P    T)r   ) __name__
__module____qualname____doc__r   ra   r   rR   rl   r   rG   emptyr   r   rN   r   intr   rC   r   Tensorr   rd   dictr\   r`   r   boolr   staticmethodrj   __classcell__rW   s   @r9   r   r      sV   (T GFFGGEekk!nGekk!nGFD"73 "7 "7H
,ell+ 
,d5<<6H%6O0P 
,Nell!3 NdEk8J N0'3D. '35<< '3RN`ELL `5<< `t `_d_k_k ` n5<< n# n3 n n nrX   r   c            	            e Zd ZdZd
dedededef fdZdeej                     de
eeej                     f   fd	Z xZS )r   a  
    YOLO Segment head for segmentation models.

    This class extends the Detect head to include mask prediction capabilities for instance segmentation tasks.

    Attributes:
        nm (int): Number of masks.
        npr (int): Number of protos.
        proto (Proto): Prototype generation module.
        cv4 (nn.ModuleList): Convolution layers for mask coefficients.

    Methods:
        forward: Return model outputs and mask coefficients.

    Examples:
        Create a segmentation head
        >>> segment = Segment(nc=80, nm=32, npr=256, ch=(256, 512, 1024))
        >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
        >>> outputs = segment(x)
    r)   nmnprr*   c                     t            ||       | _        | _        t	        |d    j                   j                         _        t        |d   dz   j                        t        j                   fd|D               _	        y)aN  
        Initialize the YOLO model attributes such as the number of masks, prototypes, and the convolution layers.

        Args:
            nc (int): Number of classes.
            nm (int): Number of masks.
            npr (int): Number of protos.
            ch (tuple): Tuple of channel sizes from backbone feature maps.
        r   r-   c           
   3      K   | ]P  }t        j                  t        |d       t        d       t        j                  j                  d             R ywr<   r1   r2   r   r3   r   r5   r6   c4r8   s     r9   r:   z#Segment.__init__.<locals>.<genexpr>  H      woptAr1~tBAPRPYPYZ\^b^e^eghPi!j wr@   N)
rB   rC   r   r   r   protorJ   r1   rL   cv4)r8   r)   r   r   r*   r   rW   s   `    @r9   rC   zSegment.__init__   sm     	R 2a5$((DGG4
A!TWW%== wtv wwrX   r6   rY   c           
         | j                  |d         }|j                  d   }t        j                  t	        | j
                        D cg c]5  } | j                  |   ||         j                  || j                  d      7 c}d      }t        j                  | |      }| j                  r|||fS | j                  rt        j                  ||gd      |fS t        j                  |d   |gd      |d   ||ffS c c}w )gReturn model outputs and mask coefficients if training, otherwise return outputs and mask coefficients.r   rp   rh   r   )r   r   rG   r^   r]   rE   r   r   r   r   rd   r_   ra   )r8   r6   pbsrb   mcs         r9   rd   zSegment.forward  s    JJqtWWQZYYtwwXAAaD)..r477B?XZ[\NN4#==b!8O-1[[		1b'1%q)guyy!A$PRUV?WZ[\]Z^`bdeYf>gg	 Ys   
:C<)r          r   )r   r   r   r   r   r   rC   r   rG   r   r   rd   r   r   s   @r9   r   r      s`    *x3 x x xu x$	hell+ 	heT%,,=O6O0P 	hrX   r   c                        e Zd ZdZddededef fdZdeej                     de
ej                  ef   fdZd	ej                  d
ej                  dej                  fdZ xZS )r"   a  
    YOLO OBB detection head for detection with rotation models.

    This class extends the Detect head to include oriented bounding box prediction with rotation angles.

    Attributes:
        ne (int): Number of extra parameters.
        cv4 (nn.ModuleList): Convolution layers for angle prediction.
        angle (torch.Tensor): Predicted rotation angles.

    Methods:
        forward: Concatenate and return predicted bounding boxes and class probabilities.
        decode_bboxes: Decode rotated bounding boxes.

    Examples:
        Create an OBB detection head
        >>> obb = OBB(nc=80, ne=1, ch=(256, 512, 1024))
        >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
        >>> outputs = obb(x)
    r)   ner*   c                      t            ||       | _        t        |d   dz   j                        t	        j
                   fd|D               _        y)a
  
        Initialize OBB with number of classes `nc` and layer channels `ch`.

        Args:
            nc (int): Number of classes.
            ne (int): Number of extra parameters.
            ch (tuple): Tuple of channel sizes from backbone feature maps.
        r   r-   c           
   3      K   | ]P  }t        j                  t        |d       t        d       t        j                  j                  d             R ywr<   )r1   r2   r   r3   r   r   s     r9   r:   zOBB.__init__.<locals>.<genexpr>@  r   r@   N)rB   rC   r   rJ   r1   rL   r   )r8   r)   r   r*   r   rW   s   `   @r9   rC   zOBB.__init__3  sJ     	R A!TWW%== wtv wwrX   r6   rY   c           
      F   |d   j                   d   }t        j                  t        | j                        D cg c]5  } | j
                  |   ||         j                  || j                  d      7 c}d      }|j                         dz
  t        j                  z  }| j                  s|| _        t        j                  | |      }| j                  r||fS | j                  rt        j                  ||gd      S t        j                  |d   |gd      |d   |ffS c c}w )r[   r   rp   rh   g      ?r   )r   rG   r^   r]   rE   r   r   r   r   r   pir_   angler   rd   ra   )r8   r6   r   rb   r   s        r9   rd   zOBB.forwardB  s    qTZZ]		ERVRYRYN[q;488A;qt,11"dggrB[]^_4'4772}}DJNN4#==e8O+/;;uyy!UQ'hUYY!e}VW=X[\]^[_afZg<hh \s   :Dr   r   c                 4    t        || j                  |d      S )zDecode rotated bounding boxes.r   r   )r   r   )r8   r   r   s      r9   r   zOBB.decode_bboxesP  s    W!<<rX   )r   r   r   )r   r   r   r   r   r   rC   r   rG   r   r   rd   r   r   r   s   @r9   r"   r"     sy    *x3 x xe xiell+ iellE6I0J i=ELL =5<< =ELL =rX   r"   c                        e Zd ZdZddededef fdZdeej                     de
ej                  ef   fdZd	ed
ej                  dej                  fdZ xZS )r    a#  
    YOLO Pose head for keypoints models.

    This class extends the Detect head to include keypoint prediction capabilities for pose estimation tasks.

    Attributes:
        kpt_shape (tuple): Number of keypoints and dimensions (2 for x,y or 3 for x,y,visible).
        nk (int): Total number of keypoint values.
        cv4 (nn.ModuleList): Convolution layers for keypoint prediction.

    Methods:
        forward: Perform forward pass through YOLO model and return predictions.
        kpts_decode: Decode keypoints from predictions.

    Examples:
        Create a pose detection head
        >>> pose = Pose(nc=80, kpt_shape=(17, 3), ch=(256, 512, 1024))
        >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
        >>> outputs = pose(x)
    r)   	kpt_shaper*   c                      t            ||       | _        |d   |d   z   _        t	        |d   dz   j                        t        j                   fd|D               _        y)aC  
        Initialize YOLO network with default parameters and Convolutional Layers.

        Args:
            nc (int): Number of classes.
            kpt_shape (tuple): Number of keypoints, number of dims (2 for x,y or 3 for x,y,visible).
            ch (tuple): Tuple of channel sizes from backbone feature maps.
        r   r   r-   c           
   3      K   | ]P  }t        j                  t        |d       t        d       t        j                  j                  d             R ywr<   )r1   r2   r   r3   nkr   s     r9   r:   z Pose.__init__.<locals>.<genexpr>y  r   r@   N)rB   rC   r   r   rJ   r1   rL   r   )r8   r)   r   r*   r   rW   s   `   @r9   rC   zPose.__init__k  s^     	R "A,1-A!TWW%== wtv wwrX   r6   rY   c           
         |d   j                   d   }t        j                  t        | j                        D cg c]5  } | j
                  |   ||         j                  || j                  d      7 c}d      }t        j                  | |      }| j                  r||fS | j                  ||      }| j                  rt        j                  ||gd      S t        j                  |d   |gd      |d   |ffS c c}w )z?Perform forward pass through YOLO model and return predictions.r   rp   r   )r   rG   r^   r]   rE   r   r   r   r   rd   r_   kpts_decodera   )r8   r6   r   rb   kptpred_kpts         r9   rd   zPose.forward{  s    qTZZ]ii%PTPWPW.YQ!QqT*//DGGR@Y[]^NN4#==c6M##B,.2kkuyy!X*l		1Q4QYJZ\]@^abcdaegj`k?ll Zs   :C9r   kptsc                 \   | j                   d   }| j                  rd| j                  dv r |j                  |g| j                   d }| j                  d   | j                  d   }}t        j                  ||g|j                        j                  ddd      }| j                  | j                  d   |z  z  }|ddddddf   d	z  | j                  d
z
  z   |z  }	nM |j                  |g| j                   d }|ddddddf   d	z  | j                  d
z
  z   | j                  z  }	|dk(  r2t        j                  |	|ddddddf   j                         fd      }	|	j                  || j                  d      S |j                         }|dk(  r$|dddd|f   j                         |dddd|f<   |dddd|f   d	z  | j                  d   d
z
  z   | j                  z  |dddd|f<   |dddd|f   d	z  | j                  d   d
z
  z   | j                  z  |dddd|f<   |S )z"Decode keypoints from predictions.r   >   r{   r|   rp   rh   r0   r~   r   N       @rx   )r   ra   r   r   r   rG   r   r   r   r   rI   r   r^   r   r   clone)
r8   r   r   ndimrc   r   r   r   r   r   s
             r9   r   zPose.kpts_decode  s.   ~~a ;;{{  
 DIIb64>>626!%A

1!LL&&)9!((KSSTUWXZ[\	||t{{1~	'ABq!RaRx[3&$,,*<=E DIIb64>>626q!RaRx[3&$,,*<=MqyIIq!Aq!A#I,"6"6"891=66"dggr**

Aqy !!QWW* 5 5 7!QWW*q!'T'z]S0DLLOc4IJdllZAaDjMq!'T'z]S0DLLOc4IJdllZAaDjMHrX   )r   )   r0   r   )r   r   r   r   r   r   rC   r   rG   r   r   rd   r   r   r   s   @r9   r    r    U  su    *x3 x xU x mell+ mellE6I0J mc  %,, rX   r    c                        e Zd ZdZdZddededededee   def fd	Zd
ee	e
j                     e
j                  f   dee
j                  ef   fdZ xZS )r!   a  
    YOLO classification head, i.e. x(b,c1,20,20) to x(b,c2).

    This class implements a classification head that transforms feature maps into class predictions.

    Attributes:
        export (bool): Export mode flag.
        conv (Conv): Convolutional layer for feature transformation.
        pool (nn.AdaptiveAvgPool2d): Global average pooling layer.
        drop (nn.Dropout): Dropout layer for regularization.
        linear (nn.Linear): Linear layer for final classification.

    Methods:
        forward: Perform forward pass of the YOLO model on input image data.

    Examples:
        Create a classification head
        >>> classify = Classify(c1=1024, c2=1000)
        >>> x = torch.randn(1, 1024, 20, 20)
        >>> output = classify(x)
    Fc1r7   kr   r   gc                     t         |           d}t        ||||||      | _        t	        j
                  d      | _        t	        j                  dd      | _        t	        j                  ||      | _
        y)a  
        Initialize YOLO classification head to transform input tensor from (b,c1,20,20) to (b,c2) shape.

        Args:
            c1 (int): Number of input channels.
            c2 (int): Number of output classes.
            k (int, optional): Kernel size.
            s (int, optional): Stride.
            p (int, optional): Padding.
            g (int, optional): Groups.
        i   r           T)r   inplaceN)rB   rC   r   convr1   AdaptiveAvgPool2dpoolDropoutdropLinearlinear)	r8   r   r7   r   r   r   r   c_rW   s	           r9   rC   zClassify.__init__  sa     	RAq!,	((+	JJd3	iiB'rX   r6   rY   c           	      J   t        |t              rt        j                  |d      }| j	                  | j                  | j                  | j                  |            j                  d                  }| j                  r|S |j                  d      }| j                  r|S ||fS )z;Perform forward pass of the YOLO model on input image data.r   )
isinstancelistrG   r^   r   r   r   r   r   r_   softmaxra   )r8   r6   rc   s      r9   rd   zClassify.forward  s|    a		!QAKK		$))DIIaL"9"A"A!"DEF==HIIaLKKq+aV+rX   )r   r   Nr   )r   r   r   r   ra   r   r   rC   r   r   rG   r   r   rd   r   r   s   @r9   r!   r!     s|    , F(3 (C (C ( (HSM (]` (&,tELL15<<?@ ,U5<<Y^K^E_ ,rX   r!   c            	            e Zd ZdZddedededef fdZdee	j                     de	j                  d	eee	j                     ef   fd
Zd Z xZS )WorldDetecta  
    Head for integrating YOLO detection models with semantic understanding from text embeddings.

    This class extends the standard Detect head to incorporate text embeddings for enhanced semantic understanding
    in object detection tasks.

    Attributes:
        cv3 (nn.ModuleList): Convolution layers for embedding features.
        cv4 (nn.ModuleList): Contrastive head layers for text-vision alignment.

    Methods:
        forward: Concatenate and return predicted bounding boxes and class probabilities.
        bias_init: Initialize detection head biases.

    Examples:
        Create a WorldDetect head
        >>> world_detect = WorldDetect(nc=80, embed=512, with_bn=False, ch=(256, 512, 1024))
        >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
        >>> text = torch.randn(1, 80, 512)
        >>> outputs = world_detect(x, text)
    r)   embedwith_bnr*   c                    t         |   ||       t        |d   t        | j                  d            t        j                  fd|D              | _        t        j                  fd|D              | _        y)]  
        Initialize YOLO detection layer with nc classes and layer channels ch.

        Args:
            nc (int): Number of classes.
            embed (int): Embedding dimension.
            with_bn (bool): Whether to use batch normalization in contrastive head.
            ch (tuple): Tuple of channel sizes from backbone feature maps.
        r   r.   c           
   3      K   | ]F  }t        j                  t        |d       t        d       t        j                  d             H ywr<   r1   r2   r   r3   r5   r6   r?   r  s     r9   r:   z'WorldDetect.__init__.<locals>.<genexpr>  sB      umntAr1~tBAPRPYPYZ\^cefPg!h u   AAc              3   L   K   | ]  }rt              n	t                 y wNr   r   r5   r   r  r  s     r9   r:   z'WorldDetect.__init__.<locals>.<genexpr>  "      h`aW!25!9/J[![ h   !$N)	rB   rC   rJ   rK   r)   r1   rL   rO   r   r8   r)   r  r  r*   r?   rW   s     `` @r9   rC   zWorldDetect.__init__  s]     	R ADGGS)*== urt uu== heg hhrX   r6   textrY   c           
         t        | j                        D ]]  }t        j                   | j                  |   ||          | j
                  |    | j                  |   ||         |      fd      ||<   _ | j                  r|S | j                  | j                  dz  z   | _
        | j                  |      }| j                  r|S ||fS )r[   r   r-   )r]   rE   rG   r^   rM   r   rO   r_   r)   r4   rF   r`   ra   )r8   r6   r  rb   rc   s        r9   rd   zWorldDetect.forward   s    tww 	[A99kdhhqk!A$/![TXXa[1=NPT1UVXYZAaD	[==H''DLL1,,OOAKKq+aV+rX   c                     | }t        |j                  |j                  |j                        D ]"  \  }}}d|d   j                  j
                  dd $ y)r   r   rp   N)r   rM   rO   rI   r   r   r   s        r9   r   zWorldDetect.bias_init
  sI     155!%%2 	%GAq!!$AbEJJOOA	%rX   r      Fr   )r   r   r   r   r   r   r   rC   r   rG   r   r   rd   r   r   r   s   @r9   r  r    so    ,i3 iC i iRW i,ell+ ,5<< ,E$u||J\^cJcDd ,%rX   r  c            
           e Zd ZdZddej
                  dej
                  dej
                  def fdZdej                  dej                  fd	Z
d
ej                  dej                  dedeeej                  f   fdZ xZS )LRPCHeada]  
    Lightweight Region Proposal and Classification Head for efficient object detection.

    This head combines region proposal filtering with classification to enable efficient detection with
    dynamic vocabulary support.

    Attributes:
        vocab (nn.Module): Vocabulary/classification layer.
        pf (nn.Module): Proposal filter module.
        loc (nn.Module): Localization module.
        enabled (bool): Whether the head is enabled.

    Methods:
        conv2linear: Convert a 1x1 convolutional layer to a linear layer.
        forward: Process classification and localization features to generate detection proposals.

    Examples:
        Create an LRPC head
        >>> vocab = nn.Conv2d(256, 80, 1)
        >>> pf = nn.Conv2d(256, 1, 1)
        >>> loc = nn.Conv2d(256, 4, 1)
        >>> head = LRPCHead(vocab, pf, loc, enabled=True)
    vocabpflocenabledc                     t         |           |r| j                  |      n|| _        || _        || _        || _        y)a`  
        Initialize LRPCHead with vocabulary, proposal filter, and localization components.

        Args:
            vocab (nn.Module): Vocabulary/classification module.
            pf (nn.Module): Proposal filter module.
            loc (nn.Module): Localization module.
            enabled (bool): Whether to enable the head functionality.
        N)rB   rC   conv2linearr  r  r  r  )r8   r  r  r  r  rW   s        r9   rC   zLRPCHead.__init__-  s;     	07T%%e,U
rX   r   rY   c                 x   t        |t        j                        r|j                  dk(  sJ t        j                  |j
                  |j                        }|j                  j                  |j                  d      j                  |j                  _	        |j                  j                  |j                  _	        |S )z4Convert a 1x1 convolutional layer to a linear layer.)r   r   rp   )r  r1   r3   kernel_sizer   in_channelsout_channelsweightr   r   r   )r8   r   r   s      r9   r!  zLRPCHead.conv2linear=  s    $		*t/?/?6/III4++T->->?![[--d.?.?DII99>>rX   cls_featloc_featconfc                    | j                   r| j                  |      d   j                  d      }|j                         |kD  }|j                  d      j	                  dd      }| j                  |r	|dd|f   n!||j                  d      j                         z        }| j                  |      |j	                  dd      f|fS | j                  |      }| j                  |      }||j                  d      ft        j                  |j                  d   |j                  d   z  |j                  t        j                        fS )	zQProcess classification and localization features to generate detection proposals.)r   r   r   rh   rp   Nr0   )r   dtype)r  r  r   r   ru   r  r   r   r  rG   onesr   r   r   )r8   r'  r(  r)  pf_scoremasks         r9   rd   zLRPCHead.forwardE  s   <<wwx(.66q9H##%,D''*44R<Hzzt(1d7"3DNN[]L^LbLbLdAdeHHHX&(:(:2r(BCTIIzz(+Hxx)Hh..q12EJJq!HNN1$55hooUZU_U_5  rX   r   )r   r   r   r   r1   Moduler   rC   r3   r   r!  rG   r   r   r   rd   r   r   s   @r9   r  r    s    0bii RYY RYY QU  		 bii   E V[\achcoco\oVp rX   r  c                       e Zd ZdZdZddedededef fdZ e	       de
j                  fd	       Zd
ee
j                     dee
j                     fdZdee
j                     de
j                  de
j                  fdZddee
j                     dedee
j                  ef   fdZ	 ddee
j                     de
j                  dedee
j                  ef   fdZd Z xZS )r%   a  
    Head for integrating YOLO detection models with semantic understanding from text embeddings.

    This class extends the standard Detect head to support text-guided detection with enhanced semantic understanding
    through text embeddings and visual prompt embeddings.

    Attributes:
        is_fused (bool): Whether the model is fused for inference.
        cv3 (nn.ModuleList): Convolution layers for embedding features.
        cv4 (nn.ModuleList): Contrastive head layers for text-vision alignment.
        reprta (Residual): Residual block for text prompt embeddings.
        savpe (SAVPE): Spatial-aware visual prompt embeddings module.
        embed (int): Embedding dimension.

    Methods:
        fuse: Fuse text features with model weights for efficient inference.
        get_tpe: Get text prompt embeddings with normalization.
        get_vpe: Get visual prompt embeddings with spatial awareness.
        forward_lrpc: Process features with fused text embeddings for prompt-free model.
        forward: Process features with class prompt embeddings to generate detections.
        bias_init: Initialize biases for detection heads.

    Examples:
        Create a YOLOEDetect head
        >>> yoloe_detect = YOLOEDetect(nc=80, embed=512, with_bn=True, ch=(256, 512, 1024))
        >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
        >>> cls_pe = torch.randn(1, 80, 512)
        >>> outputs = yoloe_detect(x, cls_pe)
    Fr)   r  r  r*   c                    t         |   ||       t        |d   t        | j                  d            k  sJ du sJ | j
                  rt        j                  fd|D              nt        j                  fd|D              | _        t        j                  fd|D              | _	        t        t                    | _        t        |      | _        | _        y)r	  r   r.   Tc           
   3      K   | ]F  }t        j                  t        |d       t        d       t        j                  d             H ywr<   r  r  s     r9   r:   z'YOLOEDetect.__init__.<locals>.<genexpr>  s?     nfg"--QARQSUW\^_I`anr  c              3     K   | ]  }t        j                  t        j                  t        ||d       t        |d            t        j                  t        d       t        d            t        j                  d              ywr<   )r1   r2   r   r   r3   r  s     r9   r:   z'YOLOEDetect.__init__.<locals>.<genexpr>  sq        MM&Aq/42q>BMM&R"3T"b!_EIIb%+s   B
Bc              3   L   K   | ]  }rt              n	t                 y wr  r  r  s     r9   r:   z'YOLOEDetect.__init__.<locals>.<genexpr>  r  r  N)rB   rC   rJ   rK   r)   rN   r1   rL   rO   r   r   r   reprtar   savper  r  s     `` @r9   rC   zYOLOEDetect.__init__v  s     	R ADGGS)*U{{$ {{ MMnkmnn    	 == heg hhy672r5)

rX   	txt_featsc                 F   | j                   ry| j                  rJ |j                  t        j                        j                  d      }t        | j                  | j                        D ]  \  }}t        |t        j                        sJ t        |t              sJ |d   }t        |t        j                        sJ |j                  }|j                  }|j                   }||j#                         z  }t%        ||      }|j&                  j(                  j                  d      j                  d      }	|j                  j(                  }
||	z  }	||
j+                  d      j-                  d      z  j                  d      }t        j.                  |      |z  }t        j                  |j0                  |	j2                  d   d      j5                  d      j                  |j&                  j6                        }|j&                  j(                  j9                  |	j-                  d      j-                  d             |j                  j(                  j9                  ||z          ||d<   |j;                           | `t        j>                         | _        d| _         y)z>Fuse text features with model weights for efficient inference.Nr   rp   r   )r#  FT) is_fusedr_   torG   float32squeezer   rO   r   r  r1   r2   r   r3   logit_scaler   r   expr   r&  r   r   r   	ones_liker$  r   requires_grad_r   copy_fuser6  rP   )r8   r8  cls_headbn_headr   r>  r   r   twr   b1b2s                r9   rC  zYOLOEDetect.fuse  s    ====  LL/77:	!$TXXtxx!8 !	Hgh666g'8999B<DdBII...!--K<<D<<DKOO--A.tT:D  ((,44R8A		AAAaiim--b11::2>B$t+B 		$$GGAJ !
  &DKK&&'  KK""1;;r?#<#<R#@AIINN  b)HRLLLNC!	F KkkmrX   tperY   c                 X    |dS t        j                  | j                  |      dd      S )z.Get text prompt embeddings with normalization.Nrp   rh   )r   r   )F	normalizer6  )r8   rJ  s     r9   get_tpezYOLOEDetect.get_tpe  s(    {tRDKK4D"PQ(RRrX   r6   vpec                    |j                   d   dk(  r@t        j                  |d   j                   d   d| j                  |d   j                        S |j
                  dk(  r| j                  ||      }|j
                  dk(  sJ |S )z4Get visual prompt embeddings with spatial awareness.r   r   r~   r-   r0   )r   rG   rH   r  r   r   r7  )r8   r6   rO  s      r9   get_vpezYOLOEDetect.get_vpe  so    99Q<1;;qtzz!}aAaDKKPP88q=**Q$Cxx1}}
rX   return_maskc           
         g }| j                   sJ d       t        | j                        D ]  } | j                  |   ||         } | j                  |   ||         }t        | j                  |   t              sJ  | j                  |   ||| j                  r| j                  sdnt        | dd            \  ||<   }|j                  |        |d   d   j                  }| j                  s| j                  |k7  rCd t        |D 	cg c]  }	|	d   	 c}	| j                  d      D        \  | _        | _        || _        t#        j$                  |D 
cg c](  }
|
d   j'                  |d   | j(                  dz  d      * c}
d	      }t#        j$                  |D 
cg c]  }
|
d
   	 c}
d	      }| j                  r| j*                  dv r|d	   }|d   }t#        j,                  ||||g|j.                        j1                  d
dd
      }| j                   | j                  d   |z  z  }| j3                  | j5                  |      |z  | j                  j7                  d      |dddd	f   z        }nG| j3                  | j5                  |      | j                  j7                  d            | j                   z  }t#        j$                  |      }t#        j$                  | j                  r| j                  s|n|d|f   |j9                         fd
      }|r| j                  r||fS ||f|fS | j                  r|S ||fS c c}	w c c}
w c c}
w )zYProcess features with fused text embeddings to generate detections for prompt-free model.z1Prompt-free inference requires model to be fused!r   r)  gMbP?c              3   @   K   | ]  }|j                  d d        ywrs   rt   rv   s     r9   r:   z+YOLOEDetect.forward_lrpc.<locals>.<genexpr>  s     )w!++a*;)wrw   rx   r-   rp   rh   r   >   r{   r|   r0   r~   N.)r:  r]   rE   rO   rM   r  lrpcr  ra   r   getattrappendr   r   rI   r   r   rG   r^   r   r4   r   r   r   r   r   rQ   r   r   )r8   r6   rR  masksrb   r'  r(  r/  r   r   rm   r   r   r   r   r   r   r   rc   s                      r9   forward_lrpczYOLOEDetect.forward_lrpc  s   }}QQQ}tww 	A"txx{1Q4(H"txx{1Q4(HdiilH555%1(T\\AwW[]cejOkJAaD$ LL	 !Q<<4::.)w\abRc\]STUVSWRceiepepruEv)w&DL$,DJiiaPAE!HdllQ.>CPRSTii+2A+Q/;;4;;*?? 1XF1XFffff%EcjjYaabcefhijI<<4;;q>I#=>D%%dhhsmd&:DLL<R<RST<UX\]^`bab`b]bXc<cdD%%dhhsmT\\5K5KA5NORVR^R^^DyyIIt{{4<<tT#t)_VYVaVaVcdfgh $At9?1a&$?1/!Q/- SdP+s   
L?
-MM	cls_pec           
         t        | d      r| j                  ||      S t        | j                        D ]]  }t	        j
                   | j                  |   ||          | j                  |    | j                  |   ||         |      fd      ||<   _ | j                  r|S | j                  | j                  dz  z   | _        | j                  |      }| j                  r|S ||fS )zEProcess features with class prompt embeddings to generate detections.rU  r   r-   )hasattrrY  r]   rE   rG   r^   rM   r   rO   r_   r)   r4   rF   r`   ra   )r8   r6   rZ  rR  rb   rc   s         r9   rd   zYOLOEDetect.forward  s     4 $$Q44tww 	]A99kdhhqk!A$/![TXXa[1=NPV1WXZ[\AaD	]==H''DLL1,,OOAKKq+aV+rX   c                 |   | }t        |j                  |j                  |j                  |j                        D ]  \  }}}}d|d   j
                  j                  dd d|d   j
                  j                  dd t        j                  d|j                  z  d|z  dz  z        |j
                  j                  dd  y)z&Initialize biases for detection heads.r   rp   Nr   r   r   rh   )
r   rM   rO   r   rI   r   r   r   r   r)   )r8   r   r   r   cr   s         r9   r   zYOLOEDetect.bias_init  s     aeeQUUAEE188< 	AJAq!Q!$AbEJJOOA!$AbEJJOOA!XXa!$$h#'a&?@AFFKKN		ArX   r  )F)r   r   r   r   r:  r   r   r   rC   r   rG   r   rC  r   rN  r   rQ  r   rY  rd   r   r   r   s   @r9   r%   r%   U  s,   < H3 C  RW B ,ell , ,\S8ELL1 Shu||6L Sell+ %,, 5<< $0d5<<0 $0t $0PUV[VbVbdiViPj $0N PU,ell#,-2\\,HL,	u||U"	#,	ArX   r%   c                        e Zd ZdZ	 ddedededededef fdZd	ee	j                     d
e	j                  deee	j                  f   fdZ xZS )r&   a[  
    YOLO segmentation head with text embedding capabilities.

    This class extends YOLOEDetect to include mask prediction capabilities for instance segmentation tasks
    with text-guided semantic understanding.

    Attributes:
        nm (int): Number of masks.
        npr (int): Number of protos.
        proto (Proto): Prototype generation module.
        cv5 (nn.ModuleList): Convolution layers for mask coefficients.

    Methods:
        forward: Return model outputs and mask coefficients.

    Examples:
        Create a YOLOESegment head
        >>> yoloe_segment = YOLOESegment(nc=80, nm=32, npr=256, embed=512, with_bn=True, ch=(256, 512, 1024))
        >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
        >>> text = torch.randn(1, 80, 512)
        >>> outputs = yoloe_segment(x, text)
    r)   r   r   r  r  r*   c                     t            ||||       | _        | _        t	        |d    j                   j                         _        t        |d   dz   j                        t        j                   fd|D               _	        y)a  
        Initialize YOLOESegment with class count, mask parameters, and embedding dimensions.

        Args:
            nc (int): Number of classes.
            nm (int): Number of masks.
            npr (int): Number of protos.
            embed (int): Embedding dimension.
            with_bn (bool): Whether to use batch normalization in contrastive head.
            ch (tuple): Tuple of channel sizes from backbone feature maps.
        r   r-   c           
   3      K   | ]P  }t        j                  t        |d       t        d       t        j                  j                  d             R ywr<   r   )r5   r6   c5r8   s     r9   r:   z(YOLOESegment.__init__.<locals>.<genexpr>?  r   r@   N)
rB   rC   r   r   r   r   rJ   r1   rL   cv5)	r8   r)   r   r   r  r  r*   rb  rW   s	   `      @r9   rC   zYOLOESegment.__init__+  sq     	UGR02a5$((DGG4
A!TWW%== wtv wwrX   r6   r  rY   c           
         | j                  |d         }|j                  d   }t        j                  t	        | j
                        D cg c]5  } | j                  |   ||         j                  || j                  d      7 c}d      }t        | d      }|st        j                  | ||      }nt        j                  | ||d      \  }}| j                  r|||fS |r2| j                  r| j                  s|j                         z  n|df   }| j                  rt        j                  ||gd      |fS t        j                  |d   |gd      |d   ||ffS c c}w )	r   r   rp   rh   rU  T)rR  .r   )r   r   rG   r^   r]   rE   rc  r   r   r\  r%   rd   r_   ra   r   r   )	r8   r6   r  r   r   rb   r   has_lrpcr/  s	            r9   rd   zYOLOESegment.forwardA  s;   JJqtWWQZYYtwwXAAaD)..r477B?XZ[\4(##D!T2A!))$4T)JGAt==b!8O&*kk$,,"txxz/BsTXyMB-1[[		1b'1%q)guyy!A$PRUV?WZ[\]Z^`bdeYf>gg Ys   
:E)r   r   r   r  Fr   )r   r   r   r   r   r   r   rC   r   rG   r   r   rd   r   r   s   @r9   r&   r&     s    0 prxx #x/2xADxUYxglx,hell+ h5<< hE%QVQ]Q]J]D^ hrX   r&   c                       e Zd ZdZdZddddddd	d
d ej                         dddddfdedededededededede	dej                  dedede	de	def fdZd3d eej                     d!ee   d"eeej                  f   fd#Zd$ej(                  d%d&fd'eee      d(e	d)ej*                  d*ed+e	d"eej                  ej                  f   fd,Zd eej                     d"eej                  eee      f   fd-Z	 	 d4d.ej                  d'eee      d/eej                     d0eej                     d"eej                  ej                  ej                  ej                  f   f
d1Zd2 Z xZS )5r#   a  
    Real-Time Deformable Transformer Decoder (RTDETRDecoder) module for object detection.

    This decoder module utilizes Transformer architecture along with deformable convolutions to predict bounding boxes
    and class labels for objects in an image. It integrates features from multiple layers and runs through a series of
    Transformer decoder layers to output the final predictions.

    Attributes:
        export (bool): Export mode flag.
        hidden_dim (int): Dimension of hidden layers.
        nhead (int): Number of heads in multi-head attention.
        nl (int): Number of feature levels.
        nc (int): Number of classes.
        num_queries (int): Number of query points.
        num_decoder_layers (int): Number of decoder layers.
        input_proj (nn.ModuleList): Input projection layers for backbone features.
        decoder (DeformableTransformerDecoder): Transformer decoder module.
        denoising_class_embed (nn.Embedding): Class embeddings for denoising.
        num_denoising (int): Number of denoising queries.
        label_noise_ratio (float): Label noise ratio for training.
        box_noise_scale (float): Box noise scale for training.
        learnt_init_query (bool): Whether to learn initial query embeddings.
        tgt_embed (nn.Embedding): Target embeddings for queries.
        query_pos_head (MLP): Query position head.
        enc_output (nn.Sequential): Encoder output layers.
        enc_score_head (nn.Linear): Encoder score prediction head.
        enc_bbox_head (MLP): Encoder bbox prediction head.
        dec_score_head (nn.ModuleList): Decoder score prediction heads.
        dec_bbox_head (nn.ModuleList): Decoder bbox prediction heads.

    Methods:
        forward: Run forward pass and return bounding box and classification scores.

    Examples:
        Create an RTDETRDecoder
        >>> decoder = RTDETRDecoder(nc=80, ch=(512, 1024, 2048), hd=256, nq=300)
        >>> x = [torch.randn(1, 512, 64, 64), torch.randn(1, 1024, 32, 32), torch.randn(1, 2048, 16, 16)]
        >>> outputs = decoder(x)
    Fr   )r     i   r   r(   r-         rg  r   rp   r.   rx   r   r)   r*   hdnqndpnhndld_ffndropoutacteval_idxndlabel_noise_ratiobox_noise_scalelearnt_init_queryc                    t         |           | _        || _        t	        |      | _        || _        || _        || _        t        j                  fd|D              | _        t        |||	|
| j
                  |      }t        |||      | _        t        j                  |      | _        || _        || _        || _        || _        |rt        j                  |      | _        t-        ddz  d      | _        t        j0                  t        j2                        t        j4                              | _        t        j2                  |      | _        t-        dd      | _        t        j                  t=        |      D cg c]  }t        j2                  |       c}      | _        t        j                  t=        |      D cg c]  }t-        dd       c}      | _         | jC                          yc c}w c c}w )a  
        Initialize the RTDETRDecoder module with the given parameters.

        Args:
            nc (int): Number of classes.
            ch (tuple): Channels in the backbone feature maps.
            hd (int): Dimension of hidden layers.
            nq (int): Number of query points.
            ndp (int): Number of decoder points.
            nh (int): Number of heads in multi-head attention.
            ndl (int): Number of decoder layers.
            d_ffn (int): Dimension of the feed-forward networks.
            dropout (float): Dropout rate.
            act (nn.Module): Activation function.
            eval_idx (int): Evaluation index.
            nd (int): Number of denoising.
            label_noise_ratio (float): Label noise ratio.
            box_noise_scale (float): Box noise scale.
            learnt_init_query (bool): Whether to learn initial query embeddings.
        c           	   3      K   | ]D  }t        j                  t        j                  |d d      t        j                               F yw)r   F)r   N)r1   r2   r3   BatchNorm2d)r5   r6   rj  s     r9   r:   z)RTDETRDecoder.__init__.<locals>.<genexpr>  s9     'wopbii2qu6UWYWeWefhWi(j'ws   A
Ar-   rh   )
num_layersr0   N)"rB   rC   
hidden_dimnheadrD   rE   r)   num_queriesnum_decoder_layersr1   rL   
input_projr   r   decoder	Embeddingdenoising_class_embednum_denoisingrt  ru  rv  	tgt_embedr   query_pos_headr2   r   	LayerNorm
enc_outputenc_score_headenc_bbox_headr]   dec_score_headdec_bbox_head_reset_parameters)r8   r)   r*   rj  rk  rl  rm  rn  ro  rp  rq  rr  rs  rt  ru  rv  decoder_layerr   rW   s      `              r9   rC   zRTDETRDecoder.__init__  s   N 	
b'"% --'wtv'ww
 :"b%RUW[W^W^`cd3BsHU &(\\"b%9"!2. "3\\"b1DN!!QVRA> --		"b(92<<;KL iiB/ Rq9 !mmc
,S1RYYr2->,ST]]RWX[R\+]QCBa,H+]^  -T+]s   HH
r6   batchrY   c           
      z   ddl m} | j                  |      \  }} ||| j                  | j                  | j
                  j                  | j                  | j                  | j                  | j                        \  }}}}	| j                  ||||      \  }
}}}| j                  |
|||| j                  | j                  | j                  |      \  }}|||||	f}| j                  r|S t!        j"                  |j%                  d      |j%                  d      j'                         fd      }| j(                  r|S ||fS )a*  
        Run the forward pass of the module, returning bounding box and classification scores for the input.

        Args:
            x (List[torch.Tensor]): List of feature maps from the backbone.
            batch (dict, optional): Batch information for training.

        Returns:
            outputs (tuple | torch.Tensor): During training, returns a tuple of bounding boxes, scores, and other
                metadata. During inference, returns a tensor of shape (bs, 300, 4+nc) containing bounding boxes and
                class scores.
        r   )get_cdn_group)	attn_maskrp   )ultralytics.models.utils.opsr  _get_encoder_inputr)   r}  r  r&  r  rt  ru  r_   _get_decoder_inputr  r  r  r  rG   r^   r=  r   ra   )r8   r6   r  r  featsshapesdn_embeddn_bboxr  dn_metar  
refer_bbox
enc_bboxes
enc_scores
dec_bboxes
dec_scoresrc   s                    r9   rd   zRTDETRDecoder.forward  sF    	? //2v 1>GG&&--""  MM	1
-'9g 594K4KESY[cel4m1z:z "& ". 	"

J 
J
GC==HIIz))!,j.@.@.C.K.K.MNPRSKKq+aV+rX   g?cpu{Gz?r  r   r,  r   epsc                 .   g }t        |      D ]  \  }\  }}	t        j                  |||      }
t        j                  |	||      }t        rt        j                  |
|d      nt        j                  |
|      \  }}t        j
                  ||gd      }t        j                  |	|g||      }|j                  d      dz   |z  }t        j                  |||      |z  d|z  z  }|j                  t        j                  ||gd      j                  d||	z  d	              t        j                  |d
      }||kD  |d
|z
  k  z  j                  dd      }t        j                  |d
|z
  z        }|j                  | t        d            }||fS )aL  
        Generate anchor bounding boxes for given shapes with specific grid size and validate them.

        Args:
            shapes (list): List of feature map shapes.
            grid_size (float, optional): Base size of grid cells.
            dtype (torch.dtype, optional): Data type for tensors.
            device (str, optional): Device to create tensors on.
            eps (float, optional): Small value for numerical stability.

        Returns:
            anchors (torch.Tensor): Generated anchor boxes.
            valid_mask (torch.Tensor): Valid mask for anchors.
        )endr,  r   ij)indexingrp   r,  r   r   rx   r   r-   r   T)keepdiminf)	enumeraterG   r   r	   meshgridstackr   r   r@  rW  r^   r   allr   masked_fillr   )r8   r  r   r,  r   r  r   rb   hrG  sysxgrid_ygrid_xgrid_xyvalid_WHwh
valid_masks                     r9   _generate_anchorszRTDETRDecoder._generate_anchors  s~   , "6* 		LIAv1!5@B!5@BFPU^^BTBV[VdVdegikVlNFFkk66"2B7G||QF%GH((+c1X=GfE	QUXZ[U[\BNN599gr]B7<<RQJK		L ))GQ'}1s7):;@@T@R
))Gq7{34%%zk5<@
""rX   c                 d   t        |      D cg c]  \  }} | j                  |   |       }}}g }g }|D ]X  }|j                  dd \  }}|j                  |j	                  d      j                  ddd             |j                  ||g       Z t        j                  |d      }||fS c c}}w )aO  
        Process and return encoder inputs by getting projection features from input and concatenating them.

        Args:
            x (List[torch.Tensor]): List of feature maps from the backbone.

        Returns:
            feats (torch.Tensor): Processed features.
            shapes (list): List of feature map shapes.
        rh   Nr   r   )r  r  r   rW  r   rk   rG   r^   )r8   r6   rb   featr  r  r  rG  s           r9   r  z RTDETRDecoder._get_encoder_input+  s     6?q\B'!TT__Q%BB 	"D::ab>DAqLLa00Aq9:MM1a&!	" 		%#f} Cs   B,r  r  r  c                    |j                   d   }| j                  ||j                  |j                        \  }}| j	                  ||z        }| j                  |      }	t        j                  |	j                  d      j                  | j                  d      j                  j                  d      }
t        j                  ||
j                        j                  d      j                  d| j                        j                  d      }|||
f   j                  || j                  d      }|dd|
f   j                  || j                  d      }| j!                  |      |z   }|j#                         }|t        j$                  ||gd      }|	||
f   j                  || j                  d      }| j&                  r6| j(                  j*                  j                  d      j                  |dd      n|}| j,                  r,|j/                         }| j&                  s|j/                         }|t        j$                  ||gd      }||||fS )a  
        Generate and prepare the input required for the decoder from the provided features and shapes.

        Args:
            feats (torch.Tensor): Processed features from encoder.
            shapes (list): List of feature map shapes.
            dn_embed (torch.Tensor, optional): Denoising embeddings.
            dn_bbox (torch.Tensor, optional): Denoising bounding boxes.

        Returns:
            embeddings (torch.Tensor): Query embeddings for decoder.
            refer_bbox (torch.Tensor): Reference bounding boxes.
            enc_bboxes (torch.Tensor): Encoded bounding boxes.
            enc_scores (torch.Tensor): Encoded scores.
        r   r  rp   r   r   )r  r,  N)r   r  r,  r   r  r  rG   r   rJ   valuesr}  indicesr   r   r   r   r  r   r^   rv  r  r&  r_   ri   )r8   r  r  r  r  r   r   r  featuresenc_outputs_scorestopk_ind	batch_indtop_k_featurestop_k_anchorsr  r  r  
embeddingss                     r9   r  z RTDETRDecoder._get_decoder_inputF  s   , [[^"44V5;;W\WcWc4d??:#56!00: ::044R8??AQAQWXYaaffgijLLRx~~>HHLSSTUW[WgWghmmnpq	 ")X"56;;B@P@PRTU8,11"d6F6FK ''7-G
'')
GZ#8!<J'	8(;<AA"dFVFVXZ[
LPLbLbT^^**44Q7>>r1aHhv
==#**,J))'..0
Hj#91=J:z:==rX   c                    t        d      dz  | j                  z  }t        | j                  j                  |       t        | j
                  j                  d   j                  d       t        | j
                  j                  d   j                  d       t        | j                  | j                        D ]a  \  }}t        |j                  |       t        |j                  d   j                  d       t        |j                  d   j                  d       c t        | j                  d          t        | j                  d   j                         | j                  rt        | j                  j                         t        | j                   j                  d   j                         t        | j                   j                  d   j                         | j"                  D ]  }t        |d   j                          y)zhInitialize or reset the parameters of the model's various components with predefined weights and biases.r  r   rp   r   r   r   N)r   r)   r   r  r   r  layersr&  r   r  r  r   r  r   rv  r  r  r  )r8   bias_clscls_reg_layers        r9   r  zRTDETRDecoder._reset_parameters  s    't,r1DGG; 	$%%**H5$$$++B/66<$$$++B/44c:d1143E3EF 	1JD$dii*dkk"o,,c2dkk"o**C0		1 	DOOA&'*112!!DNN112++2215<<=++2215<<=__ 	-EE!HOO,	-rX   r  )NN)r   r   r   r   ra   r1   ReLUr   r   r   r0  r   rC   r   rG   r   r   r   r   rd   r<  r,  strr  r  r  r  r   r   s   @r9   r#   r#   W  sS   &P F % #&!$"'#M!M! M! 	M!
 M! M! M! M! M! M! YYM! M! M! !M!  !M!"  #M!^0,ell+ 0,HTN 0,eTY[`[g[gTgNh 0,j  "]]&#T#Y&# &# {{	&#
 &# &# 
u||U\\)	*&#PD$6 5tTXY\T]A^;_ > ,0*.8>||8> T#Y8> 5<<(	8>
 %,,'8> 
u||U\\5<<E	F8>t-rX   r#   c                   8     e Zd ZdZdZddedef fdZd Z xZ	S )r$   a  
    v10 Detection head from https://arxiv.org/pdf/2405.14458.

    This class implements the YOLOv10 detection head with dual-assignment training and consistent dual predictions
    for improved efficiency and performance.

    Attributes:
        end2end (bool): End-to-end detection mode.
        max_det (int): Maximum number of detections.
        cv3 (nn.ModuleList): Light classification head layers.
        one2one_cv3 (nn.ModuleList): One-to-one classification head layers.

    Methods:
        __init__: Initialize the v10Detect object with specified number of classes and input channels.
        forward: Perform forward pass of the v10Detect module.
        bias_init: Initialize biases of the Detect module.
        fuse: Remove the one2many head for inference optimization.

    Examples:
        Create a v10Detect head
        >>> v10_detect = v10Detect(nc=80, ch=(256, 512, 1024))
        >>> x = [torch.randn(1, 256, 80, 80), torch.randn(1, 512, 40, 40), torch.randn(1, 1024, 20, 20)]
        >>> outputs = v10_detect(x)
    Tr)   r*   c                      t            ||       t        |d   t         j                  d            t        j                   fd|D               _        t        j                   j                         _
        y)z
        Initialize the v10Detect object with the specified number of classes and input channels.

        Args:
            nc (int): Number of classes.
            ch (tuple): Tuple of channel sizes from backbone feature maps.
        r   r.   c              3   :  K   | ]  }t        j                  t        j                  t        ||d |      t        |d            t        j                  t        d       t        d            t        j                  j                  d              yw)r0   )r   r   Nr=   r>   s     r9   r:   z%v10Detect.__init__.<locals>.<genexpr>  sz      !
  MMd1aa0$q"a.Ad2r13T"b!_E		"dggq)!
s   BBN)rB   rC   rJ   rK   r)   r1   rL   rO   rS   rT   rV   )r8   r)   r*   r?   rW   s   `  @r9   rC   zv10Detect.__init__  se     	R ADGGS)*== !
 !
 
  ==2rX   c                     t        j                  t        j                         g| j                  z        x| _        | _        y)z4Remove the one2many head for inference optimization.N)r1   rL   rP   rE   rM   rO   )r8   s    r9   rC  zv10Detect.fuse  s*     mmR[[]Odgg,EFF48rX   r   )
r   r   r   r   rR   r   r   rC   rC  r   r   s   @r9   r$   r$     s(    2 G33 3 3*GrX   r$   )8r   rS   r   typingr   r   r   r   rG   torch.nnr1   torch.nn.functional
functionalrL  torch.nn.initr   r   ultralytics.utils.talr	   r
   r   r   ultralytics.utils.torch_utilsr   r   blockr   r   r   r   r   r   r   r   r   r   transformerr   r   r   utilsr   r   __all__r0  r   r   r"   r    r!   r  r  r%   r&   r#   r$   r   rX   r9   <module>r     s       / /     4 P P P ] ] ]  ] ] 3
uNnRYY Nnb1hf 1hh5=& 5=pK6 K\4,ryy 4,n6%& 6%t>ryy >B{A& {A|Ah; AhH-BII -D
3G 3GrX   