§
    ­¸jk‰  ã                  ó¤  — U d Z ddlmZ ddlmZ ddlmZmZmZ ddl	Z
ddlZddlmc mZ ddlmZ ddlmZ ddlmZ ee
j        ee
j        e
j                 f         e
j        ee
j        e
j                 f         e
j        ee
j        e
j                 f         ef         Zd	ed
<   ee
j        ee
j        e
j                 f         e
j        ee
j        e
j                 f         f         Zd	ed<    e
j         de
j        ¬¦  «        Z!ded<   dZ"ded<   dLd„Z#dMd„Z$dNd„Z%dOd$„Z&dPd%„Z'dOd&„Z(dQd*„Z)dRd-„Z*dSd0„Z+dTd6„Z,dUd<„Z-	 	 dVdWdE„Z.dXdF„Z/dYdI„Z0dZdK„Z1dS )[zBGreedy matching and accumulation functions for evaluation metrics.é    )Úannotations)ÚCounter)ÚAnyÚ	TypeAliasÚcastN)ÚTensor)Úbox_iou)Ú
all_gatherr   Ú_ClassContributionÚ_ClassSlice©Údtypez"np.ndarray[Any, np.dtype[np.intp]]Ú_NO_INDICESé    ÚintÚ_MASK_IOU_CHUNKÚmasksr   ÚhwÚreturnc                óâ   ‡ ‡— ‰ j         d         }ˆˆ fd„t          d|t          ¦  «        D ¦   «         }|s&t          j        dt          j        ‰ j        ¬¦  «        S t          j        |d¬¦  «        S )uR  Sum each mask's true pixels, ``_MASK_IOU_CHUNK`` rows at a time.

    Matches ``masks.bool().view(-1, hw).float().sum(dim=1, keepdim=True)`` row for row: a row's sum
    only reads that row's own pixels, so batching rows into chunks changes neither the per-row
    floating-point reduction nor its result â€” only how many rows are converted to float32 at once.

    Args:
        masks: Boolean mask tensor of shape [count, H, W].
        hw: Flattened pixel count ``H * W`` each mask reshapes to.

    Returns:
        Float32 tensor of shape [count, 1] with each row's true-pixel count.
    r   c                óÎ   •— g | ]a}‰||t           z   …                              ¦   «                              d ‰¦  «                             ¦   «                              dd¬¦  «        ‘ŒbS )éÿÿÿÿé   T)ÚdimÚkeepdim)r   ÚboolÚviewÚfloatÚsum)Ú.0Ústartr   r   s     €€új/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/evaluation/matching.pyú
<listcomp>z#_mask_row_areas.<locals>.<listcomp>N   su   ø€ ð ð ð àð 	ˆe�e�oÑ-Ð-Ô.×3Ò3Ñ5Ô5×:Ò:¸2¸rÑBÔB×HÒHÑJÔJ×NÒNÐSTÐ^bÐNÑcÔcðð ð ó    ©r   r   ©r   Údevice©r   )ÚshapeÚranger   ÚtorchÚzerosÚfloat32r'   Úcat)r   r   ÚcountÚchunkss   ``  r"   Ú_mask_row_areasr1   ?   s…   øø€ ð ŒK˜ŒN€Eðð ð ð ð å˜1˜e¥_Ñ5Ô5ðñ ô €Fð ð MÝŒ{˜6­¬¸u¼|ÐLÑLÔLÐLÝŒ9�V Ð#Ñ#Ô#Ð#r$   Úsizeútuple[int, int]c                óÄ   — t          j        |                      ¦   «                              d¦  «        |d¬¦  «                             d¦  «                             ¦   «         S )a—  Resize one boolean-mask chunk with nearest-neighbor sampling.

    Resizes only a caller-bounded chunk so the temporary float32 interpolation
    output cannot scale with every ground-truth mask in an image.

    Args:
        masks: Boolean mask tensor of shape [chunk, H, W].
        size: Target height and width.

    Returns:
        Resized boolean mask tensor of shape [chunk, size[0], size[1]].
    r   Únearest)r2   Úmode)ÚFÚinterpolater   Ú	unsqueezeÚsqueezer   )r   r2   s     r"   Ú_resize_mask_chunkr;   W   sL   € õ Œ=˜Ÿš™œ×0Ò0°Ñ3Ô3¸$ÀYÐOÑOÔO×WÒWÐXYÑZÔZ×_Ò_ÑaÔaÐar$   Ú
pred_masksÚgt_masksc           
     óÐ  ‡‡‡— | j         d         }‰j         d         }| j         d         | j         d         fŠ‰‰j         dd…         k    }‰d         ‰d         z  Št          | ‰¦  «        }|rcˆˆˆfd„t          d|t          ¦  «        D ¦   «         }|rt	          j        |d¬¦  «        n%t	          j        dt          j        ‰j        ¬	¦  «        }nt          ‰‰¦  «        }g }t          d|t          ¦  «        D �]²}	| |	|	t          z   …          	                    ¦   «          
                    d‰¦  «                             ¦   «         }
g }t          d|t          ¦  «        D ]š}‰||t          z   …         }|rt          |‰¦  «        }| 	                    ¦   «          
                    d‰¦  «                             ¦   «         }|                     t	          j        |
|                     ¦   «         ¦  «        ¦  «         Œ›|rt	          j        |d¬¦  «        n-t	          j        |
j         d         df|
j        |
j        ¬	¦  «        }||	|	t          z   …         |                     ¦   «         z   |z
  }|                     t	          j        |dk    ||z  t	          j        |¦  «        ¦  «        ¦  «         �Œ´|s#t	          j        ||f|j        |j        ¬	¦  «        S t	          j        |d¬¦  «        S )
aW  Compute pairwise boolean-mask IoU between N predictions and M ground truths.

    Both predictions and ground truths are converted to float32 ``_MASK_IOU_CHUNK`` rows at a time.
    When mask grids differ, ground truths are also resized one chunk at a time before conversion. At
    most one prediction chunk and one ground-truth chunk are resident as float32 [chunk, H*W] tensors,
    bounding that allocation to ``_MASK_IOU_CHUNK x H x W`` on each side instead of ``N x H x W`` and
    ``M x H x W``. This changes only how much memory the call uses at once, not the returned values:
    each output entry depends solely on its own prediction mask and ground-truth mask.

    Args:
        pred_masks: Boolean mask tensor of shape [N, H, W].
        gt_masks: Boolean mask tensor of shape [M, H, W].

    Returns:
        IoU tensor of shape [N, M].
    r   éþÿÿÿr   Nr   c           
     ól   •— g | ]0}t          t          ‰||t          z   …         ‰¦  «        ‰¦  «        ‘Œ1S © )r1   r;   r   )r    r!   r=   r   Ú	mask_sizes     €€€r"   r#   z%_compute_mask_iou.<locals>.<listcomp>€   sO   ø€ ð 
ð 
ð 
àõ Õ.¨x¸ÀÍÑ@WÐ8WÔ/XÐZcÑdÔdÐfhÑiÔið
ð 
ð 
r$   r(   r%   r&   )r)   r1   r*   r   r+   r.   r,   r-   r'   r   r   r   r;   ÚappendÚmmÚtr   ÚwhereÚ
zeros_like)r<   r=   ÚnÚmÚresize_ground_truthsÚ	pred_areaÚgt_area_chunksÚgt_areaÚiou_rowsÚpstartÚ
pred_chunkÚinter_blocksÚgstartÚgt_chunkÚgt_flatÚinterÚunionr   rB   s    `               @@r"   Ú_compute_mask_iourW   g   sï  øøø€ ð" 	Ô˜Ô€AØŒ�qÔ€AØÔ! "Ô% zÔ'7¸Ô';Ð<€IØ$¨¬°r°s°sÔ(;Ò;ÐØ	�1Œ˜	 !œÑ	$€Bå 
¨BÑ/Ô/€IØð 0ð
ð 
ð 
ð 
ð 
ð 
å˜q !¥_Ñ5Ô5ð
ñ 
ô 
ˆð ðR�EŒI�n¨!Ð,Ñ,Ô,Ð,å”˜V­5¬=ÀÄÐQÑQÔQð 	ˆõ " (¨BÑ/Ô/ˆà€HÝ˜˜1�oÑ.Ô.ð Xñ XˆØ ¨µ/Ñ)AÐ AÔB×GÒGÑIÔI×NÒNÈrÐSUÑVÔV×\Ò\Ñ^Ô^ˆ
ØˆÝ˜A˜q¥/Ñ2Ô2ð 	Cð 	CˆFØ ¨µ/Ñ)AÐ AÔBˆHØ#ð CÝ-¨h¸	ÑBÔB�Ø—m’m‘o”o×*Ò*¨2¨rÑ2Ô2×8Ò8Ñ:Ô:ˆGØ×Ò¥¤¨°W·Y²Y±[´[Ñ AÔ AÑBÔBÐBÐBð ði�EŒI�l¨Ð*Ñ*Ô*Ð*å”˜jÔ.¨qÔ1°1Ð5¸ZÔ=MÐV`ÔVgÐhÑhÔhð 	ð
 ˜& 6­OÑ#;Ð;Ô<¸w¿yºy¹{¼{ÑJÈUÑRˆØ�Š�œ E¨A¢I¨u°u©}½eÔ>NÈuÑ>UÔ>UÑVÔVÑWÔWÐWÑWØð SÝŒ{˜A˜q˜6¨¬ÀÔAQÐRÑRÔRÐRÝŒ9�X 1Ð%Ñ%Ô%Ð%r$   Úiou_matrix_sortedú%np.ndarray[Any, np.dtype[np.float32]]Úgt_crowd_npú#np.ndarray[Any, np.dtype[np.bool_]]Úiou_thresholdr   úTtuple[np.ndarray[Any, np.dtype[np.int64]], np.ndarray[Any, np.dtype[np.bool_]], int]c                ól   — |                      ¦   «         st          | |¦  «        S t          | ||¦  «        S )u?  Apply COCO greedy matching to score-ordered NumPy IoUs for one class.

    Dispatches on whether the class has any crowd GT. Both loops below are per-detection Python
    loops whose cost is dominated by the number of NumPy calls each iteration makes, so the common
    crowd-free case gets its own loop rather than paying for masks that can only be no-ops.

    Args:
        iou_matrix_sorted: Pairwise IoUs whose rows are in descending detection-score order. Must not
            be modified here: the bbox caller derives it from the one ``box_iou`` matrix shared by
            every class of an image, so masking rows in place instead of copying them would leak one
            class's matching state into the classes matched after it.
        gt_crowd_np: Boolean crowd mask aligned to IoU columns.
        iou_threshold: Minimum IoU to count as a positive match.

    Returns:
        Tuple of true-positive flags, crowd-ignore flags, and the number of non-crowd ground truths.
        The scores the rows were ordered by are not returned â€” every caller already holds them.
    )ÚanyÚ_match_rows_without_crowdÚ_match_rows_with_crowd)rX   rZ   r\   s      r"   Ú_match_sorted_iou_matrixrb   ¢   s;   € ð6 �?Š?ÑÔð KÝ(Ð):¸MÑJÔJÐJÝ!Ð"3°[À-ÑPÔPÐPr$   c                ó’  — | j         \  }}t          j        |t          j        ¬¦  «        }t          j        |t          j        ¬¦  «        }t          t          t                   |                      d¬¦  «         	                    ¦   «         ¦  «        }t          t          t                   |                      d¬¦  «         	                    ¦   «         ¦  «        }t          |¦  «        D ]¿}||         |k     rŒ||         }	||	         sd||<   d||	<   Œ*t          t          j        t          t          j        t          j                 f         | |                              ¦   «         ¦  «        }
d|
|<   t          |
                     ¦   «         ¦  «        }|
|         |k    r
d||<   d||<   ŒÀ|t          j        |t          j        ¬¦  «        |fS )u)  Greedily match score-ordered IoUs for a class whose ground truths are all non-crowd.

    Behaviourally a special case of ``_match_rows_with_crowd()`` â€” every GT is claimable, none can
    be ignored, and ``total_gt`` is simply the column count. What makes it worth its own loop is
    that the per-detection cost here is NumPy call overhead, not array work: at a few dozen GTs a
    call costs more than the elements it touches, so the win comes from making calls disappear.

    Two whole-matrix reductions do that for the two cases that need no search at all: a detection
    whose best IoU is below the threshold cannot match any GT, and one whose best GT is still free
    matches exactly that GT (masking can only lower other columns, so it cannot promote a different
    one, and ``argmax`` already resolved ties to the lowest column index). Only a detection whose
    best GT was claimed by a higher-scoring detection falls back to a masked search.

    Args:
        iou_matrix_sorted: Pairwise IoUs whose rows are in descending detection-score order. Read
            only, for the reason given on ``_match_sorted_iou_matrix()``.
        iou_threshold: Minimum IoU to count as a positive match.

    Returns:
        Tuple of true-positive flags, all-False crowd-ignore flags, and the ground-truth count.
    r   r   )ÚaxisTç      ð¿)r)   Únpr,   Úbool_Úint64r   Úlistr   ÚargmaxÚtolistr   Úmaxr*   Úndarrayr   r   r-   Úcopy)rX   r\   rH   rI   Úgt_matched_npÚpred_match_npÚbest_columnsÚ	best_iousÚindexÚbest_columnÚ	free_iousÚ
best_indexs               r"   r`   r`   Â   s•  € ð: Ô"�D€A€qÝ”H˜Q¥b¤hÐ/Ñ/Ô/€MÝ”H˜Q¥b¤hÐ/Ñ/Ô/€Mõ ��Sœ	Ð#4×#;Ò#;ÀÐ#;Ñ#CÔ#C×#JÒ#JÑ#LÔ#LÑMÔM€LÝ•T�%”[Ð"3×"7Ò"7¸QÐ"7Ñ"?Ô"?×"FÒ"FÑ"HÔ"HÑIÔI€Iå�q‘”ð -ð -ˆØ�UÔ˜mÒ+Ð+ØØ" 5Ô)ˆØ˜[Ô)ð 	Ø#$ˆM˜%Ñ Ø)-ˆM˜+Ñ&Øõ �œ¥C­¬µ"´*Ô)=Ð$=Ô>Ð@QÐRWÔ@X×@]Ò@]Ñ@_Ô@_Ñ`Ô`ˆ	Ø#'ˆ	�-Ñ Ý˜×)Ò)Ñ+Ô+Ñ,Ô,ˆ
Ø�ZÔ  MÒ1Ð1Ø#$ˆM˜%Ñ Ø(,ˆM˜*Ñ%øà�"œ( 1­B¬HÐ5Ñ5Ô5°qÐ8Ð8r$   c                óT  — | j         \  }}t          j        |t          j        ¬¦  «        }t          j        |t          j        ¬¦  «        }t          j        |t          j        ¬¦  «        }t          |                     ¦   «         ¦  «        }| }	t          t          | ¦  «        ¦  «        D ]Ú}
t          t          j
        t          t          j        t          j                 f         | |
         ¦  «        }|                     ¦   «         }d||<   d|||	z  <   t          |                     ¦   «         ¦  «        }||         |k    rd||
<   d||<   Œ¢|r6|                     ¦   «         }d||	<   |                     ¦   «         |k    rd||
<   ŒÛ||t          |	                     ¦   «         ¦  «        fS )uÌ  Greedily match score-ordered IoUs for a class that may have crowd ground truths.

    Handles crowd GTs in full generality, so it stays correct for an all-non-crowd input too â€” that
    is what makes it the reference ``_match_rows_without_crowd()`` is differentially tested against.

    Args:
        iou_matrix_sorted: Pairwise IoUs whose rows are in descending detection-score order. Read
            only, for the reason given on ``_match_sorted_iou_matrix()``.
        gt_crowd_np: Boolean crowd mask aligned to IoU columns.
        iou_threshold: Minimum IoU to count as a positive match.

    Returns:
        Tuple of true-positive flags, crowd-ignore flags, and the number of non-crowd ground truths.
    r   re   r   T)r)   rf   r,   rg   rh   r   r_   r*   Úlenr   rm   r   r   r-   rn   r   rj   rl   r   )rX   rZ   r\   rH   rI   ro   rp   Úpred_ignore_npÚ	any_crowdÚnot_crowd_nprs   ÚiousÚnoncrowd_iousÚbest_noncrowd_indexÚ
crowd_iouss                  r"   ra   ra   ü   s‡  € ð. Ô"�D€A€qÝ”H˜Q¥b¤hÐ/Ñ/Ô/€MÝ”H˜Q¥b¤hÐ/Ñ/Ô/€MÝ”X˜a¥r¤xÐ0Ñ0Ô0€NÝ�[—_’_Ñ&Ô&Ñ'Ô'€IØ�<€Lõ •sÐ,Ñ-Ô-Ñ.Ô.ð -ð -ˆÝ•B”J�s¥B¤H­R¬ZÔ$8Ð8Ô9Ð;LÈUÔ;SÑTÔTˆØŸ	š	™œˆØ%)ˆ�kÑ"Ø6:ˆ�m lÑ2Ñ3õ " -×"6Ò"6Ñ"8Ô"8Ñ9Ô9ÐØÐ,Ô-°Ò>Ð>Ø#$ˆM˜%Ñ Ø15ˆMÐ-Ñ.Ð.Øð 	-ØŸš™œˆJØ'+ˆJ�|Ñ$Ø�~Š~ÑÔ =Ò0Ð0Ø(,�˜uÑ%øà˜.­#¨l×.>Ò.>Ñ.@Ô.@Ñ*AÔ*AÐAÐAr$   Úlabel_ids_npú#np.ndarray[Any, np.dtype[np.int64]]ú-dict[int, np.ndarray[Any, np.dtype[np.intp]]]c                óò   ‡ — ‰ j         dk    ri S t          j        ‰ d¬¦  «        }‰ |         }t          j        |dd…         |dd…         k    ¦  «        dz   }ˆ fd„t          j        ||¦  «        D ¦   «         S )u—  Group array positions by label in one pass over an image's labels.

    Replaces one ``label_ids_np == class_id`` scan per class â€” O(N) per class, O(N*C) over an
    image â€” with a single stable sort. Within each group the positions stay ascending, which is the
    order a per-class scan produces and the order the greedy matcher's stable score sort then
    breaks ties on, so the grouping is a pure speedup and not a reordering.

    Args:
        label_ids_np: Label of every detection (or of every GT) of one image.

    Returns:
        Dict mapping each label present to its ascending positions in *label_ids_np*; empty for an
        empty input.
    r   Ústable©Úkindr   Nr   c                óH   •— i | ]}t          ‰|d                   ¦  «        |“ŒS )r   )r   )r    Úgroupr€   s     €r"   ú
<dictcomp>z+_group_indices_by_label.<locals>.<dictcomp>G  s,   ø€ ÐXÐXÐX°5�C�˜U 1œXÔ&Ñ'Ô'¨ÐXÐXÐXr$   )r2   rf   ÚargsortÚflatnonzeroÚsplit)r€   ÚorderÚsorted_labelsÚ
boundariess   `   r"   Ú_group_indices_by_labelr�   1  s‡   ø€ ð" Ô˜AÒÐØˆ	ÝŒJ�|¨(Ð3Ñ3Ô3€EØ  Ô'€MÝ” ¨a¨b¨bÔ 1°]À3ÀBÀ3Ô5GÒ GÑHÔHÈ1ÑL€JØXÐXÐXÐX½B¼HÀUÈJÑ<WÔ<WÐXÑXÔXÐXr$   Ú	scores_npú+np.ndarray[Any, np.dtype[np.floating[Any]]]c                ó  — t          | ¦  «        }t          j        |  d¬¦  «        }| |                              t          j        d¬¦  «        t          j        |t          j        ¬¦  «        t          j        |t          j        ¬¦  «        dfS )a„  Build the contribution of a class that has detections but no ground truth.

    Both ``iou_type`` paths reach this case and must report it identically: every detection is a
    false positive, none is crowd-ignored, and the class adds nothing to the GT denominator.

    Args:
        scores_np: Detection scores of one class, in the caller's own float dtype so that near-tied
            scores are ordered at full precision before the float32 cast.

    Returns:
        Tuple ``(scores_np, matches_np, ignore_np, total_gt)`` with the scores in descending order,
        all-zero matches, all-False ignore flags, and a ``total_gt`` of 0.
    r„   r…   F©rn   r   r   )rx   rf   rŠ   Úastyper-   r,   rh   rg   )r‘   rH   r�   s      r"   Ú_unmatched_contributionr–   J  sy   € õ  	ˆI‰Œ€Aõ ŒJ˜	�z¨Ð1Ñ1Ô1€Eà�%Ô×Ò¥¤
°ÐÑ7Ô7Ý
Œ��"œ(Ð#Ñ#Ô#Ý
Œ��"œ(Ð#Ñ#Ô#Ø	ð	ð r$   Úpred_scoresÚgt_crowdc                óv  — t          j        | dd¬¦  «        }| |         }||         }t          ||¦  «        }|                     ¦   «                              ¦   «                              ¦   «                              ¦   «         }	|                     ¦   «                              ¦   «                              ¦   «         }
t          |	|
|¦  «        \  }}}t          j	        |                     ¦   «                              ¦   «                              ¦   «                              ¦   «         t          j
        ¬¦  «        |||fS )u£  Greedy highest-score-first mask matching for one class in one image.

    Implements the COCO matching algorithm over boolean-mask IoU: each GT is matched at most once; detections are
    processed in descending score order; detections matched to crowd GTs are marked as ignored rather than false
    positives. This is the segmentation path only â€” the box path never reaches here, because it shares one image-wide
    ``box_iou`` matrix and calls ``_match_sorted_iou_matrix`` directly.

    Args:
        pred_scores: Float tensor of shape [N] with detection confidences.
        pred_masks: Boolean prediction masks of shape [N, H, W].
        gt_masks: Boolean ground-truth masks of shape [M, H, W].
        gt_crowd: Bool tensor of shape [M], True for crowd instances.
        iou_threshold: Minimum IoU to count as a positive match.

    Returns:
        Tuple ``(scores_np, matches_np, ignore_np, total_gt)`` where:
            - scores_np: float32 array [N] ordered by descending score.
            - matches_np: int array [N], 1 = TP, 0 = FP.
            - ignore_np: bool array [N], True if matched to a crowd GT.
            - total_gt: number of non-crowd GT instances.
    T)Ú
descendingr„   r   )r+   rŠ   rW   Údetachr   ÚcpuÚnumpyrb   rf   Úasarrayr-   )r—   r<   r=   r˜   r\   Úsort_idxÚpred_scores_sortedÚpred_sortedÚ
iou_matrixÚiou_matrix_nprZ   Ú
matches_npÚ	ignore_npÚtotal_gts                 r"   Ú_match_single_class_segmr§   g  s  € õ@ Œ}˜[°TÀ$ÐGÑGÔG€HØ$ XÔ.ÐØ˜XÔ&€Kå" ;°Ñ9Ô9€Jð ×%Ò%Ñ'Ô'×-Ò-Ñ/Ô/×3Ò3Ñ5Ô5×;Ò;Ñ=Ô=€MØ—/’/Ñ#Ô#×'Ò'Ñ)Ô)×/Ò/Ñ1Ô1€Kå&>¸}ÈkÐ[hÑ&iÔ&iÑ#€J�	˜8å
Œ
Ð%×,Ò,Ñ.Ô.×4Ò4Ñ6Ô6×:Ò:Ñ<Ô<×BÒBÑDÔDÍBÌJÐWÑWÔWØØØð	ð r$   Úpred_scores_npÚclass_sliceú_ClassSlice | NoneÚbbox_iou_matrix_npú,np.ndarray[Any, np.dtype[np.float32]] | Nonec                ó¸  — |€| n| |d                  }|€|j         n|d         j         }|dk    rt          |¦  «        S |€
J d¦   «         ‚t          j        | d¬¦  «        }|€||         |}	}n.|\  }
}|t          j        |
|         |¦  «                 }||         }	t          ||	|¦  «        \  }}}||                              t          j        d¬¦  «        |||fS )	aþ  Accumulate one class of one image against the image's shared box-IoU matrix.

    Everything needed here is already on the host, so the class is selected by slicing the per-image
    NumPy arrays instead of by indexing device tensors. A *class_slice* of ``None`` says the image
    holds one class only: it then owns every row and column of *bbox_iou_matrix_np*, and the
    two-axis fancy-index copy that isolates a class becomes a copy of the whole matrix onto itself,
    so only the rows are reordered and the crowd mask is taken as it stands.

    Args:
        pred_scores_np: Every detection score of the image, in the caller's own float dtype.
        class_slice: The class's prediction rows and GT columns, or ``None`` when the image holds a
            single class. A class with predictions but no GT gets an empty column selection, never
            ``None``.
        gt_crowd_np: Crowd flag per GT of the image.
        bbox_iou_matrix_np: The image's ``box_iou`` matrix, or ``None`` when the image has no
            detections or no GT at all. A class without GT returns before it is read.
        iou_threshold: Minimum IoU to count as a positive match.

    Returns:
        Tuple ``(scores_np, matches_np, ignore_np, total_gt)`` contributed by the class.
    Nr   r   z~the image-wide box_iou matrix is built whenever the image has both detections and GTs, and this class has at least one of eachr„   r…   Fr”   )r2   r–   rf   rŠ   Úix_rb   r•   r-   )r¨   r©   rZ   r«   r\   Úp_scores_npÚn_gtr�   rX   Úclass_crowd_npÚpred_indicesÚ
gt_indicesr¤   r¥   r¦   s                  r"   Ú_accumulate_bbox_classr´      s
  € ð8 %0Ð$7�.�.¸^ÈKÐXYÌNÔ=[€KØ*Ð2ˆ;ÔÐ¸ÀA¼Ô8K€Dàˆq‚y€yÝ& {Ñ3Ô3Ð3àÐ)Ð)ð	2ñ *Ô)Ð)õ ŒJ˜�|¨(Ð3Ñ3Ô3€EØÐØ,>¸uÔ,EÀ{˜>ÐÐà#.Ñ ˆ�jØ.­r¬v°lÀ5Ô6IÈ:Ñ/VÔ/VÔWÐØ$ ZÔ0ˆå&>Ð?PÐR`ÐboÑ&pÔ&pÑ#€J�	˜8Ø�uÔ×$Ò$¥R¤Z°eÐ$Ñ<Ô<¸jÈ)ÐU]Ð]Ð]r$   Úpredsúdict[str, Tensor]ÚtargetsÚclass_idr°   c                ó  — | d         |k    }| d         |         }|dk    rut          t          j        |                     ¦   «                              ¦   «                              ¦   «                              ¦   «         t          j        ¬¦  «        ¦  «        S |                      d¦  «        }|                     d¦  «        }	|�|	€t          d¦  «        ‚|d         |k    }
t          |||         |	|
         ||
         |¦  «        S )a•  Accumulate one class of one image on boolean-mask IoU.

    Mask IoU stays class-local rather than being shared image-wide like the box path: an all-pairs
    mask matrix is much larger, and most of it would cover pairs that cannot match.

    Args:
        preds: One image's predictions, keyed as documented on ``build_matching_data()``.
        targets: One image's ground truths, keyed as documented on ``build_matching_data()``.
        gt_crowd: Bool tensor [M] aligned to ``targets["labels"]``, already validated by the caller.
        class_id: Class to accumulate.
        n_gt: Number of GTs of *class_id* in this image. Taken from the caller's host-side label
            counts rather than read back out of ``targets["labels"]``, which would cost one
            device-to-host sync per class.
        iou_threshold: Minimum IoU to count as a positive match.

    Returns:
        Tuple ``(scores_np, matches_np, ignore_np, total_gt)`` contributed by *class_id*.

    Raises:
        ValueError: If ``masks`` is missing from *preds* or *targets*. A class with no GT of its own
            returns before that lookup, so a one-sided class is never reported.
    ÚlabelsÚscoresr   r   r   Nz:iou_type='segm' requires 'masks' in both preds and targets)r–   rf   rž   r›   r   rœ   r�   r-   ÚgetÚ
ValueErrorr§   )rµ   r·   r˜   r¸   r°   r\   Úpred_mask_cÚp_scoresr<   r=   Ú	gt_mask_cs              r"   Ú_accumulate_segm_classrÁ   Ò  sð   € ð< ˜”/ XÒ-€KØ�XŒ˜{Ô+€Hàˆq‚y€yå&¥r¤z°(·/²/Ñ2CÔ2C×2IÒ2IÑ2KÔ2K×2OÒ2OÑ2QÔ2Q×2WÒ2WÑ2YÔ2YÕacÔakÐ'lÑ'lÔ'lÑmÔmÐmà—’˜7Ñ#Ô#€JØ�{Š{˜7Ñ#Ô#€HØÐ˜XÐ-ÝÐUÑVÔVÐVà˜Ô! XÒ-€IÝ#Ø�*˜[Ô)¨8°IÔ+>ÀÈÔ@SÐUbñô ð r$   ç      à?ÚbboxÚ
preds_listúlist[dict[str, Tensor]]Útargets_listÚiou_typeÚstrúdict[int, dict[str, Any]]c                óê  — i }t          | |¦  «        D �]Â\  }}|d         }|d         }|d         }	|d         }
|d         }|                     dt          j        t	          |¦  «        t          j        |j        ¬¦  «        ¦  «        }|                     ¦   «         }|j        dk    s#|j	        d         | 
                    ¦   «         k    r:t          dt          |j	        ¦  «        › d	| 
                    ¦   «         › d
�¦  «        ‚t          t          t                   |                     ¦   «         ¦  «        }t          t          t                   |	                     ¦   «         ¦  «        }t          t          t                   |                     ¦   «         ¦  «        }t#          |¦  «        }t#          |¦  «        }t#          d„ t          ||¦  «        D ¦   «         ¦  «        }t%          |¦  «        t%          |¦  «        z  }t	          |¦  «        dk    }i }i }|dk    r^|r\|sZt'          t)          j        |t(          j        ¬¦  «        ¦  «        }t'          t)          j        |t(          j        ¬¦  «        ¦  «        }t)          j        |t(          j        ¬¦  «        }d}d}|dk    re|rc|                     ¦   «                              ¦   «         }|j        t          j        k    r|                     ¦   «         }|                     ¦   «         }|dk    rz|rx|rvt)          j        t=          ||
¦  «                             ¦   «                              ¦   «                              ¦   «                              ¦   «         t(          j        ¬¦  «        }|D �]I}|                      |g g g ddœ¦  «        }|                     |d¦  «        dk    r6t          t          |d         ¦  «        |                     |d¦  «        z   |d<   Œn|dk    rL|€
J d¦   «         ‚|rdn"||         |                     |tB          ¦  «        f}tE          |||||¦  «        \  }} }!}"n-tG          |||||                     |d¦  «        |¦  «        \  }} }!}"t          t          t8                   |d         ¦  «         $                    t          t          t8                   |                     ¦   «         ¦  «        ¦  «         t          t          t                   |d         ¦  «         $                    t          t          t                   |                      ¦   «         ¦  «        ¦  «         t          t          t                   |d         ¦  «         $                    t          t          t                   |!                     ¦   «         ¦  «        ¦  «         t          t          |d         ¦  «        |"z   |d<   �ŒK�ŒÄd„ | %                    ¦   «         D ¦   «         S )a-	  Build compact per-class matching data from a batch of predictions and targets.

    Implements greedy highest-score-first matching compatible with the COCO algorithm. The returned dict can be passed
    directly to ``merge_matching_data()`` and ultimately consumed by ``sweep_confidence_thresholds()`` after conversion
    to list form.

    Detections are ranked in the dtype of ``preds["scores"]``, so a ``float64`` input keeps the full precision that
    separates near-tied scores, and detections that really are tied keep their input order. Both ``iou_type`` paths
    share that rule, which makes the TP/FP split reproducible across devices and dtypes. The returned scores are
    float32 either way.

    Args:
        preds_list: Per-image predictions. Each dict must contain:

            - ``boxes``: float Tensor [N, 4] in absolute xyxy coordinates.
            - ``scores``: float Tensor [N].
            - ``labels``: int64 Tensor [N].
            - ``masks`` *(optional)*: bool Tensor [N, H, W] for segmentation.

        targets_list: Per-image ground truths. Each dict must contain:

            - ``boxes``: float Tensor [M, 4] in absolute xyxy coordinates.
            - ``labels``: int64 Tensor [M].
            - ``masks`` *(optional)*: bool Tensor [M, H, W] for segmentation.
            - ``iscrowd`` *(optional)*: int64 Tensor [M], 1 for crowd instances.

        iou_threshold: IoU threshold for positive matching. Defaults to 0.5.
        iou_type: ``"bbox"`` for bounding-box IoU; ``"segm"`` for boolean-mask
            IoU. Defaults to ``"bbox"``.

    Returns:
        Dict mapping ``class_id`` (int) to a compact matching dict with keys:

            - ``"scores"``: float32 ndarray of detection scores.
            - ``"matches"``: int ndarray (1 = TP, 0 = FP).
            - ``"ignore"``: bool ndarray (True if matched to a crowd GT).
            - ``"total_gt"``: int, count of non-crowd GT instances.

    Raises:
        ValueError: If a target's ``iscrowd`` is not a 1-D tensor with one entry per GT label, or if
            ``iou_type="segm"`` and ``masks`` is missing on either side for a class that has both
            predictions and ground truth. Classes present on only one side skip the mask lookup, so
            a missing ``masks`` key is not reported for an image whose classes are all one-sided.
    Úboxesr»   rº   Úiscrowdr&   r   r   zF'iscrowd' must be a 1-D tensor with one entry per GT label, got shape z for z labelsc              3  ó$   K  — | ]\  }}|°|V — Œd S )NrA   )r    ÚlabelÚcrowds      r"   ú	<genexpr>z&build_matching_data.<locals>.<genexpr>S  s,   è è € Ð#kÐ#k©l¨e°UÐejÐ#k EÐ#kÐ#kÐ#kÐ#kÐ#kÐ#kr$   rÃ   r   N©r»   ÚmatchesÚignorer¦   r¦   zWthe image's scores are moved to host whenever it has detections, and this class has onerÒ   rÓ   c           	     ó  — i | ]\  }}|t          j        |d          t           j        ¬¦  «        t          j        |d         t           j        ¬¦  «        t          j        |d         t           j        ¬¦  «        |d         dœ“Œ€S )r»   r   rÒ   rÓ   r¦   rÑ   )rf   Úarrayr-   rh   rg   )r    r¸   Údatas      r"   r‰   z'build_matching_data.<locals>.<dictcomp>—  sˆ   € ð ð ð ñ ˆH�dð 	Ý”h˜t Hœ~µR´ZÐ@Ñ@Ô@Ý”x  Y¤µr´xÐ@Ñ@Ô@Ý”h˜t Hœ~µR´XÐ>Ñ>Ô>Ø˜ZÔ(ð	
ð 
ðð ð r$   )&Úzipr¼   r+   r,   rx   Úlongr'   r   Úndimr)   Únumelr½   Útupler   ri   r   rk   r   Úsetr�   rf   rž   rh   rg   r›   rœ   r   Úbfloat16r   r�   r	   r-   Ú
setdefaultr   r´   rÁ   ÚextendÚitems)#rÄ   rÆ   r\   rÇ   Úaccrµ   r·   Ú
pred_boxesr—   Úpred_labelsÚgt_boxesÚ	gt_labelsÚ	raw_crowdr˜   Úgt_label_idsÚpred_label_idsÚgt_crowd_idsÚ
pred_countÚgt_countÚgt_noncrowd_countÚall_class_idsÚsingle_classÚpred_groupsÚ	gt_groupsrZ   r«   r¨   Úpred_scores_cpur¸   Úentryr©   r‘   r¤   r¥   r¦   s#                                      r"   Úbuild_matching_dataró     s†  € ðd 24€Cå˜j¨,Ñ7Ô7ð _Hñ _H‰ˆˆwØ˜7”^ˆ
Ø˜H”oˆØ˜H”oˆà˜7Ô#ˆØ˜HÔ%ˆ	Ø—K’KØÝŒK�˜I™œ­e¬jÀÔAQÐRÑRÔRñ
ô 
ˆ	ð —>’>Ñ#Ô#ˆð Œ=˜AÒÐ ¤°Ô!2°i·o²oÑ6GÔ6GÒ!GÐ!GÝðJÝ˜œÑ(Ô(ðJð JØ/8¯ªÑ/@Ô/@ðJð Jð Jñô ð õ
 �D¥œI y×'7Ò'7Ñ'9Ô'9Ñ:Ô:ˆÝ�d¥3œi¨×);Ò);Ñ)=Ô)=Ñ>Ô>ˆÝ�D¥œJ¨¯ªÑ(9Ô(9Ñ:Ô:ˆõ
 ˜^Ñ,Ô,ˆ
Ý˜<Ñ(Ô(ˆÝ#Ð#kÐ#k½cÀ,ÐP\Ñ>]Ô>]Ð#kÑ#kÔ#kÑkÔkÐÝ"% h¡-¤-µ#°j±/´/Ñ"Aˆõ ˜=Ñ)Ô)¨QÒ.ˆØEGˆØCEˆ	Ø�vÒÐ *Ð°\ÐÝ1µ"´*¸^ÕSUÔS[Ð2\Ñ2\Ô2\Ñ]Ô]ˆKÝ/µ´
¸<ÍrÌxÐ0XÑ0XÔ0XÑYÔYˆIå”j µR´XÐ>Ñ>Ô>ˆØKOÐð NRˆØ�vÒÐ *ÐØ)×0Ò0Ñ2Ô2×6Ò6Ñ8Ô8ˆOØÔ$­¬Ò6Ð6Ø"1×"7Ò"7Ñ"9Ô"9�Ø,×2Ò2Ñ4Ô4ˆNØ�vÒÐ *Ð°Ðõ "$¤Ý˜
 HÑ-Ô-×4Ò4Ñ6Ô6×<Ò<Ñ>Ô>×BÒBÑDÔD×JÒJÑLÔLÕTVÔT^ð"ñ "ô "Ðð &ð "	Hñ "	HˆHØ—N’NØØ¨"¸ÈÐJÐJñô ˆEð
 �~Š~˜h¨Ñ*Ô*¨aÒ/Ð/Ý$(­¨e°JÔ.?Ñ$@Ô$@ÐCT×CXÒCXÐYaÐcdÑCeÔCeÑ$e��jÑ!Øð ˜6Ò!Ð!Ø%Ð1Ð1Ømñ 2Ô1Ð1ð '3Ðu˜d˜d¸ÀXÔ9NÐPY×P]ÒP]Ð^fÕhsÑPtÔPtÐ8u�Ý=SØ"ØØØ&Ø!ñ>ô >Ñ:�	˜: y°(°(õ >TØ˜7 H¨h¸¿ºÀXÈqÑ8QÔ8QÐS`ñ>ô >Ñ:�	˜: y°(õ ••e”˜e HœoÑ.Ô.×5Ò5µd½4Å¼;È	×HXÒHXÑHZÔHZÑ6[Ô6[Ñ\Ô\Ð\Ý••c”˜E )Ô,Ñ-Ô-×4Ò4µT½$½s¼)ÀZ×EVÒEVÑEXÔEXÑ5YÔ5YÑZÔZÐZÝ••d”˜U 8œ_Ñ-Ô-×4Ò4µT½$½t¼*Ài×FVÒFVÑFXÔFXÑ5YÔ5YÑZÔZÐZÝ $¥S¨%°
Ô*;Ñ <Ô <¸xÑ GˆE�*ÑÑñE"	HðHð ð "Ÿiši™kœkðñ ô ð r$   c                 ó   — i S )z¶Return an empty matching accumulator compatible with ``merge_matching_data()``.

    Returns:
        Empty dict to be passed as the first argument to ``merge_matching_data()``.
    rA   rA   r$   r"   Úinit_matching_accumulatorrõ   ¢  s	   € ð €Ir$   ÚaccumulatorÚnew_datac                ó  — |                      ¦   «         D ]ï\  }}|| vrY|d                              ¦   «         |d                              ¦   «         |d                              ¦   «         |d         dœ| |<   Œb| |         }t          j        |d         |d         g¦  «        |d<   t          j        |d         |d         g¦  «        |d<   t          j        |d         |d         g¦  «        |d<   |dxx         |d         z  cc<   Œð| S )aú  Merge *new_data* into *accumulator* in place.

    Both arguments share the dict schema produced by ``build_matching_data()``: each class-keyed sub-dict contains
    ``"scores"`` (float32 ndarray), ``"matches"`` (int64 ndarray), ``"ignore"`` (bool ndarray), and ``"total_gt"``
    (int).

    Args:
        accumulator: Running accumulator, modified in place.
        new_data: Batch-level matching data to merge in.

    Returns:
        The modified *accumulator* (same object, for method chaining).
    r»   rÒ   rÓ   r¦   rÑ   )rà   rn   rf   Úconcatenate)rö   r÷   r¸   rÖ   rò   s        r"   Úmerge_matching_datarú   «  s  € ð" #Ÿ.š.Ñ*Ô*ð 2ð 2‰ˆ�$Ø˜;Ð&Ð&à˜xœ.×-Ò-Ñ/Ô/Ø 	œ?×/Ò/Ñ1Ô1Ø˜xœ.×-Ò-Ñ/Ô/Ø  Ô,ð	%ð %ˆK˜Ñ!Ð!ð   Ô)ˆEÝ œn¨e°H¬o¸tÀH¼~Ð-NÑOÔOˆE�(‰OÝ!œ~¨u°YÔ/?ÀÀiÄÐ.QÑRÔRˆE�)ÑÝ œn¨e°H¬o¸tÀH¼~Ð-NÑOÔOˆE�(‰OØ�*ÐÐÔ  jÔ!1Ñ1ÐÐÑÐØÐr$   Ú
local_datac                óR   — t          | ¦  «        }i }|D ]}t          ||¦  «         Œ|S )aµ  Gather per-rank matching data from all DDP ranks and merge into one dict.

    Uses ``rfdetr.utilities.all_gather`` (pickle-based) so the data need not be a tensor. In single-process
    (non-distributed) mode, returns a merged copy of *local_data* unchanged.

    Args:
        local_data: Per-rank accumulator produced by ``merge_matching_data()``.

    Returns:
        Merged accumulator containing contributions from all ranks.
    )r
   rú   )rû   ÚgatheredÚmergedÚ	rank_datas       r"   Údistributed_merge_matching_datar   Í  s=   € õ 1;¸:Ñ0FÔ0F€HØ(*€FØð /ð /ˆ	Ý˜F IÑ.Ô.Ð.Ð.Ø€Mr$   )r   r   r   r   r   r   )r   r   r2   r3   r   r   )r<   r   r=   r   r   r   )rX   rY   rZ   r[   r\   r   r   r]   )rX   rY   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¨   r’   r©   rª   rZ   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Å   rÆ   rÅ   r\   r   rÇ   rÈ   r   rÉ   )r   rÉ   )rö   rÉ   r÷   rÉ   r   rÉ   )rû   rÉ   r   rÉ   )2Ú__doc__Ú
__future__r   Úcollectionsr   Útypingr   r   r   r�   rf   r+   Útorch.nn.functionalÚnnÚ
functionalr7   r   Útorchvision.opsr	   Úrfdetr.utilitiesr
   rÛ   rm   r   r-   rh   rg   r   r   Ú__annotations__Úintpr   r,   r   r   r1   r;   rW   rb   r`   ra   r�   r–   r§   r´   rÁ   ró   rõ   rú   r   rA   r$   r"   ú<module>r     s  ðð  IÐ HÐ Hà "Ð "Ð "Ð "Ð "Ð "à Ð Ð Ð Ð Ð Ø 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'à Ð Ð Ð Ø €€€Ø Ð Ð Ð Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð Ø #Ð #Ð #Ð #Ð #Ð #à 'Ð 'Ð 'Ð 'Ð 'Ð 'ð !&Ø„Jˆs�B”H˜RœZÔ(Ð(Ô)Ø„Jˆs�B”H˜RœXÔ&Ð&Ô'Ø„Jˆs�B”H˜RœXÔ&Ð&Ô'Øð	ô!Ð ð ð ð ñ ð Ø„Jˆs�B”H˜RœWÔ%Ð%Ô&Ø„Jˆs�B”H˜RœWÔ%Ð%Ô&ð(ô€ð ð ð ñ ð 3;°"´(¸1ÀBÄGÐ2LÑ2LÔ2L€Ð LÐ LÐ LÑ Lð €Ð Ð Ð Ñ ð$ð $ð $ð $ð0bð bð bð bð 8&ð 8&ð 8&ð 8&ðvQð Qð Qð Qð@79ð 79ð 79ð 79ðt2Bð 2Bð 2Bð 2BðjYð Yð Yð Yð2ð ð ð ð:6ð 6ð 6ð 6ðr/^ð /^ð /^ð /^ðd-ð -ð -ð -ðf Øð	]ð ]ð ]ð ]ð ]ð@ð ð ð ðð ð ð ðDð ð ð ð ð r$   