§
    l¬¸jmc  ã                  óÔ   — d dl mZ d dlZd dlmZ ddlmZ ddlmZmZ ddl	m
Z
mZmZ ddlmZ  G d	„ d
ej        ¦  «        Z G d„ de¦  «        Zdd„Zd d„Zd!d"d„Zd#d„Z	 	 d$d%d„ZdS )&é    )ÚannotationsN)Únné   )ÚLOGGER)Úbbox_iouÚprobiou)Ú	xywh2xyxyÚxywhr2xyxyxyxyÚ	xyxy2xywh)Ú
TORCH_1_11c                  ó˜   ‡ — e Zd ZdZ	 	 	 	 	 	 	 ddˆ fd„Z ej        ¦   «         d„ ¦   «         Zd„ Zd„ Z	d„ Z
d„ Zdd„Zd„ Zdd„Zd„ Zˆ xZS )ÚTaskAlignedAssigneraG  A task-aligned assigner for object detection.

    This class assigns ground-truth (gt) objects to anchors based on the task-aligned metric, which combines both
    classification and localization information.

    Attributes:
        topk (int): The number of top candidates to consider.
        topk2 (int): Secondary topk value for additional filtering.
        num_classes (int): The number of object classes.
        alpha (float): The alpha parameter for the classification component of the task-aligned metric.
        beta (float): The beta parameter for the localization component of the task-aligned metric.
        stride (list): List of stride values for different feature levels.
        stride_val (int): The stride value used for select_candidates_in_gts.
        eps (float): A small value to prevent division by zero.
    é   éP   ç      ð?ç      @Nç•Ö&è.>ÚtopkÚintÚnum_classesÚalphaÚfloatÚbetaÚstrideúlist | NoneÚepsc                ó6  •— t          ¦   «                              ¦   «          || _        |p|| _        || _        || _        || _        |�|ng d¢| _        t          | j        ¦  «        dk    r| j        d         n| j        d         | _	        || _
        d| _        dS )aÖ  Initialize a TaskAlignedAssigner object with customizable hyperparameters.

        Args:
            topk (int, optional): The number of top candidates to consider.
            num_classes (int, optional): The number of object classes.
            alpha (float, optional): The alpha parameter for the classification component of the task-aligned metric.
            beta (float, optional): The beta parameter for the localization component of the task-aligned metric.
            stride (list, optional): List of stride values for different feature levels.
            eps (float, optional): A small value to prevent division by zero.
            topk2 (int, optional): Secondary topk value for additional filtering.
        N)é   é   é    r   r   F)ÚsuperÚ__init__r   Útopk2r   r   r   r   ÚlenÚ
stride_valr   Ú_oom_warned)	Úselfr   r   r   r   r   r   r#   Ú	__class__s	           €úe/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/ultralytics/utils/tal.pyr"   zTaskAlignedAssigner.__init__   s˜   ø€ õ* 	‰Œ×ÒÑÔÐØˆŒ	Ø�]˜dˆŒ
Ø&ˆÔØˆŒ
ØˆŒ	Ø &Ð 2�f�f¸¸¸ˆŒÝ,/°´Ñ,<Ô,<¸qÒ,@Ð,@˜$œ+ aœ.˜.ÀdÄkÐRSÄnˆŒØˆŒØ ˆÔÐÐó    c                ó’  ‡— |j         d         | _        |j         d         | _        | j        dk    r…t          j        |d         | j        ¦  «        t          j        |¦  «        t          j        |¦  «        t          j        |d         t          j        ¬¦  «        t          j        |d         ¦  «        fS 	 |                      ||||||¦  «        S # t          $ r.}dt          |¦  «                             ¦   «         vr‚ Y d}~nd}~ww xY w| j        | j        cŠ}| j        s"t          j        d‰› d|› d	�¦  «         d
| _        |                     d¦  «                             ¦   «                              t          j        d|dz   |j        ¬¦  «        ¦  «                             d¦  «                             d¬¦  «                             ¦   «         }	d| _        d}
	 t-          |	¦  «        D ]´\  }| _        |                      |||dz   …         |||dz   …         ||||dz   …d| j        …f         |||dz   …d| j        …f         |||dz   …d| j        …f         ¦  «        }|
€t/          ˆfd„|D ¦   «         ¦  «        }
t1          |
|¦  «        D ]\  }}|d         ||<   ŒŒµ	 ‰|c| _        | _        n# ‰|c| _        | _        w xY w|
S )a  Compute the task-aligned assignment.

        Args:
            pd_scores (torch.Tensor): Predicted classification scores with shape (bs, num_total_anchors, num_classes).
            pd_bboxes (torch.Tensor): Predicted bounding boxes with shape (bs, num_total_anchors, 4).
            anc_points (torch.Tensor): Anchor points with shape (num_total_anchors, 2).
            gt_labels (torch.Tensor): Ground truth labels with shape (bs, n_max_boxes, 1).
            gt_bboxes (torch.Tensor): Ground truth boxes with shape (bs, n_max_boxes, 4).
            mask_gt (torch.Tensor): Mask for valid ground truth boxes with shape (bs, n_max_boxes, 1).

        Returns:
            target_labels (torch.Tensor): Target labels with shape (bs, num_total_anchors).
            target_bboxes (torch.Tensor): Target bounding boxes with shape (bs, num_total_anchors, 4).
            target_scores (torch.Tensor): Target scores with shape (bs, num_total_anchors, num_classes).
            fg_mask (torch.Tensor): Foreground mask with shape (bs, num_total_anchors).
            target_gt_idx (torch.Tensor): Target ground truth indices with shape (bs, num_total_anchors).

        References:
            https://github.com/Nioolek/PPYOLOE_pytorch/blob/master/ppyoloe/assigner/tal_assigner.py
        r   r   ©.r   ©Údtypezout of memoryNz:CUDA out of memory in TaskAlignedAssigner with batch_size=z and max_num_obj=zX; retrying assignment one image at a time on GPU. Model forward batch size is unchanged.Téÿÿÿÿ)Údevice)Úminc              3  ód   •K  — | ]*}|                      ‰g|j        d d…         ¢R ¦  «        V — Œ+dS )r   N)Ú	new_emptyÚshape)Ú.0ÚxÚbss     €r)   ú	<genexpr>z.TaskAlignedAssigner.forward.<locals>.<genexpr>‚   sD   øè è € Ð#TÐ#TÈ A§K¢K°Ð0B°a´g¸a¸b¸b´kÐ0BÐ0BÑ$CÔ$CÐ#TÐ#TÐ#TÐ#TÐ#TÐ#Tr*   )r4   r7   Ún_max_boxesÚtorchÚ	full_liker   Ú
zeros_likeÚboolÚ_forwardÚRuntimeErrorÚstrÚlowerr&   r   ÚwarningÚsqueezeÚmulÚaranger0   ÚamaxÚclamp_ÚtolistÚ	enumerateÚtupleÚzip)r'   Ú	pd_scoresÚ	pd_bboxesÚ
anc_pointsÚ	gt_labelsÚ	gt_bboxesÚmask_gtÚer9   Úlast_gt_idxÚresultsÚiÚresultÚoutputr6   r7   s                  @r)   ÚforwardzTaskAlignedAssigner.forward?   s'  ø€ ð, ”/ !Ô$ˆŒØ$œ?¨1Ô-ˆÔØÔ˜qÒ Ð å” 	¨&Ô 1°4Ô3CÑDÔDÝÔ  Ñ+Ô+ÝÔ  Ñ+Ô+ÝÔ  ¨6Ô!2½%¼*ÐEÑEÔEÝÔ  ¨6Ô!2Ñ3Ô3ðð ð	Ø—=’= ¨I°zÀ9ÈiÐY`ÑaÔaÐaøÝð 	ð 	ð 	Ø¥c¨!¡f¤f§l¢l¡n¤nÐ4Ð4Øð 5Ð4Ð4Ð4Ð4øøøøð	øøøð œ' 4Ô#3ˆˆˆKØÔð 	$ÝŒNðiÈRð ið iÐbmð ið ið iñô ð ð  $ˆDÔà�OŠO˜BÑÔßŠT‰VŒVßŠS•”˜a ¨q¡¸¼ÐHÑHÔHÑIÔIßŠT�!‰WŒWßŠV˜ˆV‰]Œ]ßŠV‰XŒXð 	ð ˆŒØˆð	8Ý'0°Ñ'=Ô'=ð %ð %Ñ#��4Ô#ØŸšØ˜a ! a¡%˜iÔ(Ø˜a ! a¡%˜iÔ(ØØ˜a ! a¡%˜iÐ);¨4Ô+;Ð);Ð;Ô<Ø˜a ! a¡%˜iÐ);¨4Ô+;Ð);Ð;Ô<Ø˜A  A¡˜IÐ'9¨Ô)9Ð'9Ð9Ô:ñô �ð �?Ý#Ð#TÐ#TÐ#TÐ#TÈVÐ#TÑ#TÔ#TÑTÔT�GÝ!$ W¨fÑ!5Ô!5ð %ð %‘I�F˜AØ ! !¤�F˜1‘I�Ið%ð%ð )+¨KÐ%ˆDŒG�TÔ%Ð%ø¨¨KÐ%ˆDŒG�TÔ%Ð7Ð7Ð7Ð7Øˆs%   Â7C Ã
D	Ã$DÄD	ÇCJ3 Ê3Kc                ó  — |                       ||||||¦  «        \  }}}	|                      ||	| j        |¦  «        \  }
}}|                      |||
|¦  «        \  }}}||z  }|                     dd¬¦  «        }|	|z  }	|	                     dd¬¦  «        }|                     |¦  «                             || j        z   ¦  «         |                     d¦  «                             d¦  «        }||z  }|||| 	                    ¦   «         |
fS )a�  Compute the task-aligned assignment.

        Args:
            pd_scores (torch.Tensor): Predicted classification scores with shape (bs, num_total_anchors, num_classes).
            pd_bboxes (torch.Tensor): Predicted bounding boxes with shape (bs, num_total_anchors, 4).
            anc_points (torch.Tensor): Anchor points with shape (num_total_anchors, 2).
            gt_labels (torch.Tensor): Ground truth labels with shape (bs, n_max_boxes, 1).
            gt_bboxes (torch.Tensor): Ground truth boxes with shape (bs, n_max_boxes, 4).
            mask_gt (torch.Tensor): Mask for valid ground truth boxes with shape (bs, n_max_boxes, 1).

        Returns:
            target_labels (torch.Tensor): Target labels with shape (bs, num_total_anchors).
            target_bboxes (torch.Tensor): Target bounding boxes with shape (bs, num_total_anchors, 4).
            target_scores (torch.Tensor): Target scores with shape (bs, num_total_anchors, num_classes).
            fg_mask (torch.Tensor): Foreground mask with shape (bs, num_total_anchors).
            target_gt_idx (torch.Tensor): Target ground truth indices with shape (bs, num_total_anchors).
        r/   T)ÚdimÚkeepdiméþÿÿÿ)
Úget_pos_maskÚselect_highest_overlapsr9   Úget_targetsrF   Úmul_Údiv_r   Ú	unsqueezer=   )r'   rL   rM   rN   rO   rP   rQ   Úmask_posÚalign_metricÚoverlapsÚtarget_gt_idxÚfg_maskÚtarget_labelsÚtarget_bboxesÚtarget_scoresÚpos_align_metricsÚpos_overlapsÚnorm_align_metrics                     r)   r>   zTaskAlignedAssigner._forward‰   s0  € ð$ ,0×+<Ò+<Ø�y )¨Y¸
ÀGñ,
ô ,
Ñ(ˆ�, ð ,0×+GÒ+GØ�h Ô 0°,ñ,
ô ,
Ñ(ˆ�w ð
 7;×6FÒ6FÀyÐR[Ð]jÐlsÑ6tÔ6tÑ3ˆ�} mð 	˜Ñ ˆØ(×-Ò-°"¸dÐ-ÑCÔCÐØ�HÑˆØ—}’}¨°T�}Ñ:Ô:ˆØ×Ò˜,Ñ'Ô'×,Ò,Ð->ÀÄÑ-IÑJÔJÐJØ(×-Ò-¨bÑ1Ô1×;Ò;¸BÑ?Ô?ÐØ%Ð(9Ñ9ˆà˜m¨]¸G¿LºL¹N¼NÈMÐYÐYr*   c                ór  — |                       |||¦  «        }|                      ||||||z  ¦  «        \  }}	|                      ||                     dd| j        ¦  «                             ¦   «         ¬¦  «        }
|
                     |¦  «                             |                     ¦   «         ¦  «        }|||	fS )aÓ  Get positive mask for each ground truth box.

        Args:
            pd_scores (torch.Tensor): Predicted classification scores with shape (bs, num_total_anchors, num_classes).
            pd_bboxes (torch.Tensor): Predicted bounding boxes with shape (bs, num_total_anchors, 4).
            gt_labels (torch.Tensor): Ground truth labels with shape (bs, n_max_boxes, 1).
            gt_bboxes (torch.Tensor): Ground truth boxes with shape (bs, n_max_boxes, 4).
            anc_points (torch.Tensor): Anchor points with shape (num_total_anchors, 2).
            mask_gt (torch.Tensor): Mask for valid ground truth boxes with shape (bs, n_max_boxes, 1).

        Returns:
            mask_pos (torch.Tensor): Positive mask with shape (bs, max_num_obj, h*w).
            align_metric (torch.Tensor): Alignment metric with shape (bs, max_num_obj, h*w).
            overlaps (torch.Tensor): Overlaps between predicted vs ground truth boxes with shape (bs, max_num_obj, h*w).
        r/   )Ú	topk_mask)Úselect_candidates_in_gtsÚget_box_metricsÚselect_topk_candidatesÚexpandr   r=   r`   )r'   rL   rM   rO   rP   rN   rQ   Úmask_in_gtsrd   re   Ú	mask_topkrc   s               r)   r]   z TaskAlignedAssigner.get_pos_mask±   s±   € ð  ×3Ò3°JÀ	È7ÑSÔSˆà!%×!5Ò!5°iÀÈIÐW`ÐbmÐpwÑbwÑ!xÔ!xÑˆ�hà×/Ò/°ÈÏÊÐWYÐ[]Ð_cÔ_hÑHiÔHi×HnÒHnÑHpÔHpÐ/ÑqÔqˆ	à—>’> +Ñ.Ô.×3Ò3°G·L²L±N´NÑCÔCˆà˜ xÐ/Ð/r*   c                ó„  — |j         d         }|                     ¦   «         }| j        | j        |f}|                     d¬¦  «        }||d         |d         ||d         |d         df                              ¦   «         f         }	|                      ||dd…                  ||d         |d         f         ¦  «        }
|	                     | j        ¦  «        |
                     | j	        ¦  «        z  }t          j        ||j        |j        ¬¦  «        }t          j        ||j        |j        ¬¦  «        }|
||<   |||<   ||fS )	a/  Compute alignment metric given predicted and ground truth bounding boxes.

        Args:
            pd_scores (torch.Tensor): Predicted classification scores with shape (bs, num_total_anchors, num_classes).
            pd_bboxes (torch.Tensor): Predicted bounding boxes with shape (bs, num_total_anchors, 4).
            gt_labels (torch.Tensor): Ground truth labels with shape (bs, n_max_boxes, 1).
            gt_bboxes (torch.Tensor): Ground truth boxes with shape (bs, n_max_boxes, 4).
            mask_gt (torch.Tensor): Mask for valid ground truth boxes with shape (bs, n_max_boxes, h*w).

        Returns:
            align_metric (torch.Tensor): Alignment metric combining classification and localization.
            overlaps (torch.Tensor): IoU overlaps between predicted and ground truth boxes.
        r\   T)Úas_tupler   é   r   N©r.   r0   )r4   r=   r7   r9   ÚnonzeroÚlongÚiou_calculationÚpowr   r   r:   Úzerosr.   r0   )r'   rL   rM   rO   rP   rQ   Únar4   ÚindicesÚbbox_scoresÚoverlap_valuesÚalign_valuesre   rd   s                 r)   rq   z#TaskAlignedAssigner.get_box_metricsË   s4  € ð Œ_˜RÔ ˆØ—,’,‘.”.ˆØ”˜Ô)¨2Ð-ˆØ—/’/¨4�/Ñ0Ô0ˆØ ¨¤
¨G°A¬J¸	À'È!Ä*ÈgÐVWÌjÐZ[ÐB[Ô8\×8aÒ8aÑ8cÔ8cÐ cÔdˆØ×-Ò-¨i¸ÀÀÀ¼Ô.DÀiÐPWÐXYÔPZÐ\cÐdeÔ\fÐPfÔFgÑhÔhˆØ"—’ t¤zÑ2Ô2°^×5GÒ5GÈÌ	Ñ5RÔ5RÑRˆå”;˜u¨I¬OÀIÔDTÐUÑUÔUˆÝ”{ 5°Ô0BÈ9ÔK[Ð\Ñ\Ô\ˆØ*ˆ�ÑØ ,ˆ�WÑØ˜XÐ%Ð%r*   c                ót   — t          ||dd¬¦  «                             d¦  «                             d¦  «        S )a
  Calculate IoU for horizontal bounding boxes.

        Args:
            gt_bboxes (torch.Tensor): Ground truth boxes.
            pd_bboxes (torch.Tensor): Predicted boxes.

        Returns:
            (torch.Tensor): IoU values between each pair of boxes.
        FT)ÚxywhÚCIoUr/   r   )r   rC   rG   ©r'   rP   rM   s      r)   r|   z#TaskAlignedAssigner.iou_calculationç   s8   € õ ˜	 9°5¸tÐDÑDÔD×LÒLÈRÑPÔP×WÒWÐXYÑZÔZÐZr*   c                óÞ  — t          j        || j        dd¬¦  «        \  }}|€9|                     dd¬¦  «        d         | j        k                         |¦  «        }|                     | d¦  «         t          j        |j        t           j        |j	        ¬¦  «        }| 
                    d|t          j        |t           j        ¬¦  «        ¦  «         |                     |d	k    d¦  «         |S )
aÈ  Select the top-k candidates based on the given metrics.

        Args:
            metrics (torch.Tensor): A tensor of shape (b, max_num_obj, h*w), where b is the batch size, max_num_obj is
                the maximum number of objects, and h*w represents the total number of anchor points.
            topk_mask (torch.Tensor, optional): An optional boolean tensor of shape (b, max_num_obj, topk), where topk
                is the number of top candidates to consider. If not provided, the top-k values are automatically
                computed based on the given metrics.

        Returns:
            (torch.Tensor): A tensor of shape (b, max_num_obj, h*w) containing the selected top-k candidates.
        r/   T©rZ   ÚlargestN)r[   r   ry   r-   r   )r:   r   Úmaxr   Ú	expand_asÚmasked_fill_r~   r4   Úint8r0   Úscatter_add_Ú	ones_like)r'   Úmetricsro   Útopk_metricsÚ	topk_idxsÚcount_tensors         r)   rr   z*TaskAlignedAssigner.select_topk_candidatesó   sà   € õ #(¤*¨W°d´iÀRÐQUÐ"VÑ"VÔ"VÑˆ�iØÐØ%×)Ò)¨"°dÐ)Ñ;Ô;¸AÔ>ÀÄÒI×TÒTÐU^Ñ_Ô_ˆIà×Ò 	˜z¨1Ñ-Ô-Ð-õ ”{ 7¤=½¼
È9ÔK[Ð\Ñ\Ô\ˆØ×!Ò! " iµ´ÀÕRWÔR\Ð1]Ñ1]Ô1]Ñ^Ô^Ð^à×!Ò! ,°Ò"2°AÑ6Ô6Ð6àÐr*   c                ó`  — t          j        | j        t           j        |j        ¬¦  «        d         }||| j        z  z   }|                     ¦   «                              ¦   «         |         }|                     d|j	        d         ¦  «        |         }| 
                    d¦  «         t          j        |j	        d         |j	        d         | j        ft           j        |j        ¬¦  «        }|                     d|                     d¦  «        d¦  «         ||dd…dd…df         dk    z  }|||fS )	a@  Compute target labels, target bounding boxes, and target scores for the positive anchor points.

        Args:
            gt_labels (torch.Tensor): Ground truth labels of shape (b, max_num_obj, 1), where b is the batch size and
                max_num_obj is the maximum number of objects.
            gt_bboxes (torch.Tensor): Ground truth bounding boxes of shape (b, max_num_obj, 4).
            target_gt_idx (torch.Tensor): Indices of the assigned ground truth objects for positive anchor points, with
                shape (b, h*w), where h*w is the total number of anchor points.
            fg_mask (torch.Tensor): A boolean tensor of shape (b, h*w) indicating the positive (foreground) anchor
                points.

        Returns:
            target_labels (torch.Tensor): Target labels for positive anchor points with shape (b, h*w).
            target_bboxes (torch.Tensor): Target bounding boxes for positive anchor points with shape (b, h*w, 4).
            target_scores (torch.Tensor): Target scores for positive anchor points with shape (b, h*w, num_classes).
        )Úendr.   r0   ).Nr/   r   r   ry   rx   N)r:   rE   r7   Úint64r0   r9   r{   ÚflattenÚviewr4   rG   r~   r   rŽ   Úscatter_rb   )	r'   rO   rP   rf   rg   Ú	batch_indrh   ri   rj   s	            r)   r_   zTaskAlignedAssigner.get_targets  s'  € õ$ ”L T¤WµE´KÈ	ÔHXÐYÑYÔYÐZcÔdˆ	Ø%¨	°DÔ4DÑ(DÑDˆØ!ŸšÑ(Ô(×0Ò0Ñ2Ô2°=ÔAˆð "Ÿš r¨9¬?¸2Ô+>Ñ?Ô?ÀÔNˆð 	×Ò˜QÑÔÐõ œØÔ  Ô# ]Ô%8¸Ô%;¸TÔ=MÐNÝ”*Ø Ô'ð
ñ 
ô 
ˆð
 	×Ò˜q -×"9Ò"9¸"Ñ"=Ô"=¸qÑAÔAÐAà%¨°°°°A°A°A°t°Ô)<¸qÒ)@ÑAˆà˜m¨]Ð:Ð:r*   c                ó^  — t          |¦  «        }|ddd…f         | j        k     }t          j        ||z                       ¦   «         t          j        | j        |j        |j        ¬¦  «        |ddd…f         ¦  «        |ddd…f<   t          |¦  «        }| 	                    d¦  «         
                    dd¦  «        \  }}|dd…df         |d         z
  |k    }	|	|dd…df         |d	         z
  |k    z  }	|	|d         |dd…df         z
  |k    z  }	|	|d	         |dd…df         z
  |k    z  }	|	S )
a¿  Select positive anchor centers within ground truth bounding boxes.

        Args:
            xy_centers (torch.Tensor): Anchor center coordinates, shape (h*w, 2).
            gt_bboxes (torch.Tensor): Ground truth bounding boxes, shape (b, n_boxes, 4).
            mask_gt (torch.Tensor): Mask for valid ground truth boxes, shape (b, n_boxes, 1).
            eps (float, optional): Small value for numerical stability.

        Returns:
            (torch.Tensor): Boolean mask of positive anchors, shape (b, n_boxes, h*w).

        Notes:
            - b: batch size, n_boxes: number of ground truth boxes, h: height, w: width.
            - Bounding box format: [x_min, y_min, x_max, y_max].
        .rx   Nry   é   r   r,   r   ©.r   )r   r%   r:   Úwherer=   Útensorr.   r0   r	   rb   Úchunk)
r'   Ú
xy_centersrP   rQ   r   Úgt_bboxes_xywhÚwh_maskÚltÚrbÚmasks
             r)   rp   z,TaskAlignedAssigner.select_candidates_in_gts7  sR  € õ  # 9Ñ-Ô-ˆØ   a b b Ô)¨D¬OÒ;ˆÝ"'¤+Ø�wÑ×$Ò$Ñ&Ô&ÝŒL˜œ°Ô0DÈ^ÔMbÐcÑcÔcØ˜3   ˜7Ô#ñ#
ô #
ˆ�s˜A˜B˜B�wÑõ
 ˜nÑ-Ô-ˆ	à×$Ò$ QÑ'Ô'×-Ò-¨a°Ñ3Ô3‰ˆˆBØ˜!˜!˜!˜Q˜$Ô " V¤*Ñ,¨sÒ2ˆØ�
˜1˜1˜1˜a˜4Ô  2 f¤:Ñ-°Ò3Ñ3ˆØ��6”
˜Z¨¨¨¨1¨Ô-Ñ-°Ò3Ñ3ˆØ��6”
˜Z¨¨¨¨1¨Ô-Ñ-°Ò3Ñ3ˆØˆr*   c                ó´  — |                      d¦  «        }|                     d¦  «        dk                         d|d¦  «        }|                     d¦  «        j        }t          j        |j        |j        |j	        ¬¦  «        }| 
                    d|                     d¦  «        d¦  «         t          j        |||¦  «        }| j        | j        k    ri||z  }t          j        || j        dd¬¦  «        j        }t          j        |j        |j        |j	        ¬¦  «        }	|	 
                    d|d¦  «         ||	z  }|                     d¦  «        \  }}
|
||fS )a®  Select anchor boxes with highest IoU when assigned to multiple ground truths.

        Args:
            mask_pos (torch.Tensor): Positive mask, shape (b, n_max_boxes, h*w).
            overlaps (torch.Tensor): IoU overlaps, shape (b, n_max_boxes, h*w).
            n_max_boxes (int): Maximum number of ground truth boxes.
            align_metric (torch.Tensor): Alignment metric for selecting best matches.

        Returns:
            target_gt_idx (torch.Tensor): Indices of assigned ground truths, shape (b, h*w).
            fg_mask (torch.Tensor): Foreground mask, shape (b, h*w).
            mask_pos (torch.Tensor): Updated positive mask, shape (b, n_max_boxes, h*w).
        r\   r   r/   ry   Tr‰   r   )Úsumrb   rs   r‹   r€   r:   r~   r4   r.   r0   rš   rŸ   r#   r   )r'   rc   re   r9   rd   rg   Úmask_multi_gtsÚmax_overlaps_idxÚis_max_overlapsÚtopk_idxrf   s              r)   r^   z+TaskAlignedAssigner.select_highest_overlapsW  sF  € ð —,’,˜rÑ"Ô"ˆà!×+Ò+¨AÑ.Ô.°Ò2×:Ò:¸2¸{ÈBÑOÔOˆØ#Ÿ<š<¨™?œ?Ô2ÐÝœ+ h¤n¸H¼NÐS[ÔSbÐcÑcÔcˆØ× Ò  Ð$4×$>Ò$>¸qÑ$AÔ$AÀ1ÑEÔEÐEÝ”;˜~¨ÀÑIÔIˆàŒ:˜œÒ"Ð"Ø'¨(Ñ2ˆLå$œz¨,¸¼
ÈÐTXÐYÑYÔYÔaÐÝ”{ 8¤>¸¼ÐPXÔP_Ð`Ñ`Ô`ˆHØ×Ò˜bÐ"2°CÑ8Ô8Ð8Ø˜Ñ ˆHà!)§¢¨bÑ!1Ô!1Ñˆ�Ø˜g xÐ/Ð/r*   )r   r   r   r   Nr   N)r   r   r   r   r   r   r   r   r   r   r   r   ©N)r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r"   r:   Úno_gradrX   r>   r]   rq   r|   rr   r_   rp   r^   Ú__classcell__)r(   s   @r)   r   r      s  ø€ € € € € ðð ð$ ØØØØ"ØØð!ð !ð !ð !ð !ð !ð !ð@ €U„]�_„_ðGð Gñ „_ðGðR&Zð &Zð &ZðP0ð 0ð 0ð4&ð &ð &ð8
[ð 
[ð 
[ðð ð ð ð8&;ð &;ð &;ðPð ð ð ð@ 0ð  0ð  0ð  0ð  0ð  0ð  0r*   r   c                  ó   — e Zd ZdZd„ Zd„ ZdS )ÚRotatedTaskAlignedAssignerzSAssigns ground-truth objects to rotated bounding boxes using a task-aligned metric.c                ón   — t          ||¦  «                             d¦  «                             d¦  «        S )z)Calculate IoU for rotated bounding boxes.r/   r   )r   rC   rG   r‡   s      r)   r|   z*RotatedTaskAlignedAssigner.iou_calculation}  s.   € å�y )Ñ,Ô,×4Ò4°RÑ8Ô8×?Ò?ÀÑBÔBÐBr*   c                óÈ  — |                      ¦   «         }|ddd…f         | j        k     }t          j        ||z                       ¦   «         t          j        | j        |j        |j        ¬¦  «        |ddd…f         ¦  «        |ddd…f<   t          |¦  «        }| 	                    dd¬¦  «        \  }}}	}
||z
  }|
|z
  }|dd…d	f         |d
         z
  }|dd…df         |d         z
  }||z   
                    d¬¦  «        }||z   
                    d¬¦  «        }||d
         z  ||d         z  z   }||d
         z  ||d         z  z   }|d	k    ||k    z  |d	k    z  ||k    z  S )aÞ  Select the positive anchor center in gt for rotated bounding boxes.

        Args:
            xy_centers (torch.Tensor): Anchor center coordinates with shape (h*w, 2).
            gt_bboxes (torch.Tensor): Ground truth bounding boxes with shape (b, n_boxes, 5).
            mask_gt (torch.Tensor): Mask for valid ground truth boxes with shape (b, n_boxes, 1).

        Returns:
            (torch.Tensor): Boolean mask of positive anchors with shape (b, n_boxes, h*w).
        .rx   é   ry   r   r\   ©rZ   Nr   r,   rž   r/   )Úcloner%   r:   rŸ   r=   r    r.   r0   r
   Úsplitr©   )r'   r¢   rP   rQ   Úgt_bboxes_cloner¤   ÚcornersÚaÚbÚ_ÚdÚabÚadÚapxÚapyÚnorm_abÚnorm_adÚ	ap_dot_abÚ	ap_dot_ads                      r)   rp   z3RotatedTaskAlignedAssigner.select_candidates_in_gts�  sŽ  € ð $Ÿ/š/Ñ+Ô+ˆØ! # q¨ s (Ô+¨d¬oÒ=ˆÝ$)¤KØ�wÑ×$Ò$Ñ&Ô&ÝŒL˜œ°Ô0EÈoÔNdÐeÑeÔeØ˜C  1 ˜HÔ%ñ%
ô %
ˆ˜˜Q˜q˜S˜Ñ!õ ! Ñ1Ô1ˆà—]’] 1¨"�]Ñ-Ô-‰
ˆˆ1ˆa�Ø�‰UˆØ�‰Uˆð ˜˜˜˜A˜Ô  6¤Ñ*ˆØ˜˜˜˜A˜Ô  6¤Ñ*ˆØ˜‘7—-’- B�-Ñ'Ô'ˆØ˜‘7—-’- B�-Ñ'Ô'ˆØ˜"˜Vœ*Ñ$ s¨R°¬ZÑ'7Ñ7ˆ	Ø˜"˜Vœ*Ñ$ s¨R°¬ZÑ'7Ñ7ˆ	Ø˜Q’ 9°Ò#7Ñ8¸IÈºNÑKÈyÐ\cÒOcÑdÐdr*   N)r¯   r°   r±   r²   r|   rp   © r*   r)   r¶   r¶   z  s@   € € € € € Ø]Ð]ðCð Cð Cð!eð !eð !eð !eð !er*   r¶   ç      à?c                ó¨  — g g }}| €J ‚| d         j         }t          t          | ¦  «        ¦  «        D �]x}||         }t          | t          ¦  «        r| |         j        dd…         n5t          | |         d         ¦  «        t          | |         d         ¦  «        f\  }}	t          j        |	¦  «         	                    | d         ¦  «        |z   }
t          j        |¦  «         	                    | d         ¦  «        |z   }t          rt          j        ||
d¬¦  «        nt          j        ||
¦  «        \  }}
|                     t          j        |
|fd¦  «                             dd¦  «        ¦  «         |                     | d                              ||	z  df||¬¦  «        ¦  «         �Œzt          j        |¦  «        t          j        |¦  «        fS )	zGenerate anchors from features.Nr   rx   r   Úij)Úindexingr/   r-   )r.   Úranger$   Ú
isinstanceÚlistr4   r   r:   rE   Útype_asr   ÚmeshgridÚappendÚstackr™   Únew_fullÚcat)ÚfeatsÚstridesÚgrid_cell_offsetÚanchor_pointsÚstride_tensorr.   rU   r   ÚhÚwÚsxÚsys               r)   Úmake_anchorsrâ   ¥  s©  € à#% r�=€MØÐÐÐØ�!ŒHŒN€EÝ•3�u‘:”:ÑÔð Qñ QˆØ˜”ˆÝ%/°µtÑ%<Ô%<Ðfˆu�QŒxŒ~˜a˜b˜bÔ!Ð!Å3ÀuÈQÄxÐPQÄ{ÑCSÔCSÕUXÐY^Ð_`ÔYaÐbcÔYdÑUeÔUeÐBf‰ˆˆ1åŒ\˜!‰_Œ_×$Ò$ U¨1¤XÑ.Ô.Ð1AÑAˆÝŒ\˜!‰_Œ_×$Ò$ U¨1¤XÑ.Ô.Ð1AÑAˆÝ:DÐ`•”  B°Ð6Ñ6Ô6Ð6Í%Ì.ÐY[Ð]_ÑJ`ÔJ`‰ˆˆBØ×Ò�Uœ[¨"¨b¨°2Ñ6Ô6×;Ò;¸BÀÑBÔBÑCÔCÐCØ×Ò˜U 1œX×.Ò.°°A±°q¨z¸6ÈÐ.ÑOÔOÑPÔPÐPÑPÝŒ9�]Ñ#Ô#¥U¤Y¨}Ñ%=Ô%=Ð=Ð=r*   Tr/   c                óÂ   — |                       d|¦  «        \  }}||z
  }||z   }|r$||z   dz  }||z
  }	t          j        ||	g|¦  «        S t          j        ||f|¦  «        S )z.Transform distance(ltrb) to box(xywh or xyxy).rx   )r¡   r:   rØ   )
ÚdistancerÜ   r…   rZ   r¥   r¦   Úx1y1Úx2y2Úc_xyÚwhs
             r)   Ú	dist2bboxré   ¶  sx   € à�^Š^˜A˜sÑ#Ô#�F€BˆØ˜2Ñ€DØ˜2Ñ€DØð *Ø�t‘˜qÑ ˆØ�D‰[ˆÝŒy˜$ ˜ SÑ)Ô)Ð)ÝŒ9�d˜D�\ 3Ñ'Ô'Ð'r*   rÜ   útorch.TensorÚbboxÚreg_maxú
int | NoneÚreturnc                ó¨   — |                      dd¦  «        \  }}t          j        | |z
  || z
  fd¦  «        }|�|                     d|dz
  ¦  «        }|S )z#Transform bbox(xyxy) to dist(ltrb).rx   r/   Nr   ç{®Gáz„?)r¡   r:   rØ   rG   )rÜ   rë   rì   rå   ræ   Údists         r)   Ú	bbox2distrò   Â  s[   € à—’˜A˜rÑ"Ô"�J€Dˆ$ÝŒ9�m dÑ*¨D°=Ñ,@ÐAÀ2ÑFÔF€DØÐØ�{Š{˜1˜g¨™nÑ-Ô-ˆØ€Kr*   c                ó^  — |                       d|¬¦  «        \  }}t          j        |¦  «        t          j        |¦  «        }}||z
  dz                        d|¬¦  «        \  }}	||z  |	|z  z
  ||z  |	|z  z   }}
t          j        |
|g|¬¦  «        |z   }t          j        |||z   g|¬¦  «        S )aî  Decode predicted rotated bounding box coordinates from anchor points and distribution.

    Args:
        pred_dist (torch.Tensor): Predicted rotated distance with shape (bs, h*w, 4).
        pred_angle (torch.Tensor): Predicted angle with shape (bs, h*w, 1).
        anchor_points (torch.Tensor): Anchor points with shape (h*w, 2).
        dim (int, optional): Dimension along which to split.

    Returns:
        (torch.Tensor): Predicted rotated bounding boxes with shape (bs, h*w, 4).
    rx   rº   r   )r¼   r:   ÚcosÚsinrØ   )Ú	pred_distÚ
pred_anglerÜ   rZ   r¥   r¦   rô   rõ   ÚxfÚyfr6   ÚyÚxys                r)   Ú	dist2rboxrü   Ë  s»   € ð �_Š_˜Q Cˆ_Ñ(Ô(�F€BˆÝŒy˜Ñ$Ô$¥e¤i°
Ñ&;Ô&;ˆ€Cà�B‰w˜!‰m×"Ò" 1¨#Ð"Ñ.Ô.�F€BˆØ�‰8�b˜3‘hÑ  S¡¨2°©8Ñ 3€q€AÝ	Œ�A�q�6˜sÐ	#Ñ	#Ô	# mÑ	3€BÝŒ9�b˜"˜r™'�]¨Ð,Ñ,Ô,Ð,r*   ri   Útarget_anglerZ   r   c                óÔ  — |                       d|¬¦  «        \  }}||z
  }|                      d|¬¦  «        \  }}	t          j        |¦  «        t          j        |¦  «        }}
||
z  |	|z  z   }| |z  |	|
z  z   }|                      d|¬¦  «        \  }}|dz  |z
  }|dz  |z
  }|dz  |z   }|dz  |z   }t          j        ||||g|¬¦  «        }|�|                     d|dz
  ¦  «        }|S )a[  Transform rotated bounding box (xywh) to distance (ltrb). This is the inverse of dist2rbox.

    Args:
        target_bboxes (torch.Tensor): Target rotated bounding boxes with shape (bs, h*w, 4), format [x, y, w, h].
        anchor_points (torch.Tensor): Anchor points with shape (h*w, 2).
        target_angle (torch.Tensor): Target angle with shape (bs, h*w, 1).
        dim (int, optional): Dimension along which to split.
        reg_max (int, optional): Maximum regression value for clamping.

    Returns:
        (torch.Tensor): Rotated distance with shape (bs, h*w, 4), format [l, t, r, b].
    rx   rº   r   Nr   rð   )r¼   r:   rô   rõ   rØ   rG   )ri   rÜ   rý   rZ   rì   rû   rè   ÚoffsetÚoffset_xÚoffset_yrô   rõ   rø   rù   rß   rÞ   Útarget_lÚtarget_tÚtarget_rÚtarget_brñ   s                        r)   Ú	rbox2distr  à  s  € ð& × Ò  ¨Ð Ñ,Ô,�F€BˆØ�-Ñ€FØŸš a¨S˜Ñ1Ô1Ñ€HˆhÝŒy˜Ñ&Ô&­¬	°,Ñ(?Ô(?ˆ€CØ	�C‰˜( S™.Ñ	(€BØ
ˆ�S‰˜8 c™>Ñ	)€Bà�8Š8�A˜3ˆ8ÑÔ�D€A€qØ�1‰u�r‰z€HØ�1‰u�r‰z€HØ�1‰u�r‰z€HØ�1‰u�r‰z€HåŒ9�h ¨(°HÐ=À3ÐGÑGÔG€DØÐØ�{Š{˜1˜g¨™nÑ-Ô-ˆà€Kr*   )rÌ   )Tr/   r®   )rÜ   rê   rë   rê   rì   rí   rî   rê   )r/   )r/   N)
ri   rê   rÜ   rê   rý   rê   rZ   r   rì   rí   )Ú
__future__r   r:   r   Ú r   r‘   r   r   Úopsr	   r
   r   Útorch_utilsr   ÚModuler   r¶   râ   ré   rò   rü   r  rË   r*   r)   ú<module>r     sw  ðð #Ð "Ð "Ð "Ð "Ð "à €€€Ø Ð Ð Ð Ð Ð à Ð Ð Ð Ð Ð Ø &Ð &Ð &Ð &Ð &Ð &Ð &Ð &Ø 5Ð 5Ð 5Ð 5Ð 5Ð 5Ð 5Ð 5Ð 5Ð 5Ø #Ð #Ð #Ð #Ð #Ð #ði0ð i0ð i0ð i0ð i0˜"œ)ñ i0ô i0ð i0ðX(eð (eð (eð (eð (eÐ!4ñ (eô (eð (eðV>ð >ð >ð >ð"	(ð 	(ð 	(ð 	(ðð ð ð ð ð-ð -ð -ð -ð2 Øð$ð $ð $ð $ð $ð $ð $r*   