
    /jL2                      d Z ddlmZ ddlZddl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 ddlmZmZmZ ddlmZmZmZ dd	lmZmZmZmZmZmZmZm Z m!Z! dd
l"m#Z#m$Z$ ddl%m&Z&m'Z'm(Z( ddl)m*Z*m+Z+ dZ, G d dej-                  Z. G d de.          Z/ G d de/          Z0 G d de.          Z1 G d de1          Z2 G d de.          Z3 G d de3          Z4 G d dej-                  Z5 G d de.          Z6 G d  d!ej-                  Z7 G d" d#e.          Z8 G d$ d%e8          Z9 G d& d'e9          Z: G d( d)ej-                  Z; G d* d+e.          Z<dS ),zModel head modules.    )annotationsN)	constant_xavier_uniform_)NOT_MACOS14)	dist2bbox	dist2rboxmake_anchors)
TORCH_1_11fuse_conv_and_bnsmart_inference_mode   )	DFLSAVPEBNContrastiveHeadContrastiveHeadProtoProto26RealNVPResidual	SwiGLUFFN)ConvDWConv)MLPDeformableTransformerDecoder!DeformableTransformerDecoderLayer)bias_init_with_problinear_init)	OBBClassifyDetectPoseRTDETRDecoderSegmentYOLOEDetectYOLOESegment	v10Detectc                  4    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/ fdZed             Zed             Zed             Zej        d             Z	 d0d1dZd2dZd3dZd3dZd Zd4d5d%Zd6d'Zd7d+Zd8d-Z xZS )9r    aU  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/v11 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.
        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   P       ncintchtuplec                b    t                                                       | _        t          |           _        | _        | 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k    rt#           j                  nt          j                     _        |r>t)          j         j                   _        t)          j         j                   _        d	S d	S )
ac  Initialize the YOLO detection layer with specified number of classes and channels.

        Args:
            nc (int): Number of classes.
            reg_max (int): Maximum number of DFL channels.
            end2end (bool): Whether to use end-to-end NMS-free detection.
            ch (tuple): Tuple of channel sizes from backbone feature maps.
           r*   r   d   c           
   3     K   | ]T}t          j        t          |d           t          d           t          j        dj        z  d                    V  UdS )   r1   r   N)nn
Sequentialr   Conv2dreg_max).0xc2selfs     `/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/ultralytics/nn/modules/head.py	<genexpr>z"Detect.__init__.<locals>.<genexpr>^   sl       !
 !
cdBM$q"a..$r2q//29RT\IY[\;];]^^!
 !
 !
 !
 !
 !
    c           
   3     K   | ]Q}t          j        t          |d           t          d           t          j        j        d                    V  RdS r4   r   Nr5   r6   r   r7   r,   r9   r:   c3r<   s     r=   r>   z"Detect.__init__.<locals>.<genexpr>b   sZ      pphi"-QARQSUW[W^`aIbIbccppppppr?   c              3  :  K   | ]}t          j        t          j        t          ||d           t          |d                    t          j        t          d           t          d                    t          j        j        d                    V  dS rA   )r5   r6   r   r   r7   r,   rC   s     r=   r>   z"Detect.__init__.<locals>.<genexpr>d   s          M&Aq//42q>>BBM&R"3"3T"b!__EEIb$'1--      r?   r   N)super__init__r,   lennlr8   notorchzerosstridemaxminr5   
ModuleListcv2legacycv3r   Identitydflcopydeepcopyone2one_cv2one2one_cv3)r<   r,   r8   end2endr.   r;   rD   	__class__s   `    @@r=   rG   zDetect.__init__N   s    	b''t|a''k$'**b"Q%1*dlQ&6788#beSRUEVEV:W:WB= !
 !
 !
 !
 !
hj!
 !
 !
 
 

 {	BMpppppmopppppp           	 )-q(8(83t|$$$bkmm 	7#}TX66D#}TX66D	7 	7r?   c                8    t          | j        | j                  S )YReturns the one-to-many head components, here for v3/v5/v8/v9/v11 backward compatibility.box_headcls_head)dictrQ   rS   r<   s    r=   one2manyzDetect.one2manys   s     TX9999r?   c                8    t          | j        | j                  S )'Returns the one-to-one head components.r^   )ra   rX   rY   rb   s    r=   one2onezDetect.one2onex   s     T-8HIIIIr?   c                D    t          | dd          ot          | d          S )zKChecks if the model has one2one for v3/v5/v8/v9/v11 backward compatibility._end2endTrf   )getattrhasattrrb   s    r=   rZ   zDetect.end2end}   s%     tZ..K743K3KKr?   c                    || _         dS )z'Override the end-to-end detection mode.N)rh   )r<   values     r=   rZ   zDetect.end2end   s     r?   r:   list[torch.Tensor]r_   torch.nn.Moduler`   returndict[str, torch.Tensor]c                V    t                      S d         j        d         t          j         fdt	           j                  D             d          }t          j         fdt	           j                  D             d          }t          ||          S )JConcatenates and returns predicted bounding boxes and class probabilities.Nr   c                x    g | ]6} |         |                                        d j        z  d          7S r1   viewr8   r9   ir_   bsr<   r:   s     r=   
<listcomp>z'Detect.forward_head.<locals>.<listcomp>   E    dddPQ;8A;qt,,11"a$,6FKKdddr?   ru   dimc                r    g | ]3} |         |                                        j        d           4S ru   )rw   r,   )r9   ry   rz   r`   r<   r:   s     r=   r{   z'Detect.forward_head.<locals>.<listcomp>   s?    \\\KHQK!--222twCC\\\r?   boxesscoresfeats)ra   shaperK   catrangerI   )r<   r:   r_   r`   r   r   rz   s   ````  @r=   forward_headzDetect.forward_head   s     x/66MqTZ]	dddddddUZ[_[bUcUcdddjlmmm\\\\\\\USWSZ^^\\\bdeee%a8888r?   Udict[str, torch.Tensor] | torch.Tensor | tuple[torch.Tensor, dict[str, torch.Tensor]]c                T    | j         |fi | j        }| j        r$d |D             } | j         |fi | j        }||d}| j        r|S |                     | j        r|d         n|          }| j        r*|                     |                    ddd                    }| j        r|n||fS )rr   c                6    g | ]}|                                 S r+   detachr9   xis     r=   r{   z"Detect.forward.<locals>.<listcomp>   s     000		000r?   )rc   rf   rf   r      r   )	r   rc   rZ   rf   training
_inferencepostprocesspermuteexport)r<   r:   predsx_detachrf   ys         r=   forwardzDetect.forward   s     "!!55t}55< 	<00a000H'd'AADLAAG!&7;;E= 	LOOGE),,%HH< 	5  1a!3!344AK/qqaZ/r?   torch.Tensorc                    |                      |          }t          j        ||d                                         fd          S )aD  Decode predicted bounding boxes and class probabilities based on multiple-level feature maps.

        Args:
            x (dict[str, torch.Tensor]): Dictionary of predictions from detection layers.

        Returns:
            (torch.Tensor): Concatenated tensor of decoded bounding boxes and class probabilities.
        r   r   )_get_decode_boxesrK   r   sigmoid)r<   r:   dboxs      r=   r   zDetect._inference   s>     %%a((y$( 3 3 5 56:::r?   c                b   |d         d         j         }| j        s| j         |k    r:d t          |d         | j        d          D             \  | _        | _        || _         |                     |                     |d                   | j                            d                    | j        z  }|S )z/Get decoded boxes based on anchors and strides.r   r   c              3  B   K   | ]}|                     d d          V  dS )r   r   N)	transpose)r9   as     r=   r>   z+Detect._get_decode_boxes.<locals>.<genexpr>   s0      )p)p!++a*;*;)p)p)p)p)p)pr?         ?r   )	r   dynamicr	   rM   anchorsstridesdecode_bboxesrU   	unsqueeze)r<   r:   r   r   s       r=   r   zDetect._get_decode_boxes   s    '
1#< 	4:..)p)p\RST[R\^b^iknEoEo)p)p)p&DL$,DJ!!$((1W:"6"68N8Nq8Q8QRRUYUaar?   c                   t          t          | j        d         | j        d                             D ]i\  }\  }}d|d         j        j        dd<   t          j        d| j        z  d| j        |         z  dz  z            |d         j        j        d| j        <   j| j	        rt          t          | j
        d         | j
        d                             D ]k\  }\  }}d|d         j        j        dd<   t          j        d| j        z  d| j        |         z  dz  z            |d         j        j        d| j        <   jdS dS )	BInitialize Detect() biases, WARNING: requires stride availability.r_   r`          @ru   N     r   	enumerateziprc   biasdatamathlogr,   rM   rZ   rf   )r<   ry   r   bs       r=   	bias_initzDetect.bias_init   sH   "3t}Z'@$-PZB[#\#\]] 	 	IAv1!$AbEJOAAA)-DGsT[^399* *AbEJOIdgI&& < 	&s4<
+CT\R\E]'^'^__  	6Aq%("
"-1XK3Q#7A"==. ."
	$'	**	 	 r?   Tbboxesr   xywhboolc                H    t          |||o| j         o| j         d          S )z'Decode bounding boxes from predictions.r   )r   r~   )r   rZ   xyxy)r<   r   r   r   s       r=   r   zDetect.decode_bboxes   s8    <dl*<49}	
 
 
 	
r?   r   c                   |                     d| j        gd          \  }}|                     || j                  \  }}}|                    d|                    ddd                    }t          j        |||gd          S )a  Post-processes YOLO model predictions.

        Args:
            preds (torch.Tensor): Raw predictions with shape (batch_size, num_anchors, 4 + nc) with last dimension
                format [x1, y1, x2, y2, class_probs].

        Returns:
            (torch.Tensor): Processed predictions with shape (batch_size, min(max_det, num_anchors), 6) and last
                dimension format [x1, y1, x2, y2, max_class_prob, class_index].
        r1   ru   r}   r   r~   index)splitr,   get_topk_indexmax_detgatherrepeatrK   r   )r<   r   r   r   confidxs         r=   r   zDetect.postprocess   s     QLb99v //EEc#**Q1*=*=>>y%.B7777r?   r   r   /tuple[torch.Tensor, torch.Tensor, torch.Tensor]c                   |j         \  }}}| j        r|nt          ||          }| j        rO|                    dd          \  }}|                    |d          \  }}|                    d|          }|||fS |                    d          d                             |          d                             d          }	|                    d|	                    dd|                    }|	                    d                              |          \  }}
|	t          j        |          d         |
|z  f         }|d         |
|z  d                                         |fS )	aN  Get top-k indices from scores.

        Args:
            scores (torch.Tensor): Scores tensor with shape (batch_size, num_anchors, num_classes).
            max_det (int): Maximum detections per image.

        Returns:
            (torch.Tensor, torch.Tensor, torch.Tensor): Top scores, class indices, and filtered indices.
        ru   T)r~   keepdimr   r}   r   r   ).N)r   r   rO   agnostic_nmsrN   topkr   r   r   flattenrK   arangefloat)r<   r   r   
batch_sizer   r,   klabelsindices	ori_indexr   r   s               r=   r   zDetect.get_topk_index   sW    #),
GR {=GGGW(=(= 	+#ZZBZ==NFF$kk!k33OFG]]1g..F67**JJ2J&&q)..q11!4>>rBB	1I,<,<Q2,F,FGGq))..q11Z00;Ub[HIi 52:y"9"?"?"A"A3FFr?   Nonec                "    dx| _         | _        dS z4Remove the one2many head for inference optimization.NrQ   rS   rb   s    r=   fusezDetect.fuse       ""4888r?   )r)   r*   Fr+   r,   r-   r.   r/   NN)r:   rm   r_   rn   r`   rn   ro   rp   )r:   rm   ro   r   r:   rp   ro   r   T)r   r   r   r   r   r   ro   r   r   r   ro   r   )r   r   r   r-   ro   r   ro   r   ) __name__
__module____qualname____doc__r   r   formatr   r   r   rK   emptyr   r   rR   r   rG   propertyrc   rf   rZ   setterr   r   r   r   r   r   r   r   r   __classcell__r[   s   @r=   r    r       s       & &P GFFGLEek!nnGek!nnGFD#7 #7 #7 #7 #7 #7 #7J : : X: J J XJ L L XL ^  ^
 dh	9 	9 	9 	9 	90 0 0 0 ; ; ; ;     
 
 
 
 
8 8 8 8 G G G G2# # # # # # # #r?   r    c                       e Zd ZdZd"d# fdZed             Zed             Zd$ fdZd% fdZ	d& fdZ
d'dZd(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)          r*   Fr+   r,   r-   nmnprr.   r/   c                    t                                          ||||           | _        | _        t	          |d          j         j                   _        t          |d         dz   j                  t          j         fd|D                        _	        |r t          j         j	                   _        dS dS )  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.
            reg_max (int): Maximum number of DFL channels.
            end2end (bool): Whether to use end-to-end NMS-free detection.
            ch (tuple): Tuple of channel sizes from backbone feature maps.
        r   r1   c           
   3     K   | ]Q}t          j        t          |d           t          d           t          j        j        d                    V  RdS rA   r5   r6   r   r7   r   r9   r:   c4r<   s     r=   r>   z#Segment.__init__.<locals>.<genexpr>$  \       w woptAr1~~tBAPRPYZ\^b^eghPiPi!j!j w w w w w wr?   N)rF   rG   r   r   r   protorN   r5   rP   cv4rV   rW   one2one_cv4)	r<   r,   r   r   r8   rZ   r.   r   r[   s	   `      @r=   rG   zSegment.__init__  s     	Wgr2222a5$(DG44
A!TW%%= w w w w wtv w w www 	7#}TX66D	7 	7r?   c                D    t          | j        | j        | j                  S )IReturns the one-to-many head components, here for backward compatibility.r_   r`   	mask_headra   rQ   rS   r   rb   s    r=   rc   zSegment.one2many(       TXDHMMMMr?   c                D    t          | j        | j        | j                  S )re   r   ra   rX   rY   r   rb   s    r=   rf   zSegment.one2one-  #     T-8HTXTdeeeer?   r:   rm   ro   4tuple | list[torch.Tensor] | dict[str, torch.Tensor]c                   t                                          |          }t          |t                    r|d         n|}|                     |d                   }t          |t
                    r5| j        r)||d         d<   |                                |d         d<   n||d<   | j        r|S | j	        r||fn|d         |f|fS gReturn model outputs and mask coefficients if training, otherwise return outputs and mask coefficients.r   r   rc   r   rf   
rF   r   
isinstancer/   r   ra   rZ   r   r   r   r<   r:   outputsr   r   r[   s        r=   r   zSegment.forward2      ''//!$$(%88E

g

1Q4  eT"" 	'| '-2j!'*,1LLNNi ))!&g= 	L#';Pgaj%5H%4PPr?   rp   r   c                    t                                          |          }t          j        ||d         gd          S z]Decode predicted bounding boxes and class probabilities, concatenated with mask coefficients.mask_coefficientr   r}   rF   r   rK   r   r<   r:   r   r[   s      r=   r   zSegment._inferenceA  :    ""1%%y%#5!67Q????r?   r_   rn   r`   r   c                     t                                          ||          }Ld         j        d         t          j         fdt           j                  D             d          |d<   |S )^Concatenates and returns predicted bounding boxes, class probabilities, and mask coefficients.Nr   c                r    g | ]3} |         |                                        j        d           4S r   rw   r   r9   ry   rz   r   r<   r:   s     r=   r{   z(Segment.forward_head.<locals>.<listcomp>M  A    2t2t2t`a<9Q<!3E3E3J3J2twXZ3[3[2t2t2tr?   r   r  rF   r   r   rK   r   r   rI   )r<   r:   r_   r`   r   r   rz   r[   s   ``  ` @r=   r   zSegment.forward_headF  s     $$Q(;; 1AB(-	2t2t2t2t2t2t2tejkokreses2t2t2tvw(x(xE$%r?   r   c                ~   |                     d| j        | j        gd          \  }}}|                     || j                  \  }}}|                    d|                    ddd                    }|                    d|                    dd| j                            }t          j        ||||gd          S a  Post-process YOLO model predictions.

        Args:
            preds (torch.Tensor): Raw predictions with shape (batch_size, num_anchors, 4 + nc + nm) with last dimension
                format [x1, y1, x2, y2, class_probs, mask_coefficient].

        Returns:
            (torch.Tensor): Processed predictions with shape (batch_size, min(max_det, num_anchors), 6 + nm) and last
                dimension format [x1, y1, x2, y2, max_class_prob, class_index, mask_coefficient].
        r1   ru   r}   r   r   	r   r,   r   r   r   r   r   rK   r   r<   r   r   r   r  r   r   s          r=   r   zSegment.postprocessP       +0++q$'476KQS+*T*T'v' //EEc#**Q1*=*=>>+22q

1aQUQX@Y@Y2ZZy%/?@bIIIIr?   r   c                0    dx| _         x| _        | _        dS r   rQ   rS   r   rb   s    r=   r   zSegment.fusea      )---48dhhhr?   r)   r   r   r*   Fr+   r,   r-   r   r-   r   r-   r.   r/   r:   rm   ro   r  r   )
r:   rm   r_   rn   r`   rn   r   rn   ro   rp   r   r   )r   r   r   r   rG   r   rc   rf   r   r   r   r   r   r   r   s   @r=   r#   r#      s        (7 7 7 7 7 7 7* N N XN f f XfQ Q Q Q Q Q@ @ @ @ @ @
     J J J J". . . . . . . .r?   r#   c                  :     e Zd ZdZdd fdZddZd fdZ xZS )	Segment26a  YOLO26 Segment head for segmentation models.

    This class extends the Segment head with Proto26 for mask prediction in instance segmentation tasks.

    Attributes:
        nm (int): Number of masks.
        npr (int): Number of protos.
        proto (Proto26): 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 = Segment26(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)   r   r   r*   Fr+   r,   r-   r   r   r.   r/   c                    t                                          ||||||           t          || j        | j        |          | _        dS )r   N)rF   rG   r   r   r   r   )r<   r,   r   r   r8   rZ   r.   r[   s          r=   rG   zSegment26.__init__{  sD     	Rgw;;;R47B77


r?   r:   rm   ro   r  c                   t                               | |          }t          |t                    r|d         n|}|                     |          }t          |t
                    rc| j        rW||d         d<   t          |t                    rt          d |D                       n|                                |d         d<   n||d<   | j        r|S | j	        r||fn|d         |f|fS )r  r   rc   r   c              3  >   K   | ]}|                                 V  d S Nr   )r9   ps     r=   r>   z$Segment26.forward.<locals>.<genexpr>  s*      44!((**444444r?   rf   r   )
r    r   r  r/   r   ra   rZ   r   r   r   r<   r:   r  r   r   s        r=   r   zSegment26.forward  s    ..q))(%88E

g

1eT"" 	'| '-2j!'*8B5%8P8PdE44e444444V[VbVbVdVd i )) "'g= 	L#';Pgaj%5H%4PPr?   r   c                    t                                                       t          | j        d          r| j                                         dS dS )zSRemove the one2many head and extra part of proto module for inference optimization.r   N)rF   r   rj   r   r<   r[   s    r=   r   zSegment26.fuse  sJ    4:v&& 	JOO	 	r?   r  r   r!  r   )r   r   r   r   rG   r   r   r   r   s   @r=   r#  r#  f  s         (8 8 8 8 8 8 8Q Q Q Q"         r?   r#  c                       e Zd ZdZd!d" fdZed             Zed             Zd# fdZd$ fdZ	d%dZ
d&dZd'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)   r   r*   Fr+   r,   r-   ner.   r/   c                .    t                                          ||||           | _        t          |d         dz   j                  t	          j         fd|D                        _        |r t          j         j                   _	        dS dS )a  Initialize OBB with number of classes `nc` and layer channels `ch`.

        Args:
            nc (int): Number of classes.
            ne (int): Number of extra parameters.
            reg_max (int): Maximum number of DFL channels.
            end2end (bool): Whether to use end-to-end NMS-free detection.
            ch (tuple): Tuple of channel sizes from backbone feature maps.
        r   r1   c           
   3     K   | ]Q}t          j        t          |d           t          d           t          j        j        d                    V  RdS rA   )r5   r6   r   r7   r-  r   s     r=   r>   zOBB.__init__.<locals>.<genexpr>  r   r?   N)
rF   rG   r-  rN   r5   rP   r   rV   rW   r   )r<   r,   r-  r8   rZ   r.   r   r[   s   `     @r=   rG   zOBB.__init__  s     	Wgr222A!TW%%= w w w w wtv w w www 	7#}TX66D	7 	7r?   c                D    t          | j        | j        | j                  S )r   r_   r`   
angle_headr   rb   s    r=   rc   zOBB.one2many  s     TXTXNNNNr?   c                D    t          | j        | j        | j                  S )re   r1  r   rb   s    r=   rf   zOBB.one2one  s#     T-8HUYUeffffr?   r:   rp   ro   r   c                    |d         | _         t                                          |          }t          j        ||d         gd          S )z[Decode predicted bounding boxes and class probabilities, concatenated with rotation angles.angler   r}   )r5  rF   r   rK   r   r  s      r=   r   zOBB._inference  sE     wZ
""1%%y%7,!4444r?   rm   r_   rn   r`   r2  c                >    t                                          ||          }rd         j        d         t          j         fdt           j                  D             d          }|                                dz
  t          j	        z  }||d<   |S )zSConcatenates and returns predicted bounding boxes, class probabilities, and angles.Nr   c                r    g | ]3} |         |                                        j        d           4S r   rw   r-  r9   ry   r2  rz   r<   r:   s     r=   r{   z$OBB.forward_head.<locals>.<listcomp>  ?    SSSqAqt$$))"dgr::SSSr?   r   g      ?r5  )
rF   r   r   rK   r   r   rI   r   r   pi)	r<   r:   r_   r`   r2  r   r5  rz   r[   s	   ``  `  @r=   r   zOBB.forward_head  s     $$Q(;;!1ABISSSSSSSE$'NNSSSUV E ]]__t+tw6E"E'Nr?   r   r   c                2    t          || j        |d          S )zDecode rotated bounding boxes.r   r}   )r   r5  )r<   r   r   s      r=   r   zOBB.decode_bboxes  s    W!<<<<r?   r   c                ~   |                     d| j        | j        gd          \  }}}|                     || j                  \  }}}|                    d|                    ddd                    }|                    d|                    dd| j                            }t          j        ||||gd          S )a  Post-process YOLO model predictions.

        Args:
            preds (torch.Tensor): Raw predictions with shape (batch_size, num_anchors, 4 + nc + ne) with last dimension
                format [x, y, w, h, class_probs, angle].

        Returns:
            (torch.Tensor): Processed predictions with shape (batch_size, min(max_det, num_anchors), 7) and last
                dimension format [x, y, w, h, max_class_prob, class_index, angle].
        r1   ru   r}   r   r   )	r   r,   r-  r   r   r   r   rK   r   )r<   r   r   r   r5  r   r   s          r=   r   zOBB.postprocess  s      %{{Atw+@b{IIvu //EEc#**Q1*=*=>>#**Q47*C*CDDy%u52>>>>r?   r   c                0    dx| _         x| _        | _        dS r   r  rb   s    r=   r   zOBB.fuse  r  r?   )r)   r   r*   Fr+   )r,   r-   r-  r-   r.   r/   r   
r:   rm   r_   rn   r`   rn   r2  rn   ro   rp   )r   r   r   r   ro   r   r   r   )r   r   r   r   rG   r   rc   rf   r   r   r   r   r   r   r   s   @r=   r   r     s         (7 7 7 7 7 7 7$ O O XO g g Xg5 5 5 5 5 5     = = = =? ? ? ?". . . . . . . .r?   r   c                      e Zd ZdZdd
ZdS )OBB26a"  YOLO26 OBB detection head for detection with rotation models. This class extends the OBB head with modified angle
    processing that outputs raw angle predictions without sigmoid transformation, compared to the original
    OBB class.

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

    Methods:
        forward_head: Concatenate and return predicted bounding boxes, class probabilities, and raw angles.

    Examples:
        Create an OBB26 detection head
        >>> obb26 = OBB26(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 = obb26(x)
    r:   rm   r_   rn   r`   r2  ro   rp   c                     t                                ||          }Nd         j        d         t          j         fdt           j                  D             d          }||d<   |S )zWConcatenates and returns predicted bounding boxes, class probabilities, and raw angles.Nr   c                r    g | ]3} |         |                                        j        d           4S r   r8  r9  s     r=   r{   z&OBB26.forward_head.<locals>.<listcomp>  r:  r?   r   r5  )r    r   r   rK   r   r   rI   )r<   r:   r_   r`   r2  r   r5  rz   s   ``  `  @r=   r   zOBB26.forward_head  s     ##D!Xx@@!1ABISSSSSSSE$'NNSSSUV E #E'Nr?   Nr?  )r   r   r   r   r   r+   r?   r=   rA  rA    s2         &     r?   rA  c                       e Zd ZdZd d! fdZed             Zed             Zd" fdZd# fdZ	d$dZ
d%dZd&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)      r4   r*   Fr+   r,   r-   	kpt_shaper/   r.   c                Z    t                                          ||||           | _        |d         |d         z   _        t	          |d         dz   j                  t          j         fd|D                        _        |r t          j	         j                   _
        dS dS )  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).
            reg_max (int): Maximum number of DFL channels.
            end2end (bool): Whether to use end-to-end NMS-free detection.
            ch (tuple): Tuple of channel sizes from backbone feature maps.
        r   r   r1   c           
   3     K   | ]Q}t          j        t          |d           t          d           t          j        j        d                    V  RdS rA   )r5   r6   r   r7   nkr   s     r=   r>   z Pose.__init__.<locals>.<genexpr>G  r   r?   N)rF   rG   rG  rK  rN   r5   rP   r   rV   rW   r   r<   r,   rG  r8   rZ   r.   r   r[   s   `     @r=   rG   zPose.__init__8  s     	Wgr222"A,1-A!TW%%= w w w w wtv w w www 	7#}TX66D	7 	7r?   c                D    t          | j        | j        | j                  S )r   r_   r`   	pose_headr   rb   s    r=   rc   zPose.one2manyK  r   r?   c                D    t          | j        | j        | j                  S )re   rN  r   rb   s    r=   rf   zPose.one2oneP  r   r?   r:   rp   ro   r   c                    t                                          |          }t          j        ||                     |d                   gd          S )zUDecode predicted bounding boxes and class probabilities, concatenated with keypoints.kptsr   r}   )rF   r   rK   r   kpts_decoder  s      r=   r   zPose._inferenceU  sF    ""1%%y%!1!1!F)!<!<=1EEEEr?   rm   r_   rn   r`   rO  c                     t                                          ||          }Ld         j        d         t          j         fdt           j                  D             d          |d<   |S )VConcatenates and returns predicted bounding boxes, class probabilities, and keypoints.Nr   c                r    g | ]3} |         |                                        j        d           4S r   rw   rK  )r9   ry   rz   rO  r<   r:   s     r=   r{   z%Pose.forward_head.<locals>.<listcomp>a  s@    &h&h&hTU|y|AaD'9'9'>'>r47B'O'O&h&h&hr?   r   rR  r  )r<   r:   r_   r`   rO  r   rz   r[   s   ``  ` @r=   r   zPose.forward_headZ  s     $$Q(;; 1AB!I&h&h&h&h&h&h&hY^_c_fYgYg&h&h&hjkllE&Mr?   r   c                ~   |                     d| j        | j        gd          \  }}}|                     || j                  \  }}}|                    d|                    ddd                    }|                    d|                    dd| j                            }t          j        ||||gd          S )a  Post-process YOLO model predictions.

        Args:
            preds (torch.Tensor): Raw predictions with shape (batch_size, num_anchors, 4 + nc + nk) with last dimension
                format [x1, y1, x2, y2, class_probs, keypoints].

        Returns:
            (torch.Tensor): Processed predictions with shape (batch_size, min(max_det, num_anchors), 6 + self.nk) and
                last dimension format [x1, y1, x2, y2, max_class_prob, class_index, keypoints].
        r1   ru   r}   r   r   )	r   r,   rK  r   r   r   r   rK   r   )r<   r   r   r   rR  r   r   s          r=   r   zPose.postprocessd  s     $kk1dgtw*?RkHHvt //EEc#**Q1*=*=>>{{q

1a(A(A{BBy%t4"====r?   r   c                0    dx| _         x| _        | _        dS r   r  rb   s    r=   r   z	Pose.fuseu  r  r?   rR  c                $   | j         d         }|j        d         }| j        r |j        |g| j         dR  }|ddddddf         dz  | j        dz
  z   | j        z  }|dk    r8t          j        ||ddddddf                                         fd          }|                    || j	        d          S |
                                }|dk    rTt          r"|dddd|f                                          n+|dddd|f                                         |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 )	"Decode keypoints from predictions.r   r   ru   Nr   r   r   r4   rG  r   r   rw   r   r   rK   r   r   rK  cloner   sigmoid_r<   rR  ndimrz   r   r   s         r=   rS  zPose.kpts_decodey  s   ~a Z]; 		"2t~2r222A111aaa!8s"dlS&89T\IAqyyIq!AAAqqq!A#I,"6"6"8"891==66"dgr***

Aqyy <aaaDjM**,,,,$%aaaDjM$9$9$;$;AaaaDjMqqq!'T'z]S0DLOc4IJdlZAaaaDjMqqq!'T'z]S0DLOc4IJdlZAaaaDjMHr?   r)   rE  r*   Fr+   r,   r-   rG  r/   r.   r/   r   )
r:   rm   r_   rn   r`   rn   rO  rn   ro   rp   r   r   rR  r   ro   r   )r   r   r   r   rG   r   rc   rf   r   r   r   r   rS  r   r   s   @r=   r!   r!   #  s        (7 7 7 7 7 7 7& N N XN f f XfF F F F F F
     > > > >". . . .       r?   r!   c                  n     e Zd ZdZdd  fdZed             Zed             Zd!dZd" fdZ	d#dZ
 xZS )$Pose26a!  YOLO26 Pose head for keypoints models.

    This class extends the Pose head with normalizing flow for keypoint prediction in 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 = Pose26(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)   rE  r*   Fr+   r,   r-   rG  r/   r.   c                    t                                          |||||           t                       _        t	          |d         dz  |d         |d         dz   z            t          j        fd|D                        _        t          j         fd|D                        _        |d         dz   _	        t          j         fd|D                        _
        |r\t          j         j                   _        t          j         j                   _        t          j         j
                   _        dS dS )	rI  r   r1   r   r   c           	   3  ~   K   | ]7}t          j        t          |d           t          d                     V  8dS )r4   N)r5   r6   r   )r9   r:   r   s     r=   r>   z"Pose26.__init__.<locals>.<genexpr>  sD       \ \TUtAr1~~tBA!O!O \ \ \ \ \ \r?   c              3  N   K   | ]}t          j        j        d           V   dS r   N)r5   r7   rK  r9   _r   r<   s     r=   r>   z"Pose26.__init__.<locals>.<genexpr>  s3      %L%LAbiDGQ&?&?%L%L%L%L%L%Lr?   c              3  N   K   | ]}t          j        j        d           V   dS ri  )r5   r7   nk_sigmarj  s     r=   r>   z"Pose26.__init__.<locals>.<genexpr>  s3      &S&S1ryT]A'F'F&S&S&S&S&S&Sr?   N)rF   rG   r   
flow_modelrN   r5   rP   r   cv4_kptsrm  	cv4_sigmarV   rW   r   one2one_cv4_kptsone2one_cv4_sigmarL  s   `     @r=   rG   zPose26.__init__  s<    	Y"===!))A!Yq\Yq\A-=>??= \ \ \ \Y[ \ \ \\\%L%L%L%L%L%L%L%LLL!!q(&S&S&S&S&SPR&S&S&SSS 	C#}TX66D$(M$-$@$@D!%)]4>%B%BD"""	C 	Cr?   c                \    t          | j        | j        | j        | j        | j                  S )r   r_   r`   rO  	kpts_headkpts_sigma_head)ra   rQ   rS   r   ro  rp  rb   s    r=   rc   zPose26.one2many  s4     XXhm N
 
 
 	
r?   c                \    t          | j        | j        | j        | j        | j                  S )re   rt  )ra   rX   rY   r   rq  rr  rb   s    r=   rf   zPose26.one2one  s9     %%&+ 2
 
 
 	
r?   r:   rm   r_   rn   r`   rO  ru  rv  ro   rp   c                   	 t                                ||          }d         j        d         fdt           j                  D             	t          j        	 fdt           j                  D             d          |d<    j        r9t          j        	 fdt           j                  D             d          |d<   |S )	rU  Nr   c                >    g | ]} |         |                   S r+   r+   )r9   ry   rO  r:   s     r=   r{   z'Pose26.forward_head.<locals>.<listcomp>  s+    CCCq	!QqT**CCCr?   c                r    g | ]3} |         |                                        j        d           4S r   rW  )r9   ry   rz   featuresru  r<   s     r=   r{   z'Pose26.forward_head.<locals>.<listcomp>  sA    &o&o&o[\|y|HQK'@'@'E'Eb$'SU'V'V&o&o&or?   r   rR  c                r    g | ]3} |         |                                        j        d           4S r   )rw   rm  )r9   ry   rz   r{  rv  r<   s     r=   r{   z'Pose26.forward_head.<locals>.<listcomp>  sB    iiiUV'_Q'4499"dmRPPiiir?   
kpts_sigma)r    r   r   r   rI   rK   r   r   )
r<   r:   r_   r`   rO  ru  rv  r   rz   r{  s
   ``  ``` @@r=   r   zPose26.forward_head  s     ##D!Xx@@ 1ABCCCCCE$'NNCCCH!I&o&o&o&o&o&o&o`efjfm`n`n&o&o&oqrssE&M} &+iiiiiiiiZ_`d`gZhZhiiikl' 'l# r?   r   c                    t                                                       dx| _        x| _        x| _        | _        dS r   )rF   r   ro  rp  rn  rr  r+  s    r=   r   zPose26.fuse  s7    TXXXX4;Q;Q;Qr?   rR  r   c                    | j         d         }|j        d         }| j        r |j        |g| j         dR  }|ddddddf         | j        z   | j        z  }|dk    r8t          j        ||ddddddf                                         fd          }|                    || j	        d          S |
                                }|dk    rTt          r"|dddd|f                                          n+|dddd|f                                         |dddd|f<   |dddd|f         | j        d         z   | j        z  |dddd|f<   |dddd|f         | j        d         z   | j        z  |dddd|f<   |S )r[  r   r   ru   Nr   r4   r\  r_  s         r=   rS  zPose26.kpts_decode  s   ~a Z]; 		"2t~2r222A111aaa!8t|+t|;AqyyIq!AAAqqq!A#I,"6"6"8"891==66"dgr***

Aqyy <aaaDjM**,,,,$%aaaDjM$9$9$;$;AaaaDjMqqq!'T'z]T\!_<LAaaaDjMqqq!'T'z]T\!_<LAaaaDjMHr?   ra  rb  )r:   rm   r_   rn   r`   rn   rO  rn   ru  rn   rv  rn   ro   rp   r   rc  )r   r   r   r   rG   r   rc   rf   r   r   rS  r   r   s   @r=   re  re    s         (C C C C C C C2 
 
 X
 
 
 X
   *Y Y Y Y Y Y
       r?   re  c                  2     e Zd ZdZdZdd fdZd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 on input feature maps.

    Examples:
        Create a classification head
        >>> classify = Classify(c1=1024, c2=1000)
        >>> x = torch.randn(1, 1024, 20, 20)
        >>> output = classify(x)
    Fr   Nc1r-   r;   r   sr(  
int | Nonegc                   t                                                       d}t          ||||||          | _        t	          j        d          | _        t	          j        dd          | _        t	          j	        ||          | _
        dS )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): Kernel size.
            s (int): Stride.
            p (int, optional): Padding.
            g (int): Groups.
        i   r           T)r(  inplaceN)rF   rG   r   convr5   AdaptiveAvgPool2dpoolDropoutdropLinearlinear)	r<   r  r;   r   r  r(  r  c_r[   s	           r=   rG   zClassify.__init__  sx     	RAq!,,	(++	Jd333	iB''r?   r:   !list[torch.Tensor] | torch.Tensorro   torch.Tensor | tuplec           	     n   t          |t                    rt          j        |d          }|                     |                     |                     |                     |                                        d                              }| j	        r|S |
                    d          }| j        r|n||fS )z+Perform forward pass on input feature maps.r   )r  listrK   r   r  r  r  r  r   r   softmaxr   )r<   r:   r   s      r=   r   zClassify.forward.  s    a 	 	!QAKK		$))DIIaLL"9"9"A"A!"D"DEEFF= 	HIIaLLK+qqaV+r?   )r   r   Nr   )r  r-   r;   r-   r   r-   r  r-   r(  r  r  r-   )r:   r  ro   r  )r   r   r   r   r   rG   r   r   r   s   @r=   r   r     sg         * F( ( ( ( ( ( ($, , , , , , , ,r?   r   c                  @     e Zd ZdZ	 	 	 	 	 	 dd fdZd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)      Fr*   r+   r,   r-   embedwith_bnr   r8   rZ   r.   r/   c                B   t                                          ||||           t          |d         t          | j        d                    t          j        fd|D                       | _        t          j        fd|D                       | _        dS )  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.
            reg_max (int): Maximum number of DFL channels.
            end2end (bool): Whether to use end-to-end NMS-free detection.
            ch (tuple): Tuple of channel sizes from backbone feature maps.
        )r8   rZ   r.   r   r2   c           
   3     K   | ]L}t          j        t          |d           t          d           t          j        d                    V  MdS rA   r5   r6   r   r7   r9   r:   rD   r  s     r=   r>   z'WorldDetect.__init__.<locals>.<genexpr>d  sY       u umntAr1~~tBAPRPYZ\^cefPgPg!h!h u u u u u ur?   c              3  V   K   | ]#}rt                    nt                      V  $d S r'  r   r   r9   rk  r  r  s     r=   r>   z'WorldDetect.__init__.<locals>.<genexpr>e  =       h h`aW![!25!9!9!9/J[J[ h h h h h hr?   N)	rF   rG   rN   rO   r,   r5   rP   rS   r   	r<   r,   r  r  r8   rZ   r.   rD   r[   s	     ``   @r=   rG   zWorldDetect.__init__O  s    & 	Wg"EEEADGS))**= u u u u urt u u uuu= h h h h heg h h hhhr?   r:   rm   textr   ro   dict[str, torch.Tensor] | tuplec           
     t   
 d |D             }t           j                  D ]e}t          j          j        |         ||                     j        |           j        |         ||                   |          fd          ||<   f j         j        dz  z    _	        |d         j
        d         
t          j        
 fd|D             d          }|                     j        dz   j        fd          \  }}t          |||          } j        r|S                      |          }	 j        r|	n|	|fS )zHConcatenate and return predicted bounding boxes and class probabilities.c                6    g | ]}|                                 S r+   )r]  r   s     r=   r{   z'WorldDetect.forward.<locals>.<listcomp>i  s     ((((((r?   r   r1   r   c                H    g | ]}|                     j        d           S r   )rw   rJ   )r9   r   rz   r<   s     r=   r{   z'WorldDetect.forward.<locals>.<listcomp>n  s+    @@@2772tw33@@@r?   r   r   )r   rI   rK   r   rQ   r   rS   r,   r8   rJ   r   r   ra   r   r   r   )r<   r:   r  r   ry   x_catr   r   r   r   rz   s   `         @r=   r   zWorldDetect.forwardg  sC   ((a(((tw 	[ 	[A9kdhqk!A$//![TXa[1=N=NPT1U1UVXYZZAaDD'DL1,,qTZ]	@@@@@a@@@!DDT\A%5tw$?CCv5u==== 	LOOE""K/qqaZ/r?   c                    | }t          |j        |j        |j                  D ]\  }}}d|d         j        j        dd<   dS )r         ?ru   N)r   rQ   rS   rM   r   r   )r<   mr   r   r  s        r=   r   zWorldDetect.bias_initv  sS     15!%22 	% 	%GAq!!$AbEJOAAA	% 	%r?   r)   r  Fr*   Fr+   )r,   r-   r  r-   r  r   r8   r-   rZ   r   r.   r/   )r:   rm   r  r   ro   r  )r   r   r   r   rG   r   r   r   r   s   @r=   r  r  9  s         . i i i i i i i00 0 0 0% % % % % % %r?   r  c                  F     e Zd ZdZdd fd	Zedd            ZddZ xZS )LRPCHeadaX  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)
    Tvocab	nn.Modulepflocenabledr   c                    t                                                       |r|                     |          n|| _        || _        || _        || _        dS )aW  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)rF   rG   conv2linearr  r  r  r  )r<   r  r  r  r  r[   s        r=   rG   zLRPCHead.__init__  sS     	07BT%%e,,,U
r?   r  	nn.Conv2dro   	nn.Linearc                   t          | t          j                  r| j        dk    sJ t          j        | j        | j                  }| j                            | j        d          j	        |j        _	        | j
        j	        |j
        _	        |S )z4Convert a 1x1 convolutional layer to a linear layer.)r   r   ru   )r  r5   r7   kernel_sizer  in_channelsout_channelsweightrw   r   r   )r  r  s     r=   r  zLRPCHead.conv2linear  su     $	**It/?6/I/I/II4+T->??![--d.?DDI9>r?   cls_featr   loc_featr   r   tuple[tuple, torch.Tensor]c                   | j         r|                     |          d                             d          }|                                |k    }|                    d                              dd          }|                     |r|dd|f         n)||                    d                                          z            }|                     |          |                    dd          |fS |                     |          }|                     |          }||                    d          t          j
        |j        d         |j        d         z  |j        t          j                  fS )	zQProcess classification and localization features to generate detection proposals.)r   r   r   r   ru   Nr4   )devicedtype)r  r  r   r   r   r  r   r-   r  rK   onesr   r  r   )r<   r  r  r   pf_scoremasks         r=   r   zLRPCHead.forward  sE   < 	wwx((.66q99H##%%,D''**44R<<Hzzt"d(111d7"3"3DNN[]L^L^LbLbLdLdAdeeH88H%%x'9'9"b'A'A4GGzz(++Hxx))H  ##
8>!,x~a/@@`e`jkkk r?   r   )r  r  r  r  r  r  r  r   )r  r  ro   r  )r  r   r  r   r   r   ro   r  )	r   r   r   r   rG   staticmethodr  r   r   r   s   @r=   r  r    s         .          \       r?   r  c                       e Zd ZdZdZ	 d(d) fdZ e            d*d+d            Zd,dZd-dZ	d.dZ
d/ fd!Zd/d"Z fd#Zed$             Zed%             Zd& Zd' Z xZS )0r$   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+   r,   r-   r  r  r   r.   r/   c                   t                                          ||||           t          |d         t          | j        d                    k    sJ sJ | j        r!t          j        fd|D                       n t          j        fd|D                       | _        t          j        fd|D                       | _	        |r<t          j        | j                  | _        t          j        | j	                  | _        t          t                              | _        t#          |          | _        | _        dS )r  r   r2   c           
   3     K   | ]L}t          j        t          |d           t          d           t          j        d                    V  MdS rA   r  r  s     r=   r>   z'YOLOEDetect.__init__.<locals>.<genexpr>  sW      nnfg"-QARQSUW\^_I`I`aannnnnnr?   c              3  0  K   | ]}t          j        t          j        t          ||d           t          |d                    t          j        t          d           t          d                    t          j        d                    V  dS rA   )r5   r6   r   r   r7   r  s     r=   r>   z'YOLOEDetect.__init__.<locals>.<genexpr>  s          M&Aq//42q>>BBM&R"3"3T"b!__EEIb%++      r?   c              3  V   K   | ]#}rt                    nt                      V  $d S r'  r  r  s     r=   r>   z'YOLOEDetect.__init__.<locals>.<genexpr>  r  r?   N)rF   rG   rN   rO   r,   rR   r5   rP   rS   r   rV   rW   rY   r   r   r   reprtar   savper  r  s	     ``   @r=   rG   zYOLOEDetect.__init__  se    	Wgr222ADGS))**U{{{{w {	BMnnnnnkmnnnnnn           	 = h h h h heg h h hhh 	7#}TX66D#}TX66Dy66772r5))



r?   N	txt_featsr   c                   |dx| _         x| _        | _        dS | j        rdS | j        rJ |                    t          j                                      d          }| 	                    || j        | j                   | j
        r!| 	                    || j        | j                   | `t          j                    | _        d| _        dS )>Fuse text features with model weights for efficient inference.Nr   T)rQ   rS   r   is_fusedr   torK   float32squeeze_fuse_tprZ   rY   r   r  r5   rT   )r<   r  s     r=   r   zYOLOEDetect.fuse  s     -11DH1tx$(F= 	F=   LL//77::	i48444< 	IMM)T%5t7GHHHKkmmr?   r`   rn   bn_headro   r   c                :   t          ||          D ]\  }}t          |t          j                  sJ t          |t                    sJ |d         }t          |t          j                  sJ |j        }|j        }|j        }	||	                                z  }
t          ||	          }|j        j                            d                              d          }|j        j        }|
|z  }|
|                    d                              d          z                      d          }t!          j        |          |z  }t          j        |j        |j        d         d                              d                              |j        j                  }|j        j                            |                    d                              d                     |j        j                            ||z              ||d<   |                                 
dS )zGFuse text prompt embeddings with model weights for efficient inference.ru   r   r   )r  FN)r   r  r5   r6   r   r7   logit_scaler   normexpr   r  r   r  reshaper   rK   	ones_liker  r   requires_grad_r  r  copy_r   )r<   r  r`   r  cls_hbn_hr  r  r   r  twr   b1b2s                  r=   r  zYOLOEDetect._fuse_tp  s   x11 !	 !	KE4eR]33333d$5666669DdBI.....*K9D9DKOO---A.tT::D ((,,44R88A	AAAaiimm--b111::2>>B$$t+B 	$GAJ !  
  &&DK&''  K""1;;r??#<#<R#@#@AAAIN  b)))E"IIIKKKKC!	 !	r?   tpetorch.Tensor | Nonec                ^    |dn)t          j        |                     |          dd          S )z.Get text prompt embeddings with normalization.Nru   r   )r~   r(  )F	normalizer  )r<   r  s     r=   get_tpezYOLOEDetect.get_tpe?  s.    {ttDKK4D4D"PQ(R(R(RRr?   r:   rm   vpec                    |j         d         dk    r9t          j        |d         j         d         d| j        |d         j                  S |j        dk    r|                     ||          }|j        dk    sJ |S )z4Get visual prompt embeddings with spatial awareness.r   r   )r  r1   r4   )r   rK   rL   r  r  r`  r  )r<   r:   r  s      r=   get_vpezYOLOEDetect.get_vpeC  sp    9Q<1;qtz!}aAaDKPPPP8q==**Q$$Cx1}}}}
r?   r  c                    t          | d          r|                     |dd                   S t                                          |          S )zEProcess features with class prompt embeddings to generate detections.lrpcNr4   )rj   forward_lrpcrF   r   )r<   r:   r[   s     r=   r   zYOLOEDetect.forwardL  sG    4   	,$$QrrU+++wwq!!!r?   c           
        g g g }}}|d         j         d         }| j        s| j        n| j        }| j        s| j        n| j        }t          | j                  D ]} ||         ||                   }	 ||         ||                   }
t          | j	        |         t                    sJ  | j	        |         |	|
| j        r	| j        sdnt          | dd                    \  }}}|                    |                    || j        dz  d                     |                    |           |                    |           t#          t%          j        |d          t%          j        |d          |t%          j        |                    }|                     |          }| j        r*|                     |                    ddd                    }| j        r|n||fS )	YProcess features with fused text embeddings to generate detections for prompt-free model.r   r   MbP?r1   ru   r   )r   r   r   r   r   )r   rZ   rQ   rX   rS   rY   r   rI   r  r  r  r   r   ri   appendrw   r8   ra   rK   r   r   r   r   )r<   r:   r   r   r   rz   rQ   rS   ry   r  r  boxscorer   r   r   s                   r=   r  zYOLOEDetect.forward_lrpcR  s   !2ruvqTZ]"l@dhh0@"l@dhh0@tw 	 	As1vad||Hs1vad||HdilH55555*dil[WW74QV;W;W OC
 LL"dlQ&6;;<<<MM%   LL59UA..uy7K7KST\a\efk\l\lmmmOOE""< 	5  1a!3!344AK/qqaZ/r?   c                    t                                          |          }t          | d          r | j        r	| j        s|n|d|d         f         }|S )z.Decode predicted bounding boxes for inference.r  .r   )rF   r   rj   r   r   )r<   r:   r   r[   s      r=   r   zYOLOEDetect._get_decode_boxesj  sV    ww((++4   	W;Vt|V44c1W:oAVDr?   c                D    t          | j        | j        | j                  S )r]   r_   r`   contrastive_headr   rb   s    r=   rc   zYOLOEDetect.one2manyq  s     TX48TTTTr?   c                D    t          | j        | j        | j                  S )re   r  r   rb   s    r=   rf   zYOLOEDetect.one2onev  s#     T-8H[_[kllllr?   c                $    t                    dk    sJ dt                     d            t                      S d         j        d         t          j         fdt           j                  D             d          }d         j        d	          _        t          j         fd
t           j                  D             d          } j         j        dz  z    _	        t          ||dd                   S )z_Concatenates and returns predicted bounding boxes, class probabilities, and contrastive scores.r1   zLExpected 4 features including 3 feature maps and 1 text embeddings, but got .Nr   c                x    g | ]6} |         |                                        d j        z  d          7S rt   rv   rx   s     r=   r{   z,YOLOEDetect.forward_head.<locals>.<listcomp>  r|   r?   ru   r}   r   c                    g | ]I} |          |         |                   d                                         j        d           JS r   )r  r,   )r9   ry   rz   r`   r  r<   r:   s     r=   r{   z,YOLOEDetect.forward_head.<locals>.<listcomp>  sX    lllXY a !QqT!2!2AbE::BB2twPRSSlllr?   r4   r   )
rH   ra   r   rK   r   r   rI   r,   r8   rJ   )r<   r:   r_   r`   r  r   r   rz   s   `````  @r=   r   zYOLOEDetect.forward_head{  s(   1vv{{{tknopkqkqttt{{{x/66MqTZ]	dddddddUZ[_[bUcUcdddjlmmmB%+a.llllllll]bcgcj]k]klllrt
 
 
 'DL1,,%ae<<<<r?   c                   t          t          | j        d         | j        d         | j        d                             D ]v\  }\  }}}d|d         j        j        dd<   d|d         j        j        dd<   t          j        d| j        z  d	| j        |         z  d
z  z            |j        j        dd<   w| j	        rt          t          | j
        d         | j
        d         | j
        d                             D ]x\  }\  }}}d|d         j        j        dd<   d|d         j        j        dd<   t          j        d| j        z  d	| j        |         z  d
z  z            |j        j        dd<   wdS dS )r   r_   r`   r  r   ru   Nr  r   r   r   r   )r<   ry   r   r   cs        r=   r   zYOLOEDetect.bias_init  s   %j)4=+DdmTfFghh
 
 	Q 	QLAy1a "%AbEJOAAA!$AbEJOAAA!Xa$'kS4;q>5Ia4O&OPPAFKNN< 	U )DL,dl:.FUgHhii! ! U U9Aq! &)"
"%("
"!%!dg+t{1~9MRS8S*S!T!TAAA	U 	UU Ur?   r  )r,   r-   r  r-   r  r   r.   r/   r'  r  r   )r  r   r`   rn   r  rn   ro   r   )r  r  ro   r  )r:   rm   r  r   ro   r   r:   rm   ro   r  )r   r   r   r   r  rG   r   r   r  r  r  r   r  r   r   rc   rf   r   r   r   r   s   @r=   r$   r$     sw        : H mo$ $ $ $ $ $ $L     "# # # #JS S S S   " " " " " "0 0 0 00     U U XU m m Xm= = =U U U U U U Ur?   r$   c                       e Zd ZdZ	 	 	 	 	 	 	 	 d*d+ fdZed             Zed             Zd,dZd- fdZ	d. fdZ
d/ fd$Zd0d&Zd1d2 fd)Z xZS )3r%   aV  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  Fr*   r+   r,   r-   r   r   r  r  r   r.   r/   c	                   	 t                                          ||||||           | _        | _        t	          |d          j         j                   _        t          |d         dz   j                  	t          j        	 fd|D                        _	        |r t          j         j	                   _        dS dS )a7  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.
            reg_max (int): Maximum number of DFL channels.
            end2end (bool): Whether to use end-to-end NMS-free detection.
            ch (tuple): Tuple of channel sizes from backbone feature maps.
        r   r1   c           
   3     K   | ]Q}t          j        t          |d           t          d           t          j        j        d                    V  RdS rA   r   r9   r:   c5r<   s     r=   r>   z(YOLOESegment.__init__.<locals>.<genexpr>  r   r?   N)rF   rG   r   r   r   r   rN   r5   rP   cv5rV   rW   one2one_cv5)r<   r,   r   r   r  r  r8   rZ   r.   r
  r[   s   `        @r=   rG   zYOLOESegment.__init__  s    . 	UGWgrBBB2a5$(DG44
A!TW%%= w w w w wtv w w www 	7#}TX66D	7 	7r?   c                P    t          | j        | j        | j        | j                  S )r]   r_   r`   r   r  )ra   rQ   rS   r  r   rb   s    r=   rc   zYOLOESegment.one2many  s%     TXDH_c_ghhhhr?   c                P    t          | j        | j        | j        | j                  S )re   r  )ra   rX   rY   r  r   rb   s    r=   rf   zYOLOESegment.one2one  s3     %%&!-	
 
 
 	
r?   r:   rm   ro   r  c           
         g g g }}}d         j         d          j        s j        n j        } j        s j        n j        } j        s j        n j        t           j	                  D ]} ||         |                   } ||         |                   }	t           j        |         t                    sJ   j        |         ||	 j        r	 j        sdnt           dd                    \  }
}}|                    |
                     j        dz  d                     |                    |           |                    |           t'          j         fdt           j	                  D             d          }t'          j        |          }t+          t'          j        |d          t'          j        |d          | j        r j        s||                                z  n	|d|f         	          }                     |          } j        r*                     |                    ddd
                    } j        r|n||fS )r  r   r   r  r1   ru   c                r    g | ]3} |         |                                        j        d           4S r   r  )r9   ry   rz   r  r<   r:   s     r=   r{   z-YOLOESegment.forward_lrpc.<locals>.<listcomp>  s=    SSSqAqt))"dgr::SSSr?   r   .)r   r   r   r   r  r   )r   rZ   rQ   rX   rS   rY   r  r  r   rI   r  r  r  r   r   ri   r  rw   r8   rK   r   ra   r-   r   r   r   )r<   r:   r   r   r   rQ   rS   ry   r  r  r  r  r   mcr   r   rz   r  s   ``              @@r=   r  zYOLOESegment.forward_lrpc  sY   !2ruvqTZ]"l@dhh0@"l@dhh0@"l@dhh0@tw 	 	As1vad||Hs1vad||HdilH55555*dil[WW74QV;W;W OC
 LL"dlQ&6;;<<<MM%   LLYSSSSSSSE$'NNSSSUVWW	%  )E1%%9VQ''15eT\eR%))++--WYZ]_dZdWe
 
 
 OOE""< 	5  1a!3!344AK/qqaZ/r?   r  c                   t                                          |          }t          |t                    r|d         n|}|                     |d                   }t          |t
                    r5| j        r)||d         d<   |                                |d         d<   n||d<   | j        r|S | j	        r||fn|d         |f|fS r  r  r  s        r=   r   zYOLOESegment.forward  r	  r?   rp   r   c                    t                                          |          }t          j        ||d         gd          S r  r  r  s      r=   r   zYOLOESegment._inference  r  r?   r_   rn   r`   r   r  c                     t                                          |||          }Ld         j        d         t          j         fdt           j                  D             d          |d<   |S )r  Nr   c                r    g | ]3} |         |                                        j        d           4S r   r  r  s     r=   r{   z-YOLOESegment.forward_head.<locals>.<listcomp>"  r  r?   r   r  r  )	r<   r:   r_   r`   r   r  r   rz   r[   s	   ``  `  @r=   r   zYOLOESegment.forward_head  s     $$Q(<LMM 1AB(-	2t2t2t2t2t2t2tejkokreses2t2t2tvw(x(xE$%r?   r   c                ~   |                     d| j        | j        gd          \  }}}|                     || j                  \  }}}|                    d|                    ddd                    }|                    d|                    dd| j                            }t          j        ||||gd          S r  r  r  s          r=   r   zYOLOESegment.postprocess%  r  r?   Nr  c                    t                                          |           |7d| _        t          | j        d          r| j                                         dS dS )r  Nr   )rF   r   r  rj   r   )r<   r  r[   s     r=   r   zYOLOESegment.fuse6  sY    YDHtz6** "
!!!F	 r?   r)   r   r   r  Fr*   Fr+   r,   r-   r   r-   r   r-   r  r-   r  r   r.   r/   r  r!  r   )r:   rm   r_   rn   r`   rn   r   rn   r  rn   ro   rp   r   r'  r  )r   r   r   r   rG   r   rc   rf   r  r   r   r   r   r   r   r   s   @r=   r%   r%     sV        0 7 7 7 7 7 7 7B i i Xi 
 
 X
0 0 0 0BQ Q Q Q Q Q@ @ @ @ @ @
     J J J J"          r?   r%   c                  4    e Zd ZdZ	 	 	 	 	 	 	 	 dddZddZdS )YOLOESegment26a  YOLOE-style segmentation head module using Proto26 for mask generation.

    This class extends the YOLOESegment functionality to include segmentation capabilities by integrating a Proto26
    generation module and convolutional layers to predict mask coefficients.

    Args:
        nc (int): Number of classes. Defaults to 80.
        nm (int): Number of masks. Defaults to 32.
        npr (int): Number of prototype channels. Defaults to 256.
        embed (int): Embedding dimensionality. Defaults to 512.
        with_bn (bool): Whether to use Batch Normalization. Defaults to False.
        reg_max (int): Maximum number of DFL channels. Defaults to 16.
        end2end (bool): Whether to use end-to-end detection mode. Defaults to False.
        ch (tuple[int, ...]): Input channels for each scale.

    Attributes:
        nm (int): Number of segmentation masks.
        npr (int): Number of prototype channels.
        proto (Proto26): Prototype generation module for segmentation.
        cv5 (nn.ModuleList): Convolutional layers for generating mask coefficients from features.
        one2one_cv5 (nn.ModuleList, optional): Deep copy of cv5 for end-to-end detection branches.
    r)   r   r   r  Fr*   r+   r,   r-   r   r   r  r  r   r.   r/   c	           	     t   	 t                                ||||||           | _        | _        t	          | j         j        |           _        t          |d         dz   j                  	t          j        	 fd|D                        _	        |r t          j         j	                   _        dS dS )zVInitialize YOLOESegment26 with class count, mask parameters, and embedding dimensions.r   r1   c           
   3     K   | ]Q}t          j        t          |d           t          d           t          j        j        d                    V  RdS rA   r   r	  s     r=   r>   z*YOLOESegment26.__init__.<locals>.<genexpr>j  r   r?   N)r$   rG   r   r   r   r   rN   r5   rP   r  rV   rW   r  )
r<   r,   r   r   r  r  r8   rZ   r.   r
  s
   `        @r=   rG   zYOLOESegment26.__init__X  s     	T2ugwLLLR47B77
A!TW%%= w w w w wtv w w www 	7#}TX66D	7 	7r?   r:   rm   ro   r  c                   t                               | |          }t          |t                    r|d         n|}|                     d |D             d          }t          |t
                    rE| j        r9t          | d          s)||d         d<   |                                |d         d<   n||d<   | j	        r|S | j
        r||fn|d	         |f|fS )
r  r   c                6    g | ]}|                                 S r+   r   r   s     r=   r{   z*YOLOESegment26.forward.<locals>.<listcomp>r  s     444BBIIKK444r?   F)return_semsegr  rc   r   rf   r   )r$   r   r  r/   r   ra   rZ   rj   r   r   r   r)  s        r=   r   zYOLOESegment26.forwardn  s    %%dA..(%88E

g

44!444E
JJeT"" 	'| 'GD&$9$9 '-2j!'*,1LLNNi ))!&g= 	L#';Pgaj%5H%4PPr?   Nr  r  r!  )r   r   r   r   rG   r   r+   r?   r=   r  r  @  sk         2 7 7 7 7 7,Q Q Q Q Q Qr?   r  c                       e Zd ZdZdZg Z ej        d          Z ej        d          Z	dZ
dddddd	d
dd ej                    dddddfdE fd%ZdFdGd-Zed.ej        d/d0fdHd:            ZdId<Z	 	 dJdKdCZdD Z xZS )Lr"   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)   )r     i   r   r(   r1         r#  r  ru   r2   r   r  r,   r-   r.   r/   hdnqndpnhndld_ffndropoutr   actr  eval_idxndlabel_noise_ratiobox_noise_scalelearnt_init_queryr   c           	        t                                                       | _        || _        t	          |          | _        | _        || _        || _        t          j
        fd|D                       | _        t          |||	|
| j        |          }t          |||          | _        t          j                  | _        || _        || _        || _        || _        |rt          j        |          | _        t-          ddz  d          | _        t          j        t          j                  t          j                            | _        t          j                  | _        t-          dd          | _        t          j
        fdt=          |          D                       | _        t          j
        fdt=          |          D                       | _         | !                                 dS )	aw  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   | ]A}t          j        t          j        |d d          t          j                            V  BdS )r   F)r   N)r5   r6   r7   BatchNorm2d)r9   r:   r&  s     r=   r>   z)RTDETRDecoder.__init__.<locals>.<genexpr>  sP      'w'wopbi2qu6U6U6UWYWefhWiWi(j(j'w'w'w'w'w'wr?   r1   r   
num_layersr4   c                :    g | ]}t          j                  S r+   )r5   r  )r9   rk  r&  r,   s     r=   r{   z*RTDETRDecoder.__init__.<locals>.<listcomp>  s%    ,S,S,S1RYr2->->,S,S,Sr?   c                6    g | ]}t          d d          S )r1   r4   r6  )r   )r9   rk  r&  s     r=   r{   z*RTDETRDecoder.__init__.<locals>.<listcomp>  s*    +]+]+]QCBa,H,H,H+]+]+]r?   N)"rF   rG   
hidden_dimnheadrH   rI   r,   num_queriesnum_decoder_layersr5   rP   
input_projr   r   decoder	Embeddingdenoising_class_embednum_denoisingr0  r1  r2  	tgt_embedr   query_pos_headr6   r  	LayerNorm
enc_outputenc_score_headenc_bbox_headr   dec_score_headdec_bbox_head_reset_parameters)r<   r,   r.   r&  r'  r(  r)  r*  r+  r,  r-  r.  r/  r0  r1  r2  decoder_layerr[   s    ` `             r=   rG   zRTDETRDecoder.__init__  s   L 	
b''"% -'w'w'w'wtv'w'w'www
 :"b%RUW[W^`cdd3BsHUU &(\"b%9%9"!2. "3 	2\"b11DN!!QVRA>>> -	"b(9(92<;K;KLL iB// Rq999 !m,S,S,S,S,Sc

,S,S,STT]+]+]+]+]RWX[R\R\+]+]+]^^     r?   Nr:   rm   batchdict | Nonero   tuple | torch.Tensorc           
     ,   ddl m} |                     |          \  }} ||| j        | j        | j        j        | j        | j        | j	        | j
                  \  }}}}	|                     ||||          \  }
}}}|                     |
|||| j        | j        | j        |          \  }}|||||	f}| j
        r|S t!          j        |                    d          |                    d                                          fd          }| j        r|n||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_maskru   )ultralytics.models.utils.opsrQ  _get_encoder_inputr,   r<  rA  r  rB  r0  r1  r   _get_decoder_inputr?  rJ  rI  rD  rK   r   r  r   r   )r<   r:   rM  rQ  r   shapesdn_embeddn_bboxrR  dn_metar  
refer_bbox
enc_bboxes
enc_scores
dec_bboxes
dec_scoresr   s                    r=   r   zRTDETRDecoder.forward  sU    	?>>>>> //22v 1>G&-" M	1
 	1
-'9g 594K4KESY[cel4m4m1z:z "& ". 	"
 	"

J 
J
GC= 	HIz))!,,j.@.@.C.C.K.K.M.MNPRSSK+qqaV+r?   g?cpu{Gz?rV  list[list[int]]	grid_sizer  torch.dtyper  streps!tuple[torch.Tensor, torch.Tensor]c                T   g }t          |           D ]\  }\  }}t          j        |||          }	t          j        |||          }
t          rt          j        |	|
d          nt          j        |	|
          \  }}t          j        ||gd          }t          j        ||g||          }|                    d          dz   |z  }t          j        |||          |z  d|z  z  }|	                    t          j
        ||gd                              d||z  d	                     t          j
        |d
          }||k    |d
|z
  k     z                      dd          }t          j        |d
|z
  z            }|                    | t          d                    }||fS )aC  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)indexingru   r  r  r   r   r   r1   r   T)r   inf)r   rK   r   r
   meshgridstacktensorr   r  r  r   rw   allr   masked_fillr   )rV  rb  r  r  re  r   ry   hr  sysxgrid_ygrid_xgrid_xyvalid_WHwh
valid_masks                    r=   _generate_anchorszRTDETRDecoder._generate_anchors,  s   * "6** 		L 		LIAv1!5@@@B!5@@@BFPlU^BTBBBBV[VdegikVlVlNFFk66"2B77G|QF%GGGH((++c1X=GfEEE	QUXZ[U[\BNN59gr]B77<<RQJJKKKK)GQ''}1s7):;@@T@RR
)Gq7{344%%zk5<<@@
""r?   $tuple[torch.Tensor, list[list[int]]]c                J     fdt          |          D             }g }g }|D ]h}|j        dd         \  }}|                    |                    d                              ddd                     |                    ||g           it          j        |d          }||fS )aF  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.
        c                B    g | ]\  }} j         |         |          S r+   )r>  )r9   ry   featr<   s      r=   r{   z4RTDETRDecoder._get_encoder_input.<locals>.<listcomp>^  s/    BBB'!TT_Q%%BBBr?   r   Nr   r   )r   r   r  r   r   rK   r   )r<   r:   r   rV  r  rr  r  s   `      r=   rT  z RTDETRDecoder._get_encoder_inputS  s     CBBBYq\\BBB 	" 	"D:abb>DAqLLa00Aq99:::MM1a&!!!! 	%##f}r?   r   r   rW  r  rX  =tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]c                   |j         d         }| j        s| j        |k    r6|                     ||j        |j                  \  | _        | _        || _        |                     | j        |z            }| 	                    |          }t          j        |                    d          j        | j        d          j                            d          }t          j        ||j                                      d                              d| j                                      d          }	||	|f                             || j        d          }
| j        dd|f                             || j        d          }|                     |
          |z   }|                                }|t          j        ||gd          }||	|f                             || j        d          }| j        r4| j        j                            d                              |dd          n|
}| j        r/|                                }| j        s|                                }|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   rk  ru   r   r}   )rh  r  N)r   r   rV  r{  r  r  r   rz  rF  rG  rK   r   rN   valuesr<  r   rw   r   r   r   rH  r   r   r2  rC  r  r   r   )r<   r   rV  rW  rX  rz   r{  enc_outputs_scorestopk_ind	batch_indtop_k_featurestop_k_anchorsrZ  r[  r\  
embeddingss                   r=   rU  z RTDETRDecoder._get_decoder_inputm  sc   * [^< 	!4;&00,0,B,B6QVQ\ejeq,B,r,r)DL$/ DK ??4?U#:;;!00:: :044R88?AQWXYYYaffgijjLRx~>>>HHLLSSTUW[Wghhmmnpqq	 ")X"56;;B@PRTUUQQQ[166r4;KRPP ''77-G
''))
GZ#8!<<J'	8(;<AA"dFVXZ[[
LPLbvT^*44Q77>>r1aHHHhv
= 	1#**,,J) 1'..00
Hj#91==J:z:==r?   c                v   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 ]Z\  }}t          |j        |           t          |j        d         j        d           t          |j        d         j        d           [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                   dS )zhInitialize or reset the parameters of the model's various components with predefined weights and biases.r`  r)   ru   r  r   r   N)r   r,   r   rG  r   rH  layersr  r   rI  rJ  r   rF  r   r2  rC  rD  r>  )r<   bias_clscls_reg_layers        r=   rK  zRTDETRDecoder._reset_parameters  s    't,,r1DG; 	$%*H555$$+B/6<<<$$+B/4c:::d143EFF 	1 	1JD$di***dk"o,c222dk"o*C0000DOA&'''*1222! 	3DN1222+215<===+215<===_ 	- 	-EE!HO,,,,	- 	-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-   r0  r   r1  r   r2  r   r'  )r:   rm   rM  rN  ro   rO  )rV  ra  rb  r   r  rc  r  rd  re  r   ro   rf  )r:   rm   ro   r|  r   )
r   r   rV  ra  rW  r  rX  r  ro   r  )r   r   r   r   r   rV  rK   r   r   rz  r   r5   ReLUrG   r   r  r  r{  rT  rU  rK  r   r   s   @r=   r"   r"     sP       % %N FFek!nnGQJG % #&!$"'#L! L! L! L! L! L! L!\/, /, /, /, /,b   "]$# $# $# $# \$#L   < )-'+9> 9> 9> 9> 9>v- - - - - - -r?   r"   c                  0     e Zd ZdZdZdd 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+   r,   r-   r.   r/   c                .    t                                          |d|           t          |d         t           j        d                    t          j         fd|D                        _        t          j	         j                   _
        dS )zInitialize 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.
        T)rZ   r.   r   r2   c              3  B  K   | ]}t          j        t          j        t          ||d |          t          |d                    t          j        t          d           t          d                    t          j        j        d                    V  dS )r4   )r  r   NrB   rC   s     r=   r>   z%v10Detect.__init__.<locals>.<genexpr>  s       !
 !
  Md1aa000$q"a..AAd2r1333T"b!__EE	"dgq)) !
 !
 !
 !
 !
 !
r?   N)rF   rG   rN   rO   r,   r5   rP   rS   rV   rW   rY   )r<   r,   r.   rD   r[   s   `  @r=   rG   zv10Detect.__init__  s     	Tb111ADGS))**= !
 !
 !
 !
 !
 !
 !
 !
 
 
  =22r?   c                "    dx| _         | _        dS r   r   rb   s    r=   r   zv10Detect.fuse  r   r?   )r)   r+   r   )r   r   r   r   rZ   rG   r   r   r   s   @r=   r&   r&     sb         0 G3 3 3 3 3 3 3(# # # # # # #r?   r&   )=r   
__future__r   rV   r   rK   torch.nnr5   torch.nn.functional
functionalr  torch.nn.initr   r   ultralytics.utilsr   ultralytics.utils.talr   r   r	   ultralytics.utils.torch_utilsr
   r   r   blockr   r   r   r   r   r   r   r   r   r  r   r   transformerr   r   r   utilsr   r   __all__Moduler    r#   r#  r   rA  r!   re  r   r  r  r$   r%   r  r"   r&   r+   r?   r=   <module>r     sN     " " " " " "                   4 4 4 4 4 4 4 4 ) ) ) ) ) ) D D D D D D D D D D \ \ \ \ \ \ \ \ \ \ o o o o o o o o o o o o o o o o o o o o o o         ] ] ] ] ] ] ] ] ] ] 3 3 3 3 3 3 3 3
ua# a# a# a# a#RY a# a# a#He. e. e. e. e.f e. e. e.P8 8 8 8 8 8 8 8v]. ]. ]. ]. ].& ]. ]. ].@    C   Di i i i i6 i i iXr r r r rT r r rj2, 2, 2, 2, 2,ry 2, 2, 2,jC% C% C% C% C%& C% C% C%N? ? ? ? ?ry ? ? ?DUU UU UU UU UU& UU UU UUpc c c c c; c c cL<Q <Q <Q <Q <Q\ <Q <Q <Q~- - - - -BI - - -D
1# 1# 1# 1# 1# 1# 1# 1# 1# 1#r?   