
    hhS                         d dl mZmZmZmZmZ d dlZd dlmZ d dl	mc m
Z d dlmZmZ d dlmZ ddlmZ  G d dej&                        Z G d	 d
e      Zy)    )AnyDictListOptionalTupleN)	FocalLossVarifocalLoss)bbox_iou   )HungarianMatcherc                       e Zd ZdZ	 	 	 	 	 	 	 	 	 d"dedeeeef      de	de	de	de	ded	ed
ef fdZ
	 d#dej                  dej                  dej                  dededeeej                  f   fdZ	 d#dej                  dej                  dedeeej                  f   fdZ	 	 	 	 d$dej                  dej                  dej                  dej                  dee   deee      dedeej                     deej                     deeej                  f   fdZedee   deeej                  ej                  f   ej                  f   fd       Zdej                  dej                  dee   deej                  ej                  f   fdZ	 	 	 	 d%dej                  dej                  dej                  dej                  dee   deej                     deej                     dedeee      deeej                  f   fdZ	 d#dej                  dej                  deeef   ded edeeej                  f   fd!Z xZS )&DETRLossa  
    DETR (DEtection TRansformer) Loss class for calculating various loss components.

    This class computes classification loss, bounding box loss, GIoU loss, and optionally auxiliary losses for the
    DETR object detection model.

    Attributes:
        nc (int): Number of classes.
        loss_gain (Dict[str, float]): Coefficients for different loss components.
        aux_loss (bool): Whether to compute auxiliary losses.
        use_fl (bool): Whether to use FocalLoss.
        use_vfl (bool): Whether to use VarifocalLoss.
        use_uni_match (bool): Whether to use a fixed layer for auxiliary branch label assignment.
        uni_match_ind (int): Index of fixed layer to use if use_uni_match is True.
        matcher (HungarianMatcher): Object to compute matching cost and indices.
        fl (FocalLoss | None): Focal Loss object if use_fl is True, otherwise None.
        vfl (VarifocalLoss | None): Varifocal Loss object if use_vfl is True, otherwise None.
        device (torch.device): Device on which tensors are stored.
    nc	loss_gainaux_lossuse_fluse_vfluse_uni_matchuni_match_indgammaalphac
                 
   t         
|           |	ddddddd}|| _        t        dddd      | _        || _        || _        |rt        ||	      nd| _        |rt        ||	      nd| _
        || _        || _        d| _        y)	a  
        Initialize DETR loss function with customizable components and gains.

        Uses default loss_gain if not provided. Initializes HungarianMatcher with preset cost gains. Supports auxiliary
        losses and various loss types.

        Args:
            nc (int): Number of classes.
            loss_gain (Dict[str, float], optional): Coefficients for different loss components.
            aux_loss (bool): Whether to use auxiliary losses from each decoder layer.
            use_fl (bool): Whether to use FocalLoss.
            use_vfl (bool): Whether to use VarifocalLoss.
            use_uni_match (bool): Whether to use fixed layer for auxiliary branch label assignment.
            uni_match_ind (int): Index of fixed layer for uni_match.
            gamma (float): The focusing parameter that controls how much the loss focuses on hard-to-classify examples.
            alpha (float): The balancing factor used to address class imbalance.
        Nr         g?)classbboxgiou	no_objectmaskdice)r   r   r   )	cost_gain)super__init__r   r   matcherr   r   r   flr	   vflr   r   device)selfr   r   r   r   r   r   r   r   r   	__class__s             [/var/www/html/dev/engine/venv/lib/python3.12/site-packages/ultralytics/models/utils/loss.pyr#   zDETRLoss.__init__$   s    : 	"#QUV`abI'AqRS2TU" -3)E5)29=.t**    pred_scorestargets	gt_scoresnum_gtspostfixreturnc                    d| }|j                   dd \  }}t        j                  ||| j                  dz   ft        j                  |j
                        }	|	j                  d|j                  d      d       |	dddf   }	|j                  ||d      |	z  }| j                  rU|r | j                  r| j                  |||	      }
n | j                  ||	j                               }
|
t        |d      |z  z  }
n: t        j                  d	      ||      j                  d      j!                         }
||
j#                         | j$                  d
   z  iS )a}  
        Compute classification loss based on predictions, target values, and ground truth scores.

        Args:
            pred_scores (torch.Tensor): Predicted class scores with shape (B, N, C).
            targets (torch.Tensor): Target class indices with shape (B, N).
            gt_scores (torch.Tensor): Ground truth confidence scores with shape (B, N).
            num_gts (int): Number of ground truth objects.
            postfix (str, optional): String to append to the loss name for identification in multi-loss scenarios.

        Returns:
            (Dict[str, torch.Tensor]): Dictionary containing classification loss value.

        Notes:
            The function supports different classification loss types:
            - Varifocal Loss (if self.vfl is True and num_gts > 0)
            - Focal Loss (if self.fl is True)
            - BCE Loss (default fallback)
        
loss_classNr   r   )dtyper'   .none	reductionr   )shapetorchzerosr   int64r'   scatter_	unsqueezeviewr%   r&   floatmaxnnBCEWithLogitsLossmeansumsqueezer   )r(   r,   r-   r.   r/   r0   
name_classbsnqone_hotloss_clss              r*   _get_loss_classzDETRLoss._get_loss_classP   s2   . "'+
""2A&B++r2tww{35;;w~~^G--b115#ss(#NN2r1-7	7748888KGD77;@GQ",,H=r++f=k9UZZ[\]aacHH,,.1HHIIr+   pred_bboxes	gt_bboxesc                 F   d| }d| }i }t        |      dk(  rJt        j                  d| j                        ||<   t        j                  d| j                        ||<   |S | j                  d   t        j                  ||d      z  t        |      z  ||<   d	t        ||d
d
      z
  ||<   ||   j                         t        |      z  ||<   | j                  d   ||   z  ||<   |j                         D ci c]  \  }}||j                          c}}S c c}}w )aQ  
        Compute bounding box and GIoU losses for predicted and ground truth bounding boxes.

        Args:
            pred_bboxes (torch.Tensor): Predicted bounding boxes with shape (N, 4).
            gt_bboxes (torch.Tensor): Ground truth bounding boxes with shape (N, 4).
            postfix (str, optional): String to append to the loss names for identification in multi-loss scenarios.

        Returns:
            (Dict[str, torch.Tensor]): Dictionary containing:
                - loss_bbox{postfix}: L1 loss between predicted and ground truth boxes, scaled by the bbox loss gain.
                - loss_giou{postfix}: GIoU loss between predicted and ground truth boxes, scaled by the giou loss gain.

        Notes:
            If no ground truth boxes are provided (empty list), zero-valued tensors are returned for both losses.
        	loss_bbox	loss_giour           r'   r   rE   r7   g      ?T)xywhGIoUr   )lenr:   tensorr'   r   Fl1_lossr
   rE   itemsrF   )	r(   rM   rN   r0   	name_bbox	name_gioulosskvs	            r*   _get_loss_bboxzDETRLoss._get_loss_bboxz   s   (  y)	y)	y>Q#ll3t{{CDO#ll3t{{CDOK..0199[)_d3eehkluhvvYidQU VVYy/--/#i.@Y..04	?BY+/::<841a199;888s   >Dgt_cls	gt_groupsmatch_indicesmasksgt_maskc
                    t        j                  |dnd|j                        }
|O| j                  rC| j	                  || j
                     || j
                     |||||| j
                     nd|	      }t        t        ||            D ]d  \  }\  }}|||   nd}| j                  |||||||	||	      }|
dxx   |d|    z  cc<   |
d	xx   |d
|    z  cc<   |
dxx   |d|    z  cc<   f d| |
d   d| |
d	   d| |
d   i}
|
S )a[  
        Get auxiliary losses for intermediate decoder layers.

        Args:
            pred_bboxes (torch.Tensor): Predicted bounding boxes from auxiliary layers.
            pred_scores (torch.Tensor): Predicted scores from auxiliary layers.
            gt_bboxes (torch.Tensor): Ground truth bounding boxes.
            gt_cls (torch.Tensor): Ground truth classes.
            gt_groups (List[int]): Number of ground truths per image.
            match_indices (List[Tuple], optional): Pre-computed matching indices.
            postfix (str, optional): String to append to loss names.
            masks (torch.Tensor, optional): Predicted masks if using segmentation.
            gt_mask (torch.Tensor, optional): Ground truth masks if using segmentation.

        Returns:
            (Dict[str, torch.Tensor]): Dictionary of auxiliary losses.
        Nr      rS   rd   re   )rd   re   r0   rc   r   r3   r   rP   r   rQ   loss_class_auxloss_bbox_auxloss_giou_aux)	r:   r;   r'   r   r$   r   	enumeratezip	_get_loss)r(   rM   r,   rN   ra   rb   rc   r0   rd   re   r]   i
aux_bboxes
aux_scores	aux_masksloss_s                   r*   _get_loss_auxzDETRLoss._get_loss_aux   st   < {{ 11qASAST T%7%7 LLD../D../383DeD../$ ) M ,5Sk5R+S 	4'A'
J$)$5a4INN+ # 
E Guz'344GGuy	233GGuy	233G	4, WI&QG9%tAwG9%tAw
 r+   c                 h   t        j                  t        |       D cg c]  \  }\  }}t        j                  ||        c}}}      }t        j                  | D cg c]  \  }}|	 c}}      }t        j                  | D cg c]  \  }}|	 c}}      }||f|fS c c}}}w c c}}w c c}}w )at  
        Extract batch indices, source indices, and destination indices from match indices.

        Args:
            match_indices (List[Tuple]): List of tuples containing matched indices.

        Returns:
            batch_idx (Tuple[torch.Tensor, torch.Tensor]): Tuple containing (batch_idx, src_idx).
            dst_idx (torch.Tensor): Destination indices.
        )r:   catrl   	full_like)rc   ro   src_	batch_idxsrc_idxdstdst_idxs           r*   
_get_indexzDETRLoss._get_index  s     II)TaJbcc;1hsAusA6cd	))?Xc1S?@))?XaS?@7#W,, d??s   #B!B(
B.
c                    t        j                  t        ||      D cg c]J  \  }\  }}t        |      dkD  r||   n.t        j                  d|j
                  d   | j                        L c}}}      }t        j                  t        ||      D cg c]J  \  }\  }}t        |      dkD  r||   n.t        j                  d|j
                  d   | j                        L c}}}      }	||	fS c c}}}w c c}}}w )a  
        Assign predicted bounding boxes to ground truth bounding boxes based on match indices.

        Args:
            pred_bboxes (torch.Tensor): Predicted bounding boxes.
            gt_bboxes (torch.Tensor): Ground truth bounding boxes.
            match_indices (List[Tuple]): List of tuples containing matched indices.

        Returns:
            pred_assigned (torch.Tensor): Assigned predicted bounding boxes.
            gt_assigned (torch.Tensor): Assigned ground truth bounding boxes.
        r   r5   rS   )r:   rv   rm   rV   r;   r9   r'   )
r(   rM   rN   rc   tro   ry   pred_assignedjgt_assigneds
             r*   _get_assigned_bboxeszDETRLoss._get_assigned_bboxes  s     		 "%[-!@ Av1 A
!Aqwwr{4;;(WW
 ii "%Y!> Av1 A
!Aqwwr{4;;(WW
 k))s   AC3AC:c
           	      6   |	| j                  |||||||      }	| j                  |	      \  }
}||
   ||   }}|j                  dd \  }}t        j                  ||f| j
                  |j                  |j                        }||   ||
<   t        j                  ||g|j                        }t        |      r.t        |j                         |d      j                  d      ||
<   i | j                  |||t        |      |      | j                  |||      S )	a%  
        Calculate losses for a single prediction layer.

        Args:
            pred_bboxes (torch.Tensor): Predicted bounding boxes.
            pred_scores (torch.Tensor): Predicted class scores.
            gt_bboxes (torch.Tensor): Ground truth bounding boxes.
            gt_cls (torch.Tensor): Ground truth classes.
            gt_groups (List[int]): Number of ground truths per image.
            masks (torch.Tensor, optional): Predicted masks if using segmentation.
            gt_mask (torch.Tensor, optional): Ground truth masks if using segmentation.
            postfix (str, optional): String to append to loss names.
            match_indices (List[Tuple], optional): Pre-computed matching indices.

        Returns:
            (Dict[str, torch.Tensor]): Dictionary of losses.
        Nrh   r   )r'   r4   rS   T)rT   r5   )r$   r~   r9   r:   fullr   r'   r4   r;   rV   r
   detachrF   rL   r`   )r(   rM   r,   rN   ra   rb   rd   re   r0   rc   idxgt_idxrH   rI   r-   r.   s                   r*   rn   zDETRLoss._get_loss2  s)   :   LL[)VYe]d ) M oom4V!,S!19V3DY""2A&B**b"Xtww{7I7IQWQ]Q]^f~KKR1C1CD	y>%k&8&8&:IDQYYZ\]IcN
"";C	NT[\
!!+y'B
 	
r+   batchkwargsc                    |j                   | _         |j                  dd      }|d   |d   |d   }	}}| j                  |d   |d   |||	||      }
| j                  r,|
j	                  | j                  |dd |dd |||	||             |
S )a  
        Calculate loss for predicted bounding boxes and scores.

        Args:
            pred_bboxes (torch.Tensor): Predicted bounding boxes, shape (L, B, N, 4).
            pred_scores (torch.Tensor): Predicted class scores, shape (L, B, N, C).
            batch (Dict[str, Any]): Batch information containing cls, bboxes, and gt_groups.
            postfix (str, optional): Postfix for loss names.
            **kwargs (Any): Additional arguments, may include 'match_indices'.

        Returns:
            (Dict[str, torch.Tensor]): Computed losses, including main and auxiliary (if enabled).

        Notes:
            Uses last elements of pred_bboxes and pred_scores for main loss, and the rest for auxiliary losses if
            self.aux_loss is True.
        rc   Nclsbboxesrb   r5   r0   rc   )r'   getrn   r   updatert   )r(   rM   r,   r   r0   r   rc   ra   rN   rb   
total_losss              r*   forwardzDETRLoss.forwarde  s    2 "((

?D9',U|U8_eKFX9	^^O[_iT[kx $ 

 ==""$k#2&6	69Vcel r+   )	P   NTTFFr   g      ?g      ?) )Nr   NN)NNr   N)__name__
__module____qualname____doc__intr   r   strr@   boolr#   r:   TensorrL   r`   r   r   rt   staticmethodr~   r   rn   r   r   __classcell__r)   s   @r*   r   r      s   , 04#** De,-* 	*
 * * * * * *Z wy(J <<(J27,,(JKP<<(Jbe(Jps(J	c5<<	 (JV RT!9 <<!949LL!9KN!9	c5<<	 !9R 04(,*.F\\F \\F <<	F
 F 9F  U,F F %F %,,'F 
c5<<	 FP -$u+ -%ellELL>X8Y[`[g[g8g2h - - * <<*49LL*QUV[Q\*	u||U\\)	**H )-*./31
\\1
 \\1
 <<	1

 1
 91
 %1
 %,,'1
 1
  U,1
 
c5<<	 1
p (\\( \\( CH~	(
 ( ( 
c5<<	 (r+   r   c                   \    e Zd ZdZ	 	 	 ddeej                  ej                  f   deee	f   de
ej                     de
ej                     de
eee	f      deeej                  f   f fdZed	eej                     d
edee   deeej                  ej                  f      fd       Z xZS )RTDETRDetectionLossa#  
    Real-Time DeepTracker (RT-DETR) Detection Loss class that extends the DETRLoss.

    This class computes the detection loss for the RT-DETR model, which includes the standard detection loss as well as
    an additional denoising training loss when provided with denoising metadata.
    predsr   	dn_bboxes	dn_scoresdn_metar1   c           
         |\  }}t         |   |||      }|c|d   |d   }
}	t        |d         t        |	      k(  sJ | j                  |	|
|d         }t         |   |||d|      }|j	                  |       |S |j	                  |j                         D ci c]'  }| dt        j                  d| j                        ) c}       |S c c}w )av  
        Forward pass to compute detection loss with optional denoising loss.

        Args:
            preds (Tuple[torch.Tensor, torch.Tensor]): Tuple containing predicted bounding boxes and scores.
            batch (Dict[str, Any]): Batch data containing ground truth information.
            dn_bboxes (torch.Tensor, optional): Denoising bounding boxes.
            dn_scores (torch.Tensor, optional): Denoising scores.
            dn_meta (Dict[str, Any], optional): Metadata for denoising.

        Returns:
            (Dict[str, torch.Tensor]): Dictionary containing total loss and denoising loss if applicable.
        
dn_pos_idxdn_num_grouprb   _dnr   rR   rS   )	r"   r   rV   get_dn_match_indicesr   keysr:   rW   r'   )r(   r   r   r   r   r   rM   r,   r   r   r   rc   dn_lossr^   r)   s                 r*   r   zRTDETRDetectionLoss.forward  s    * $) [W_[+uE
 '.|'<gn>UJu[)*c*o=== !55j,PUVaPbcM goiE5`monGg&
  YcYhYhYjkTU!Cy%,,s4;;*OOkl ls   ,Cr   r   rb   c                 d   g }t        j                  dg|dd       j                  d      }t        |      D ]  \  }}|dkD  rt        j                  |t         j
                        ||   z   }|j                  |      }t        | |         t        |      k(  s#J dt        | |          dt        |       d       |j                  | |   |f       |j                  t        j                  dgt         j
                        t        j                  dgt         j
                        f        |S )	a  
        Get match indices for denoising.

        Args:
            dn_pos_idx (List[torch.Tensor]): List of tensors containing positive indices for denoising.
            dn_num_group (int): Number of denoising groups.
            gt_groups (List[int]): List of integers representing number of ground truths per image.

        Returns:
            (List[Tuple[torch.Tensor, torch.Tensor]]): List of tuples containing matched indices for denoising.
        r   Nr5   )endr4   z"Expected the same length, but got z and z respectively.)r4   )
r:   	as_tensorcumsum_rl   arangelongrepeatrV   appendr;   )r   r   rb   dn_match_indices
idx_groupsro   num_gtr   s           r*   r   z(RTDETRDetectionLoss.get_dn_match_indices  s     __a%9)CR.%9:BB1E
"9- 		rIAvz&

CjQRmS|4:a=)S[8 8Z]9K8LERUV\R]Q^^lm8 !''A(?@ ''aS

)KU[[Z[Y\didndnMo(pq		r  r+   )NNN)r   r   r   r   r   r:   r   r   r   r   r   r   r   r   r   r   r   r   s   @r*   r   r     s     -1,0,0'U\\5<</0' CH~' ELL)	'
 ELL)' $sCx.)' 
c5<<	 'R  & 69 FJ3i 	eELL%,,./	0   r+   r   )typingr   r   r   r   r   r:   torch.nnrB   torch.nn.functional
functionalrX   ultralytics.utils.lossr   r	   ultralytics.utils.metricsr
   opsr   Moduler   r    r+   r*   <module>r      sC    4 3     ; . !~ryy ~BL ( L r+   