§
    ezniY>  ã                   ó–   — 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dS )
é    N)Ú	FocalLossÚVarifocalLoss)Úbbox_ioué   )ÚHungarianMatcherc                   ó†   ‡ — e Zd ZdZ	 	 	 	 	 	 	 dˆ fd„	Zdd	„Zdd
„Z	 	 	 	 dd„Zed„ ¦   «         Z	d„ Z
	 	 	 	 dd„Zdd„Zˆ xZS )ÚDETRLossa+  
    DETR (DEtection TRansformer) Loss class. This class calculates and returns the different loss components for the
    DETR object detection model. It computes classification loss, bounding box loss, GIoU loss, and optionally auxiliary
    losses.

    Attributes:
        nc (int): The number of classes.
        loss_gain (dict): Coefficients for different loss components.
        aux_loss (bool): Whether to compute auxiliary losses.
        use_fl (bool): Use FocalLoss or not.
        use_vfl (bool): Use VarifocalLoss or not.
        use_uni_match (bool): Whether to use a fixed layer to assign labels for the auxiliary branch.
        uni_match_ind (int): The fixed indices of a layer to use if `use_uni_match` is True.
        matcher (HungarianMatcher): Object to compute matching cost and indices.
        fl (FocalLoss or None): Focal Loss object if `use_fl` is True, otherwise None.
        vfl (VarifocalLoss or None): Varifocal Loss object if `use_vfl` is True, otherwise None.
        device (torch.device): Device on which tensors are stored.
    éP   NTFr   c                 ó@  •— t          ¦   «                              ¦   «          |€	dddddddœ}|| _        t          ddddœ¬¦  «        | _        || _        || _        |rt          ¦   «         nd| _        |rt          ¦   «         nd| _
        || _        || _        d| _        dS )	aÑ  
        DETR loss function.

        Args:
            nc (int): The number of classes.
            loss_gain (dict): The coefficient of loss.
            aux_loss (bool): If 'aux_loss = True', loss at each decoder layer are to be used.
            use_vfl (bool): Use VarifocalLoss or not.
            use_uni_match (bool): Whether to use a fixed layer to assign labels for auxiliary branch.
            uni_match_ind (int): The fixed indices of a layer.
        Nr   é   é   gš™™™™™¹?)ÚclassÚbboxÚgiouÚ	no_objectÚmaskÚdice)r   r   r   )Ú	cost_gain)ÚsuperÚ__init__Úncr   ÚmatcherÚ	loss_gainÚaux_lossr   Úflr   ÚvflÚuse_uni_matchÚuni_match_indÚdevice)	Úselfr   r   r   Úuse_flÚuse_vflr   r   Ú	__class__s	           €ú}/var/www/html/cool-property-finder/image-detection-backend/venv/lib/python3.11/site-packages/ultralytics/models/utils/loss.pyr   zDETRLoss.__init__!   s­   ø€ õ& 	‰Œ×ÒÑÔÐàÐØ"#¨Q¸ÈÐUVÐ`aÐbÐbˆIØˆŒÝ'¸AÀqÐRSÐ2TÐ2TÐUÑUÔUˆŒØ"ˆŒØ ˆŒØ!'Ð1•)‘+”+�+¨TˆŒØ&-Ð7•=‘?”?�?°4ˆŒà*ˆÔØ*ˆÔØˆŒˆˆó    Ú c                 óÐ  — d|› �}|j         dd…         \  }}t          j        ||| j        dz   ft          j        |j        ¬¦  «        }	|	                     d|                     d¦  «        d¦  «         |	ddd…f         }	|                     ||d¦  «        |	z  }| j	        r`|r| j
        r|  
                    |||	¦  «        }
n(|  	                    ||	                     ¦   «         ¦  «        }
|
t          |d¦  «        |z  z  }
nD t          j        d¬	¦  «        ||¦  «                             d¦  «                             ¦   «         }
||
                     ¦   «         | j        d
         z  iS )z^Computes the classification loss based on predictions, target values, and ground truth scores.Ú
loss_classNr   r   )Údtyper   éÿÿÿÿ.Únone©Ú	reductionr   )ÚshapeÚtorchÚzerosr   Úint64r   Úscatter_Ú	unsqueezeÚviewr   r   ÚfloatÚmaxÚnnÚBCEWithLogitsLossÚmeanÚsumÚsqueezer   )r    Úpred_scoresÚtargetsÚ	gt_scoresÚnum_gtsÚpostfixÚ
name_classÚbsÚnqÚone_hotÚloss_clss              r$   Ú_get_loss_classzDETRLoss._get_loss_classC   se  € ð , 'Ð+Ð+ˆ
ØÔ" 2 A 2Ô&‰ˆˆBå”+˜r 2 t¤w°¡{Ð3½5¼;ÈwÌ~Ð^Ñ^Ô^ˆØ×Ò˜˜G×-Ò-¨bÑ1Ô1°1Ñ5Ô5Ð5Ø˜#˜s ˜s˜(Ô#ˆØ—N’N 2 r¨1Ñ-Ô-°Ñ7ˆ	àŒ7ð 	dØð A˜4œ8ð AØŸ8š8 K°¸GÑDÔD��àŸ7š7 ;°·²±´Ñ@Ô@�Ø�˜G Q™œ¨"Ñ,Ñ,ˆHˆHà=•rÔ+°fÐ=Ñ=Ô=¸kÈ9ÑUÔU×ZÒZÐ[\Ñ]Ô]×aÒaÑcÔcˆHà˜H×,Ò,Ñ.Ô.°´ÀÔ1HÑHÐIÐIr%   c                 ó&  — d|› �}d|› �}i }t          |¦  «        dk    r>t          j        d| j        ¬¦  «        ||<   t          j        d| j        ¬¦  «        ||<   |S | j        d         t          j        ||d¬¦  «        z  t          |¦  «        z  ||<   d	t          ||d
d
¬¦  «        z
  ||<   ||                              ¦   «         t          |¦  «        z  ||<   | j        d         ||         z  ||<   d„ | 	                    ¦   «         D ¦   «         S )z~Calculates and returns the bounding box loss and GIoU loss for the predicted and ground truth bounding
        boxes.
        Ú	loss_bboxÚ	loss_giour   ç        ©r   r   r:   r,   g      ð?T)ÚxywhÚGIoUr   c                 ó>   — i | ]\  }}||                      ¦   «         “ŒS © )r;   )Ú.0ÚkÚvs      r$   ú
<dictcomp>z+DETRLoss._get_loss_bbox.<locals>.<dictcomp>k   s&   € Ð8Ð8Ð8¡4 1 a��1—9’9‘;”;Ð8Ð8Ð8r%   )
Úlenr/   Útensorr   r   ÚFÚl1_lossr   r:   Úitems)r    Úpred_bboxesÚ	gt_bboxesr@   Ú	name_bboxÚ	name_giouÚlosss          r$   Ú_get_loss_bboxzDETRLoss._get_loss_bboxY   s  € ð
 * Ð)Ð)ˆ	Ø) Ð)Ð)ˆ	àˆÝˆy‰>Œ>˜QÒÐÝ#œl¨2°d´kÐBÑBÔBˆD�‰OÝ#œl¨2°d´kÐBÑBÔBˆD�‰OØˆKàœ.¨Ô0µ1´9¸[È)Ð_dÐ3eÑ3eÔ3eÑeÕhkÐluÑhvÔhvÑvˆˆY‰Ø¥¨°iÀdÐQUÐ VÑ VÔ VÑVˆˆY‰Ø˜yœ/×-Ò-Ñ/Ô/µ#°i±.´.Ñ@ˆˆY‰Øœ.¨Ô0°4¸	´?ÑBˆˆY‰Ø8Ð8¨4¯:ª:©<¬<Ð8Ñ8Ô8Ð8r%   c
                 óT  — t          j        |�dnd|j        ¬¦  «        }
|€H| j        rA|                      || j                 || j                 ||||�|| j                 nd|	¬¦  «        }t          t          ||¦  «        ¦  «        D ]}\  }\  }}|�||         nd}|                      |||||||	||¬¦	  «	        }|
dxx         |d|› �         z  cc<   |
d	xx         |d
|› �         z  cc<   |
dxx         |d|› �         z  cc<   Œ~d|› �|
d         d|› �|
d	         d|› �|
d         i}
|
S )zGet auxiliary losses.Nr   é   rK   ©ÚmasksÚgt_mask)rb   rc   r@   Úmatch_indicesr   r(   r   rH   r   rI   Úloss_class_auxÚloss_bbox_auxÚloss_giou_aux)	r/   r0   r   r   r   r   Ú	enumerateÚzipÚ	_get_loss)r    rY   r<   rZ   Úgt_clsÚ	gt_groupsrd   r@   rb   rc   r]   ÚiÚ
aux_bboxesÚ
aux_scoresÚ	aux_masksÚloss_s                   r$   Ú_get_loss_auxzDETRLoss._get_loss_auxŒ   s§  € õ Œ{ Ð 1˜1˜1°qÀÔASÐTÑTÔTˆØÐ  TÔ%7Ð Ø ŸLšL¨°TÔ5GÔ)HØ)4°TÔ5GÔ)HØ)2Ø)/Ø)2ØLQÐL]¨u°TÔ5GÔ/HÐ/HÐcgØ18ð )ñ :ô :ˆMõ ,5µS¸ÀkÑ5RÔ5RÑ+SÔ+Sð 	4ð 	4Ñ'ˆAÑ'�
˜JØ$)Ð$5˜˜aœ˜¸4ˆIØ—N’N :Ø#-Ø#,Ø#)Ø#,Ø)2Ø+2Ø+2Ø1>ð #ñ @ô @ˆEð �ˆGˆGŒG�uÐ3¨'Ð3Ð3Ô4Ñ4ˆGˆG‰GØ�ˆGˆGŒG�uÐ2¨Ð2Ð2Ô3Ñ3ˆGˆG‰GØ�ˆGˆGŒG�uÐ2¨Ð2Ð2Ô3Ñ3ˆGˆG‰GˆGð '˜WÐ&Ð&¨¨Q¬Ø%˜GÐ%Ð% t¨A¤wØ%˜GÐ%Ð% t¨A¤wð0ˆð ˆr%   c                 óÜ   — t          j        d„ t          | ¦  «        D ¦   «         ¦  «        }t          j        d„ | D ¦   «         ¦  «        }t          j        d„ | D ¦   «         ¦  «        }||f|fS )z[Returns batch indices, source indices, and destination indices from provided match indices.c                 óD   — g | ]\  }\  }}t          j        ||¦  «        ‘ŒS rO   )r/   Ú	full_like)rP   rm   ÚsrcÚ_s       r$   ú
<listcomp>z'DETRLoss._get_index.<locals>.<listcomp>À   s,   € ÐcÐcÐc¹;¸1¹h¸sÀA�uœ¨s°AÑ6Ô6ÐcÐcÐcr%   c                 ó   — g | ]\  }}|‘ŒS rO   rO   )rP   rv   rw   s      r$   rx   z'DETRLoss._get_index.<locals>.<listcomp>Á   s   € Ð?Ð?Ð?¡X c¨1˜SÐ?Ð?Ð?r%   c                 ó   — g | ]\  }}|‘ŒS rO   rO   )rP   rw   Údsts      r$   rx   z'DETRLoss._get_index.<locals>.<listcomp>Â   s   € Ð?Ð?Ð?¡X a¨˜SÐ?Ð?Ð?r%   )r/   Úcatrh   )rd   Ú	batch_idxÚsrc_idxÚdst_idxs       r$   Ú
_get_indexzDETRLoss._get_index½   sw   € õ ”IÐcÐcÍ)ÐTaÑJbÔJbÐcÑcÔcÑdÔdˆ	Ý”)Ð?Ð?°Ð?Ñ?Ô?Ñ@Ô@ˆÝ”)Ð?Ð?°Ð?Ñ?Ô?Ñ@Ô@ˆØ˜7Ð# WÐ,Ð,r%   c                 óÄ   ‡ — t          j        ˆ fd„t          ||¦  «        D ¦   «         ¦  «        }t          j        ˆ fd„t          ||¦  «        D ¦   «         ¦  «        }||fS )z[Assigns predicted bounding boxes to ground truth bounding boxes based on the match indices.c                 ó    •— g | ]J\  }\  }}t          |¦  «        d k    r||         n&t          j        d |j        d         ‰j        ¬¦  «        ‘ŒKS ©r   r*   rK   ©rT   r/   r0   r.   r   )rP   ÚtÚIrw   r    s       €r$   rx   z1DETRLoss._get_assigned_bboxes.<locals>.<listcomp>Ç   s`   ø€ ð #>ð #>ð #>á�‘6�A�qõ ˜‘F”F˜Q’J�JˆAˆaŒDˆD¥E¤K°°1´7¸2´;ÀtÄ{Ð$SÑ$SÔ$Sð#>ð #>ð #>r%   c                 ó    •— g | ]J\  }\  }}t          |¦  «        d k    r||         n&t          j        d |j        d         ‰j        ¬¦  «        ‘ŒKS rƒ   r„   )rP   r…   rw   ÚJr    s       €r$   rx   z1DETRLoss._get_assigned_bboxes.<locals>.<listcomp>Ê   s`   ø€ ð !<ð !<ð !<á�‘6�A�qõ ˜‘F”F˜Q’J�JˆAˆaŒDˆD¥E¤K°°1´7¸2´;ÀtÄ{Ð$SÑ$SÔ$Sð!<ð !<ð !<r%   )r/   r|   ri   )r    rY   rZ   rd   Úpred_assignedÚgt_assigneds   `     r$   Ú_get_assigned_bboxeszDETRLoss._get_assigned_bboxesÅ   s”   ø€ åœ	ð #>ð #>ð #>ð #>å  ¨mÑ<Ô<ð#>ñ #>ô #>ñ ?ô ?ˆõ ”ið !<ð !<ð !<ð !<å  ¨MÑ:Ô:ð!<ñ !<ô !<ñ =ô =ˆð ˜kÐ)Ð)r%   c
           
      ó´  — |	€|                       |||||||¬¦  «        }	|                      |	¦  «        \  }
}||
         ||         }}|j        dd…         \  }}t          j        ||f| j        |j        |j        ¬¦  «        }||         ||
<   t          j        ||g|j        ¬¦  «        }t          |¦  «        r:t          |                     ¦   «         |d¬¦  «                             d¦  «        ||
<   i }|                     |                      |||t          |¦  «        |¦  «        ¦  «         |                     |                      |||¦  «        ¦  «         |S )	zGet losses.Nra   r   )r   r)   rK   T)rL   r*   )r   r€   r.   r/   Úfullr   r   r)   r0   rT   r   Údetachr;   ÚupdaterF   r^   )r    rY   r<   rZ   rk   rl   rb   rc   r@   rd   ÚidxÚgt_idxrB   rC   r=   r>   r]   s                    r$   rj   zDETRLoss._get_lossÏ   sc  € ð Ð Ø ŸLšL¨Ø)4Ø)2Ø)/Ø)2Ø/4Ø18ð )ñ :ô :ˆMð —o’o mÑ4Ô4‰ˆˆVØ!,¨SÔ!1°9¸VÔ3D�YˆàÔ" 2 A 2Ô&‰ˆˆBÝ”*˜b "˜X t¤w°{Ô7IÐQWÔQ]Ð^Ñ^Ô^ˆØ˜f”~ˆ�‰å”K  R °Ô1CÐDÑDÔDˆ	Ýˆy‰>Œ>ð 	^Ý% k×&8Ò&8Ñ&:Ô&:¸IÈDÐQÑQÔQ×YÒYÐZ\Ñ]Ô]ˆI�c‰NàˆØ�Š�D×(Ò(¨°g¸yÍ#ÈiÉ.Ì.ÐZaÑbÔbÑcÔcÐcØ�Š�D×'Ò'¨°YÀÑHÔHÑIÔIÐIð ˆr%   c                 óT  — |j         | _         |                     dd¦  «        }|d         |d         |d         }	}}|                      |d         |d         |||	||¬¦  «        }
| j        r>|
                     |                      |dd…         |dd…         |||	||¦  «        ¦  «         |
S )aÒ  
        Args:
            pred_bboxes (torch.Tensor): [l, b, query, 4]
            pred_scores (torch.Tensor): [l, b, query, num_classes]
            batch (dict): A dict includes:
                gt_cls (torch.Tensor) with shape [num_gts, ],
                gt_bboxes (torch.Tensor): [num_gts, 4],
                gt_groups (List(int)): a list of batch size length includes the number of gts of each image.
            postfix (str): postfix of loss name.
        rd   NÚclsÚbboxesrl   r*   ©r@   rd   )r   Úgetrj   r   r�   rr   )r    rY   r<   Úbatchr@   Úkwargsrd   rk   rZ   rl   Ú
total_losss              r$   ÚforwardzDETRLoss.forwardõ   sÔ   € ð "Ô(ˆŒØŸ
š
 ?°DÑ9Ô9ˆØ',¨U¤|°U¸8´_ÀeÈKÔFX˜9�	ˆà—^’^ K°¤OØ$/°¤OØ$-Ø$*Ø$-Ø,3Ø2?ð $ñ Aô Aˆ
ð Œ=ð 	-Ø×ÒØ×"Ò" ;¨s°¨sÔ#3°[ÀÀ"ÀÔ5EÀyÐRXÐZcÐerØ#*ñ,ô ,ñ-ô -ð -ð Ðr%   )r
   NTTFFr   )r&   )Nr&   NN)NNr&   N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   rF   r^   rr   Ústaticmethodr€   r‹   rj   rš   Ú__classcell__©r#   s   @r$   r	   r	      s  ø€ € € € € ðð ð( ØØØØØ$Ø ð ð  ð  ð  ð  ð  ðDJð Jð Jð Jð,9ð 9ð 9ð 9ðr %)Ø Ø Ø"ð/ð /ð /ð /ðb ð-ð -ñ „\ð-ð*ð *ð *ð  ØØØ $ð$ð $ð $ð $ðLð ð ð ð ð ð ð r%   r	   c                   ó:   ‡ — e Zd ZdZdˆ fd„	Ze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.
    Nc                 óæ  •‡ — |\  }}t          ¦   «                              |||¦  «        }|�‘|d         |d         }
}	t          |d         ¦  «        t          |	¦  «        k    sJ ‚‰                      |	|
|d         ¦  «        }t          ¦   «                              |||d|¬¦  «        }|                     |¦  «         n3|                     ˆ fd„|                     ¦   «         D ¦   «         ¦  «         |S )aF  
        Forward pass to compute the detection loss.

        Args:
            preds (tuple): Predicted bounding boxes and scores.
            batch (dict): Batch data containing ground truth information.
            dn_bboxes (torch.Tensor, optional): Denoising bounding boxes. Default is None.
            dn_scores (torch.Tensor, optional): Denoising scores. Default is None.
            dn_meta (dict, optional): Metadata for denoising. Default is None.

        Returns:
            (dict): Dictionary containing the total loss and, if applicable, the denoising loss.
        NÚ
dn_pos_idxÚdn_num_grouprl   Ú_dnr•   c                 óN   •— i | ]!}|› d �t          j        d‰j        ¬¦  «        “Œ"S )r§   rJ   rK   )r/   rU   r   )rP   rQ   r    s     €r$   rS   z/RTDETRDetectionLoss.forward.<locals>.<dictcomp>:  s3   ø€ ÐjÐjÐjÐST !˜y˜y˜y­%¬,°rÀ$Ä+Ð*NÑ*NÔ*NÐjÐjÐjr%   )r   rš   rT   Úget_dn_match_indicesr�   Úkeys)r    Úpredsr—   Ú	dn_bboxesÚ	dn_scoresÚdn_metarY   r<   r™   r¥   r¦   rd   Údn_lossr#   s   `            €r$   rš   zRTDETRDetectionLoss.forward  sÿ   øø€ ð $)Ñ ˆ�[Ý‘W”W—_’_ [°+¸uÑEÔEˆ
ð ÐØ'.¨|Ô'<¸gÀnÔ>U˜ˆJÝ�u˜[Ô)Ñ*Ô*­c°*©o¬oÒ=Ð=Ð=Ð=ð !×5Ò5°jÀ,ÐPUÐVaÔPbÑcÔcˆMõ ‘g”g—o’o i°¸EÈ5Ð`m�oÑnÔnˆGØ×Ò˜gÑ&Ô&Ð&Ð&ð ×ÒÐjÐjÐjÐjÐXb×XgÒXgÑXiÔXiÐjÑjÔjÑkÔkÐkàÐr%   c                 ó¼  — g }t          j        dg|dd…         ¢¦  «                             d¦  «        }t          |¦  «        D �]\  }}|dk    rµt          j        |t           j        ¬¦  «        ||         z   }|                     |¦  «        }t          | |         ¦  «        t          |¦  «        k    s
J d¦   «         ‚dt          | |         ¦  «        › dt          |¦  «        › d� |                     | |         |f¦  «         ŒÁ|                     t          j	        dgt           j        ¬	¦  «        t          j	        dgt           j        ¬	¦  «        f¦  «         �Œ|S )
a¼  
        Get the 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 the number of ground truths for each image.

        Returns:
            (List[tuple]): List of tuples containing matched indices for denoising.
        r   Nr*   )Úendr)   zExpected the same length, zbut got z and z respectively.)r)   )
r/   Ú	as_tensorÚcumsum_rh   ÚarangeÚlongÚrepeatrT   Úappendr0   )r¥   r¦   rl   Údn_match_indicesÚ
idx_groupsrm   Únum_gtr‘   s           r$   r©   z(RTDETRDetectionLoss.get_dn_match_indices>  sQ  € ð ÐÝ”_ aÐ%9¨)°C°R°C¬.Ð%9Ñ:Ô:×BÒBÀ1ÑEÔEˆ
Ý" 9Ñ-Ô-ð 	rñ 	r‰IˆAˆvØ˜ŠzˆzÝœ¨&½¼
ÐCÑCÔCÀjÐQRÄmÑS�ØŸš |Ñ4Ô4�Ý˜: aœ=Ñ)Ô)­S°©[¬[Ò8Ð8Ð8Ð:VÑ8Ô8Ð8ØO�3˜z¨!œ}Ñ-Ô-ÐOÐOµC¸±K´KÐOÐOÐOÐOØ ×'Ò'¨°A¬¸Ð(?Ñ@Ô@Ð@Ð@à ×'Ò'­¬°a°SÅÄ
Ð)KÑ)KÔ)KÍUÌ[ÐZ[ÐY\ÕdiÔdnÐMoÑMoÔMoÐ(pÑqÔqÐqÑqØÐr%   )NNN)r›   rœ   r�   rž   rš   rŸ   r©   r    r¡   s   @r$   r£   r£     sc   ø€ € € € € ðð ð ð  ð  ð  ð  ð  ðD ð ð  ñ „\ð ð  ð  ð  ð  r%   r£   )r/   Útorch.nnr7   Útorch.nn.functionalÚ
functionalrV   Úultralytics.utils.lossr   r   Úultralytics.utils.metricsr   Úopsr   ÚModuler	   r£   rO   r%   r$   ú<module>rÂ      sì   ðð €€€Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð Ð Ð Ð à ;Ð ;Ð ;Ð ;Ð ;Ð ;Ð ;Ð ;Ø .Ð .Ð .Ð .Ð .Ð .à !Ð !Ð !Ð !Ð !Ð !ðDð Dð Dð Dð DˆrŒyñ Dô Dð DðNB ð B ð B ð B ð B ˜(ñ B ô B ð B ð B ð B r%   