§
    ­¸jó ã                  óÞ  — U d 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
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mZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlm Z m!Z!m"Z"m#Z#m$Z$ ddl%m&Z&  e&¦   «         Z'dZ(dZ)dZ*eege+eej,                 eej,                 f         f         Z-ddiZ.de/d<   ddiZ0de/d<    e	e-e¦  «        ZdZ1dZ2 G d„ de¦  «        Z3 G d„ dej4        ¦  «        Z5d#d"„Z6dS )$zFModules to compute the matching cost and solve the corresponding LSAP.é    )Úannotations)ÚCallableÚMapping)ÚAnyÚ
NamedTupleÚcastN)ÚNDArray©Úlinear_sum_assignment)ÚTensorÚnn)Úpad_sequence)Ú_assignment)Úcompute_keypoint_matching_cost)Úpoint_sample)Úbatch_dice_lossÚbatch_sigmoid_ce_lossÚbox_cxcywh_to_xyxyÚgeneralized_box_iouÚpairwise_box_l1_cost)Ú
get_loggerg      ð?g       @i0W ÚdynamicTúdict[str, Any]Ú_L1_COST_COMPILE_KWARGSztriton.cudagraphsFÚ_L1_COST_COMPILE_OPTIONSg     ˆÃ@iÀ c                  óF   — e Zd ZU dZded<   ded<   ded<   ded	<   d
ed<   dS )Ú_TargetSideSafetyuë  A precomputed compact-path target-side safety result from
    :meth:`HungarianMatcher._precompute_target_side_safety`.

    Tied to the ``targets`` list object (by identity, not equality â€” the ``targets`` this reflects
    can only be the exact object it was computed from; a different batch that happens to build an
    equal-looking list is not the same targets) and to the ``pred_boxes`` dtype/device and
    ``num_classes`` it was computed against, so :meth:`HungarianMatcher._detection_inputs_are_safe`
    can verify those still match the current call before reusing ``safe``, falling back to a fresh
    computation otherwise. Object identity distinguishes one step's targets list from another's â€”
    dtype/device/``num_classes`` stay constant for an entire training run, so checking only those
    would let a value computed for one step's targets be silently reused for a different step's â€”
    but it cannot detect in-place mutation of the same list's contents between precompute and use.
    Callers must not mutate ``targets`` after precomputing against it.

    Attributes:
        safe: Unsynced 0-d bool Tensor â€” whether the target-side safety sweep passed.
        targets: The exact targets list object this was computed from (identity-checked on reuse).
        pred_boxes_dtype: dtype of the ``pred_boxes`` this was computed against.
        pred_boxes_device: Device of the ``pred_boxes`` this was computed against.
        num_classes: Number of classes this was computed against.
    r   Úsafeúlist[dict[str, Any]]Útargetsútorch.dtypeÚpred_boxes_dtypeútorch.deviceÚpred_boxes_deviceÚintÚnum_classesN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__© ó    úe/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/models/matcher.pyr   r   \   sW   € € € € € € ðð ð, €L€L�LØ!Ð!Ð!Ñ!Ø!Ð!Ð!Ñ!Ø#Ð#Ð#Ñ#ØÐÐÑÐÐr-   r   c                  óì  ‡ — e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 dJdKˆ fd„ZdLdMd„ZdNd!„ZdOˆ fd#„ZedPd&„¦   «         Z	dQd(„Z
edRd0„¦   «         ZedSd2„¦   «         ZedSd3„¦   «         ZedTd4„¦   «         ZedSd5„¦   «         Z ej        ¦   «         dUd7„¦   «         Ze	 dLdVd9„¦   «         Zdd:œdWd<„ZdXd?„Z ej        ¦   «         	 	 dYdZdB„¦   «         Zed[dF„¦   «         Zd\dH„Z ej        ¦   «         	 	 dYd]dI„¦   «         Zˆ xZS )^ÚHungarianMatchera,  This class computes an assignment between the targets and the predictions of the network For efficiency reasons,
    the targets don't include the no_object.

    Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the
    best predictions, while the others are un-matched (and thus treated as non-objects).

    Note:
        The focal loss exponent ``gamma`` is fixed at ``_FOCAL_LOSS_GAMMA`` (2.0) and is not
        configurable. Only ``focal_alpha`` can be adjusted at construction time.
    é   ç      Ð?Fé   Nç        Ú
cost_classÚfloatÚ	cost_bboxÚ	cost_giouÚfocal_alphaÚuse_pos_onlyÚboolÚuse_position_modulated_costÚmask_point_sample_ratior%   Úcost_mask_ceÚcost_mask_diceÚnum_keypoints_per_classúlist[int] | NoneÚkeypoint_l1_loss_coefÚkeypoint_findable_loss_coefÚkeypoint_visible_loss_coefÚkeypoint_nll_loss_coefc                ód  •— t          ¦   «                              ¦   «          || _        || _        || _        |dk    s|dk    s|dk    s
J d¦   «         ‚|| _        || _        || _        |	| _        |
pg | _	        || _
        || _        || _        || _        d| _        d| _        i | _        d| _        dS )a  Creates the matcher.

        Args:
            cost_class: Relative weight of the classification error in the matching cost.
            cost_bbox: Relative weight of the L1 error of the bounding box coordinates.
            cost_giou: Relative weight of the GIoU loss of the bounding box.
            focal_alpha: Alpha parameter for focal loss used in the classification cost.
            use_pos_only: Reserved for future use; currently has no effect.
            use_position_modulated_cost: Reserved for future use; currently has no effect.
            mask_point_sample_ratio: Downsampling ratio for mask point sampling.
            cost_mask_ce: Relative weight of the binary cross-entropy mask cost.
            cost_mask_dice: Relative weight of the Dice mask cost.
        r   zall costs can't be 0FN)ÚsuperÚ__init__r5   r7   r8   r9   r=   r>   r?   r@   rB   rC   rD   rE   Ú_warned_non_finite_costsÚ_compile_l1_costÚ_l1_cost_compile_optionsÚ_compiled_l1_cost)Úselfr5   r7   r8   r9   r:   r<   r=   r>   r?   r@   rB   rC   rD   rE   Ú	__class__s                  €r.   rH   zHungarianMatcher.__init__†   sÌ   ø€ õ< 	‰Œ×ÒÑÔÐØ$ˆŒØ"ˆŒØ"ˆŒØ˜QŠˆ )¨q¢. .°IÀ²N°N°NÐDZ±N´NÐBØ&ˆÔØ'>ˆÔ$Ø(ˆÔØ,ˆÔØ'>Ð'DÀ"ˆÔ$Ø%:ˆÔ"Ø+FˆÔ(Ø*DˆÔ'Ø&<ˆÔ#Ø(-ˆÔ%Ø %ˆÔØ8:ˆÔ%ð MQˆÔÐÐr-   Úcompile_optionsúMapping[str, Any] | NoneÚreturnÚNonec                óF   — d| _         i |pi ¥t          ¥| _        d| _        dS )aú  Compile the L1 box cost with ``torch.compile`` on its first use in the executing process.

        Only the request is recorded here. The compiled callable is built lazily by whichever process runs
        the matcher, because a compiled function wrapper cannot be pickled: building it eagerly would break
        the ``ddp_spawn``/``ddp_notebook`` launchers, which pickle the trainer -- and with it the criterion
        and this matcher -- into every worker. Mixed-dtype box pairs keep the eager helper regardless, so
        ``torch.cdist``'s dtype rejection is preserved.

        Args:
            compile_options: Inductor options forwarded to ``torch.compile``; ``triton.cudagraphs`` is always
                forced off on top of them (see ``_L1_COST_COMPILE_OPTIONS``).

        Examples:
            >>> matcher = HungarianMatcher()
            >>> matcher.enable_compiled_l1_cost({"triton.cudagraphs": True})
            >>> matcher._l1_cost_compile_options
            {'triton.cudagraphs': False}
        TN)rJ   r   rK   rL   )rM   rO   s     r.   Úenable_compiled_l1_costz(HungarianMatcher.enable_compiled_l1_cost¹   s2   € ð& !%ˆÔØ(_¨OÐ,A¸rÐ(_ÕF^Ð(_ˆÔ%Ø!%ˆÔÐÐr-   ú"Callable[[Tensor, Tensor], Tensor]c                óŽ   — | j         st          S | j        €*t          j        t          fi t
          ¤d| j        i¤Ž| _        | j        S )zXReturn the L1 box cost callable, compiling it on first use once compilation was enabled.NÚoptions)rJ   r   rL   ÚtorchÚcompiler   rK   )rM   s    r.   Ú_resolve_l1_costz!HungarianMatcher._resolve_l1_costÐ   s`   € àÔ$ð 	(Ý'Ð'ØÔ!Ð)Ý%*¤]Ý$ð&ð &Ý(?ð&ð &ØIMÔIfð&ð &ð &ˆDÔ"ð Ô%Ð%r-   r   c                óT   •— t          ¦   «                              ¦   «         }i |¥ddi¥S )zKPickle the compilation request but never the per-process compiled callable.rL   N)rG   Ú__getstate__)rM   ÚstaterN   s     €r.   r\   zHungarianMatcher.__getstate__Ú   s0   ø€ õ !&¡¤× 4Ò 4Ñ 6Ô 6ˆØ3�%Ð3Ð,¨dÐ3Ð3Ð3r-   Úcost_matrixr   c                óL  — t          j        | ¦  «        }|                     ¦   «         r| S t          j        | j        ¦  «        }|                     ¦   «         r˜| |         }|                     ¦   «         }||                     ¦   «                              ¦   «         z   t          z   }t          j        |¦  «        s|  	                    |j        ¦  «        }n6t          j
        ||j        ¬¦  «        }n|  	                    |j        ¦  «        }|                      ¦   «         }||| <   |S )aô  Replace non-finite cost entries with a large finite sentinel.

        >>> HungarianMatcher._sanitize_cost_matrix(
        ...     torch.tensor([[1.0, float("nan")], [float("inf"), -2.0]])
        ... ).tolist()
        [[1.0, 4.0], [4.0, -2.0]]

        Args:
            cost_matrix: Cost matrix to sanitize before Hungarian assignment.

        Returns:
            Cost matrix with all non-finite entries replaced by a finite sentinel that is no smaller than any valid
            entry.
        )Úmax)rX   ÚisfiniteÚallÚfinfoÚdtypeÚanyr`   ÚabsÚ_SANITIZED_COST_MARGINÚ
new_tensorÚclampÚclone)r^   Úfinite_maskÚ
dtype_infoÚfinite_costsÚmax_costÚreplacement_costÚsanitized_cost_matrixs          r.   Ú_sanitize_cost_matrixz&HungarianMatcher._sanitize_cost_matrixà   s  € õ  ”n [Ñ1Ô1ˆØ�?Š?ÑÔð 	ØÐå”[ Ô!2Ñ3Ô3ˆ
Ø�?Š?ÑÔð 	FØ& {Ô3ˆLØ#×'Ò'Ñ)Ô)ˆHð  (¨,×*:Ò*:Ñ*<Ô*<×*@Ò*@Ñ*BÔ*BÑBÕE[Ñ[Ðå”>Ð"2Ñ3Ô3ð UØ#.×#9Ò#9¸*¼.Ñ#IÔ#IÐ Ð å#(¤;Ð/?ÀZÄ^Ð#TÑ#TÔ#TÐ Ð ð  +×5Ò5°j´nÑEÔEÐà +× 1Ò 1Ñ 3Ô 3ÐØ.>Ð˜{˜lÑ+Ø$Ð$r-   Úlogitsc                óÚ   — | j         }t          }|                     ¦   «         }d|z
  ||z  z  t          j        | ¦  «         z  }|d|z
  |z  z  t          j        |¦  «         z  }||z
  }|S )a�  Focal-loss classification cost for logits already gathered at the target classes they are scored against.

        Every operation is elementwise, so the leading dimensions are free: the compact path passes
        ``[bs, num_queries, max_targets]`` and the full path ``[bs * num_queries, total_targets]``.

        >>> HungarianMatcher(focal_alpha=0.25)._focal_classification_cost(torch.zeros(1, 2)).tolist()
        [[-0.08664339780807495, -0.08664339780807495]]

        Args:
            logits: Classification logits already selected at their target classes.

        Returns:
            Focal classification cost, same shape as ``logits``.
        r1   )r9   Ú_FOCAL_LOSS_GAMMAÚsigmoidÚFÚ
logsigmoid)rM   rr   ÚalphaÚgammaÚprobabilitiesÚnegative_costÚpositive_costÚcosts           r.   Ú_focal_classification_costz+HungarianMatcher._focal_classification_cost  s}   € ð$ Ô ˆÝ!ˆØŸšÑ(Ô(ˆØ˜U™ }°eÑ';Ñ<ÅÄÈvÈgÑAVÔAVÐ@VÑWˆØ ! mÑ"3¸Ñ!=Ñ>Å1Ä<ÐPVÑCWÔCWÐBWÑXˆØ$ }Ñ4ˆØˆr-   r"   r!   r$   r#   r&   r    r   c                óp  — |d         d         j         }|D ]v}|d         j         | k    s|d         j        |k    rt          j        d|¬¦  «        c S |d         j        |k    s|d         j         |k    rt          j        d|¬¦  «        c S Œwg }t          j        | ¦  «        j        dz  dz  }t          j        d„ |D ¦   «         ¦  «        }|                     t          j        |¦  «         	                    ¦   «         | 
                    ¦   «         |k     	                    ¦   «         z  ¦  «         t          j        d	„ |D ¦   «         ¦  «        }	|                     |	dk     	                    ¦   «         |	|k      	                    ¦   «         z  ¦  «         t          j        |¦  «         	                    ¦   «         S )
u“  Return whether the *target*-side half of the compact-path safety gate passes.

        Split out of :meth:`_detection_inputs_are_safe` because this half depends only on
        ``targets`` plus ``pred_boxes_dtype``/``pred_boxes_device``/``num_classes`` â€” all identical
        across every one of the (final layer + aux layers + enc layer) calls
        ``SetCriterion.forward`` makes with the same ``targets`` in one training step â€” so
        :meth:`_precompute_target_side_safety` can compute it once per step instead of once per call.

        Args:
            pred_boxes_dtype: dtype of the predictions' box tensor.
            pred_boxes_device: Device of the predictions' box tensor.
            num_classes: Number of classes the predictions' logits cover.
            targets: Per-image target dicts containing ``boxes`` and ``labels``.

        Returns:
            An *unsynced* 0-d bool Tensor, false if any target's box dtype or device disagrees with
            the predictions', if any target's label device disagrees with the predictions', if any
            target box coordinate is non-finite or exceeds ``coordinate_limit``, or if any label
            falls outside ``[0, num_classes)``; true otherwise. Deliberately left as a Tensor rather
            than cast to ``bool`` so :meth:`_detection_inputs_are_safe` can fuse it with its
            pred-side check into a single host-device sync.
        r   ÚlabelsÚboxesF©Údeviceç      à?r3   c                ó   — g | ]
}|d          ‘ŒS ©r�   r,   ©Ú.0Útargets     r.   ú
<listcomp>z:HungarianMatcher._target_side_precheck.<locals>.<listcomp>V  s   € Ð!HÐ!HÐ!H°f &¨¤/Ð!HÐ!HÐ!Hr-   c                ó   — g | ]
}|d          ‘ŒS ©r€   r,   r‡   s     r.   rŠ   z:HungarianMatcher._target_side_precheck.<locals>.<listcomp>^  s   € Ð"JÐ"JÐ"J¸ 6¨(Ô#3Ð"JÐ"JÐ"Jr-   )rd   rƒ   rX   Útensorrc   r`   ÚcatÚappendra   rb   rf   Ústack)
r"   r$   r&   r    Útarget_label_dtyper‰   ÚchecksÚcoordinate_limitÚtarget_boxesÚtarget_labelss
             r.   Ú_target_side_precheckz&HungarianMatcher._target_side_precheck"  s¶  € ðF % QœZ¨Ô1Ô7ÐØð 	Eð 	EˆFØ�gŒÔ$Ð(8Ò8Ð8¸FÀ7¼OÔ<RÐVgÒ<gÐ<gÝ”| EÐ2CÐDÑDÔDÐDÐDÐDØ�hÔÔ&Ð*;Ò;Ð;¸vÀhÔ?OÔ?UÐYkÒ?kÐ?kÝ”| EÐ2CÐDÑDÔDÐDÐDÐDð @lð  "ˆå œ;Ð'7Ñ8Ô8Ô<ÀÑCÀbÑHÐÝ”yÐ!HÐ!HÀÐ!HÑ!HÔ!HÑIÔIˆØ�Š•e”n \Ñ2Ô2×6Ò6Ñ8Ô8¸L×<LÒ<LÑ<NÔ<NÐRbÒ<b×;gÒ;gÑ;iÔ;iÑiÑjÔjÐjõ œ	Ð"JÐ"JÀ'Ð"JÑ"JÔ"JÑKÔKˆØ�Š�}¨Ò)×.Ò.Ñ0Ô0°MÀKÒ4O×3TÒ3TÑ3VÔ3VÑVÑWÔWÐWÝŒ{˜6Ñ"Ô"×&Ò&Ñ(Ô(Ð(r-   Úoutputsc                ób   — | d         j         d         dk    od|d         vod| v o	d|d         v  S )aé  Return whether the compact path could apply at all, before the input-safety gate is consulted.

        Sole owner of the compact path's routing precondition, so callers that want to skip work the
        compact path would never use (``SetCriterion.forward`` precomputing the target-side safety
        sweep) test the same rule :meth:`forward` routes on instead of reimplementing it.

        >>> outputs = {"pred_logits": torch.zeros(2, 3, 4)}
        >>> HungarianMatcher._compact_path_applicable(outputs, [{}, {}])
        True
        >>> HungarianMatcher._compact_path_applicable({"pred_logits": torch.zeros(1, 3, 4)}, [{}])
        False

        Args:
            outputs: Model outputs containing at least ``pred_logits``.
            targets: Per-image target dicts.

        Returns:
            ``True`` only for a batch of more than one image with neither mask nor keypoint targets;
            every other batch is matched by the full cartesian path regardless of input safety.
        Úpred_logitsr   r1   ÚmasksÚpred_keypointsÚ	keypoints©Úshape©r—   r    s     r.   Ú_compact_path_applicablez)HungarianMatcher._compact_path_applicableb  sO   € ð. �MÔ"Ô(¨Ô+¨aÒ/ð PØ˜w qœzÐ)ðPà%¨Ð0ÐN°[ÀGÈAÄJÐ5NÐOð	
r-   c                óv   — | d         j         d         dk    o"d|d         v od| v o	d|d         v  o	d|d         vS )u  Return whether the compact-class/bbox/GIoU hybrid could apply to a batch WITH mask targets.

        Mirrors :meth:`_compact_path_applicable`'s routing precondition for the opposite case: a
        batch that has mask targets instead of none. Still requires more than one image (the same
        regression :meth:`_compact_path_applicable` already guards against applies here identically â€”
        the compact route's fixed overhead cannot be justified at ``batch_size == 1``) and still
        excludes keypoints, an untested combination with masks. Also excludes fixed-row target
        padding (``"valid"`` in ``targets[0]``, from XLA's target padding, see ``pack_targets``):
        that mechanism's per-column sentinel is verified only for the fully compact detection matrix
        (:meth:`_compute_compact_detection_cost_matrix`'s own ``"valid"`` handling), and a mask cost
        is not necessarily constant across queries for a padded (invalid) target column the way the
        sentinel assumes, so the interaction is unverified â€” route those batches to the full
        cartesian path instead, exactly as :meth:`_compact_path_applicable` already routes masks and
        keypoints away from the pure-detection compact path for the same kind of reason.

        >>> outputs = {"pred_logits": torch.zeros(2, 3, 4)}
        >>> targets = [{"masks": torch.zeros(1, 8, 8)}, {"masks": torch.zeros(1, 8, 8)}]
        >>> HungarianMatcher._compact_mask_path_applicable(outputs, targets)
        True

        Args:
            outputs: Model outputs containing at least ``pred_logits``.
            targets: Per-image target dicts.

        Returns:
            ``True`` only for a batch of more than one image, with mask targets, no keypoint
            targets, and no fixed-row target padding.
        r™   r   r1   rš   r›   rœ   Úvalidr�   rŸ   s     r.   Ú_compact_mask_path_applicablez.HungarianMatcher._compact_mask_path_applicable~  s`   € ð> �MÔ"Ô(¨Ô+¨aÒ/ð *Ø˜7 1œ:Ð%ð*à%¨Ð0ÐN°[ÀGÈAÄJÐ5NÐOð*ð ˜w qœzÐ)ð		
r-   c                ó6   — t          | d         j        ¦  «        S )a‡  Return whether the masks-present compact route is measured on this device.

        >>> HungarianMatcher._mask_compact_device_supported({"pred_logits": torch.zeros(2, 3, 4)})
        False

        Args:
            outputs: Model outputs containing ``pred_logits``.

        Returns:
            ``True`` for CUDA tensors; other backends retain the established full-cartesian path.
        r™   )r;   Úis_cuda)r—   s    r.   Ú_mask_compact_device_supportedz/HungarianMatcher._mask_compact_device_supported£  s   € õ �G˜MÔ*Ô2Ñ3Ô3Ð3r-   c                óÌ   — | d         j         dd…         \  }}d„ |D ¦   «         }t          |d¬¦  «        }||z  t          |¦  «        |z
  z  }t          |t          k    ¦  «        S )aZ  Return whether this masks-present batch is large enough for the compact route to pay off.

        The compact route (``pad_sequence`` + gather + ``cdist``/vmapped GIoU,
        :meth:`_compute_compact_detection_cost_matrix`) has a roughly constant per-call fixed cost.
        Gate on the number of cross-image entries it avoids, not the compact matrix's own size: two
        batches can have the same ``batch_size * num_queries * max(sizes)`` while one has balanced
        target counts and the other has almost every target in one image, leaving little work to save.

        >>> outputs = {"pred_logits": torch.zeros(2, 4, 5)}
        >>> targets = [{"boxes": torch.zeros(1, 4)}, {"boxes": torch.zeros(1, 4)}]
        >>> HungarianMatcher._mask_compact_worth_it(outputs, targets)
        False

        Args:
            outputs: Model outputs containing at least ``pred_logits``.
            targets: Per-image target dicts containing ``boxes``.

        Returns:
            ``True`` when the number of avoided class/bbox/GIoU entries reaches
            :data:`_MASK_COMPACT_SAVED_ELEMENT_LIMIT`.
        r™   Né   c                ó8   — g | ]}t          |d          ¦  «        ‘ŒS r†   ©Úlenr‡   s     r.   rŠ   z;HungarianMatcher._mask_compact_worth_it.<locals>.<listcomp>Ê  ó$   € Ð<Ð<Ð<¨&•�V˜G”_Ñ%Ô%Ð<Ð<Ð<r-   r   )Údefault)rž   r`   Úsumr;   Ú!_MASK_COMPACT_SAVED_ELEMENT_LIMIT)r—   r    Ú
batch_sizeÚnum_queriesÚsizesÚmax_targetsÚsaved_elementss          r.   Ú_mask_compact_worth_itz'HungarianMatcher._mask_compact_worth_it²  sr   € ð. #*¨-Ô"8Ô">¸rÀ¸rÔ"BÑˆ
�KØ<Ð<°GÐ<Ñ<Ô<ˆÝ˜%¨Ð+Ñ+Ô+ˆØ# kÑ1µS¸±Z´ZÀ+Ñ5MÑNˆÝ�NÕ&GÒGÑHÔHÐHr-   ú_TargetSideSafety | Nonec                óp  — |                       ||¦  «        }|                      |¦  «        o+|                      ||¦  «        o|                      ||¦  «        }|s|sdS |d         }|d         j        d         }|                      |j        |j        ||¦  «        }t          |||j        |j        |¦  «        S )u¤  Precompute the compact-path safety gate's target-side sweep once, for reuse across the several
        :meth:`forward` calls ``SetCriterion.forward`` makes with the same ``targets`` (once per decoder layer, plus
        aux/enc outputs). Recomputing the target-side sweep on every one of those calls wastes ~47% of the gate's total
        cost on work that never changes within a step (measured on an RTX 4060: ~300-700us/step saved by caching it).

        Examples:
            >>> matcher = HungarianMatcher()
            >>> outputs = {
            ...     "pred_logits": torch.zeros(2, 3, 4),
            ...     "pred_boxes": torch.rand(2, 3, 4),
            ... }
            >>> targets = [
            ...     {"boxes": torch.rand(1, 4), "labels": torch.tensor([0])},
            ...     {"boxes": torch.rand(1, 4), "labels": torch.tensor([1])},
            ... ]
            >>> result = matcher._precompute_target_side_safety(outputs, targets)
            >>> bool(result.safe)  # .safe is an unsynced Tensor, so compare via bool() to sync it
            True

        Args:
            outputs: Any one of the step's outputs dicts (``pred_boxes``/``pred_logits`` share the
                same dtype/device/``num_classes`` across every layer of one forward pass, by
                construction); typically the final-layer output.
            targets: The step's targets, unchanged across every :meth:`forward` call it feeds.

        Returns:
            ``None`` when neither the detection-only compact path nor the CUDA masks-hybrid path can
            run for this batch, since :meth:`forward` then never reaches the safety gate and sweeping
            the targets would be pure overhead. Otherwise a :class:`_TargetSideSafety` to pass as
            :meth:`forward`'s ``target_side_safety`` argument. :meth:`forward` verifies the exact
            ``targets`` object (by identity) plus the dtype/device/``num_classes`` it was computed
            against still match the current call before trusting it, falling back to a fresh
            computation otherwise â€” reusing it never changes what :meth:`forward` returns, only how
            much redundant work it does to get there.
        NÚ
pred_boxesr™   éÿÿÿÿ)	r    r¦   r£   rµ   rž   r–   rd   rƒ   r   )rM   r—   r    Údetection_compact_applicableÚmask_compact_applicabler¸   r&   r   s           r.   Ú_precompute_target_side_safetyz/HungarianMatcher._precompute_target_side_safetyÏ  sÑ   € ðN (,×'DÒ'DÀWÈgÑ'VÔ'VÐ$à×/Ò/°Ñ8Ô8ð >Ø×2Ò2°7¸GÑDÔDð>à×+Ò+¨G°WÑ=Ô=ð 	 ð
 -ð 	Ð0Gð 	Ø�4Ø˜\Ô*ˆ
Ø˜mÔ,Ô2°2Ô6ˆØ×)Ò)¨*Ô*:¸JÔ<MÈ{Ð\cÑdÔdˆÝ   w°
Ô0@À*ÔBSÐU`ÑaÔaÐar-   Útarget_side_safetyc                óV  — | d         }| d         j         d         }|�<|j        |u r3|j        |j        k    r#|j        |j        k    r|j        |k    r|j        }n't           	                    |j        |j        ||¦  «        }t          j        |j        ¦  «        j        dz  dz  }t          j        |¦  «                             ¦   «         |                     ¦   «         |k                         ¦   «         z  }t!          t          j        ||g¦  «                             ¦   «         ¦  «        S )aò  Return whether the compact path can preserve the full path's finite-cost behavior.

        Args:
            outputs: Model outputs containing ``pred_boxes`` and ``pred_logits``.
            targets: Per-image target dicts containing ``boxes`` and ``labels``.
            target_side_safety: An optional precomputed result from
                :meth:`_precompute_target_side_safety`, reused instead of recomputing the
                target-side sweep from scratch when it was computed from this exact ``targets``
                object (by identity) and its dtype/device/``num_classes`` still match this call's
                ``outputs``.

        Returns:
            ``False`` if any target's box dtype or device disagrees with the predictions', if any
            target's label device disagrees with the predictions', if any box coordinate (predicted or
            target) is non-finite or exceeds ``coordinate_limit``, or if any label falls outside
            ``[0, num_classes)``; ``True`` otherwise. Any ``False`` routes the batch to the full path.
            Both halves stay unsynced Tensors until one final ``bool()`` below, so the whole gate
            costs exactly one host-device sync per call however the target-side half was obtained.
        r¸   r™   r¹   Nr„   r3   )rž   r    r"   rd   r$   rƒ   r&   r   r0   r–   rX   rc   r`   ra   rb   rf   r;   r�   )r—   r    r½   r¸   r&   Útarget_side_safer“   Úpred_side_safes           r.   Ú_detection_inputs_are_safez+HungarianMatcher._detection_inputs_are_safe  s  € ð2 ˜\Ô*ˆ
Ø˜mÔ,Ô2°2Ô6ˆàÐ*Ø"Ô*¨gÐ5Ð5Ø"Ô3°zÔ7GÒGÐGØ"Ô4¸
Ô8IÒIÐIØ"Ô.°+Ò=Ð=à1Ô6ÐÐå/×EÒEØÔ  *Ô"3°[À'ñ ô  Ðõ !œ; zÔ'7Ñ8Ô8Ô<ÀÑCÀbÑHÐÝœ¨
Ñ3Ô3×7Ò7Ñ9Ô9¸Z¿^º^Ñ=MÔ=MÐQaÒ=a×<fÒ<fÑ<hÔ<hÑhˆõ
 •E”KÐ!1°>Ð BÑCÔC×GÒGÑIÔIÑJÔJÐJr-   ©Úclamp_target_labelsrÃ   c               ó  ‡— |d         j         dd…         \  }}d„ |D ¦   «         }t          d„ |D ¦   «         d¬¦  «        }t          d„ |D ¦   «         d¬¦  «        }|j         d	         }	|r*|                     d
|d         j         d         d	z
  ¦  «        }|dd…ddd…f                              |||	¦  «        }
t	          j        |d         d|
¦  «        }|                      |¦  «        } |                      ¦   «         |d         |¦  «        } t	          j        t          ¦  «        t          |d         ¦  «        t          |¦  «        ¦  «         }| j        |z  | j        |z  z   | j        |z  z   Šd|d
         v r_t	          j        d„ |D ¦   «         ¦  «                             ‰j        ¦  «        }‰                     |dd…ddd…f          t$          ¦  «        Št	          j        ˆfd„t)          |¦  «        D ¦   «         d¬¦  «        S )uz  Compute same-image detection costs with targets padded only to the batch maximum.

        Args:
            outputs: Model outputs containing ``pred_boxes`` and ``pred_logits``.
            targets: Per-image target dicts containing ``boxes`` and ``labels``.
            clamp_target_labels: If True, clamp target label ids into ``[0, num_classes)`` before
                the gather so an out-of-range label cannot raise; used only by the batched fast
                path, which defers the safety decision until after the single host transfer (see
                the ``clamp_target_labels`` block below).

        Returns:
            Cost matrix of shape ``[num_queries, sum(sizes)]``, where ``sizes`` is each image's real
            (unpadded) target count. The class, bbox, and GIoU terms are computed on tensors padded to
            ``max(sizes)`` for the gather/cdist/GIoU ops, but the padding columns are dropped per-image
            (``[:, :size]``) before the per-image slices are concatenated along ``dim=-1`` â€” the
            returned tensor never carries the padded ``max(sizes)`` width or a leading batch dimension.
        r™   Nr¨   c                ó8   — g | ]}t          |d          ¦  «        ‘ŒS r†   rª   r‡   s     r.   rŠ   zKHungarianMatcher._compute_compact_detection_cost_matrix.<locals>.<listcomp>W  r¬   r-   c                ó   — g | ]
}|d          ‘ŒS rŒ   r,   r‡   s     r.   rŠ   zKHungarianMatcher._compute_compact_detection_cost_matrix.<locals>.<listcomp>X  s   € Ð)QÐ)QÐ)Q¸v¨&°Ô*:Ð)QÐ)QÐ)Qr-   T)Úbatch_firstc                ó   — g | ]
}|d          ‘ŒS r†   r,   r‡   s     r.   rŠ   zKHungarianMatcher._compute_compact_detection_cost_matrix.<locals>.<listcomp>Y  s   € Ð+RÐ+RÐ+RÀ¨F°7¬OÐ+RÐ+RÐ+Rr-   r1   r   r¹   r¸   r¢   c                ó   — g | ]
}|d          ‘ŒS ©r¢   r,   r‡   s     r.   rŠ   zKHungarianMatcher._compute_compact_detection_cost_matrix.<locals>.<listcomp>s  s   € Ð GÐ GÐ G°V ¨¤Ð GÐ GÐ Gr-   c                ó4   •— g | ]\  }}‰|d d …d |…f         ‘ŒS ©Nr,   )rˆ   ÚindexÚsizeÚpadded_cost_matrixs      €r.   rŠ   zKHungarianMatcher._compute_compact_detection_cost_matrix.<locals>.<listcomp>v  s1   ø€ ÐUÐUÐU±[°U¸DÐ  q q q¨%¨4¨% Ô0ÐUÐUÐUr-   ©Údim)rž   r   ri   ÚexpandrX   Úgatherr~   rZ   Úvmapr   r   r7   r5   r8   r�   Útorƒ   Úmasked_fillÚ_PADDED_TARGET_COSTrŽ   Ú	enumerate)rM   r—   r    rÃ   r°   r±   r²   Úpadded_target_idsÚpadded_target_boxesr³   Úgather_indexÚtarget_logitsÚ
class_costÚ	bbox_costÚ	giou_costr¢   rÏ   s                   @r.   Ú&_compute_compact_detection_cost_matrixz7HungarianMatcher._compute_compact_detection_cost_matrix>  sG  ø€ ð0 #*¨-Ô"8Ô">¸rÀ¸rÔ"BÑˆ
�KØ<Ð<°GÐ<Ñ<Ô<ˆÝ(Ð)QÐ)QÈÐ)QÑ)QÔ)QÐ_cÐdÑdÔdÐÝ*Ð+RÐ+RÈ'Ð+RÑ+RÔ+RÐ`dÐeÑeÔeÐØ'Ô-¨aÔ0ˆàð 	að !2× 7Ò 7¸¸7À=Ô;QÔ;WÐXZÔ;[Ð^_Ñ;_Ñ `Ô `Ðà(¨¨¨¨D°!°!°!¨Ô4×;Ò;¸JÈÐU`ÑaÔaˆÝœ W¨]Ô%;¸QÀÑMÔMˆØ×4Ò4°]ÑCÔCˆ
à+�D×)Ò)Ñ+Ô+¨G°LÔ,AÐCVÑWÔWˆ	Ø4•U”ZÕ 3Ñ4Ô4Ý˜w |Ô4Ñ5Ô5ÝÐ2Ñ3Ô3ñ
ô 
ð 
ˆ	ð "œ^¨iÑ7¸$¼/ÈJÑ:VÑVÐY]ÔYgÐjsÑYsÑsÐØ�g˜a”jÐ Ð õ ”KÐ GÐ G¸wÐ GÑ GÔ GÑHÔH×KÒKÐL^ÔLeÑfÔfˆEØ!3×!?Ò!?ÀÀqÀqÀqÈ$ÐPQÐPQÐPQÀzÔARÐ@RÕTgÑ!hÔ!hÐÝŒyØUÐUÐUÐUÅIÈeÑDTÔDTÐUÑUÔUØð
ñ 
ô 
ð 	
r-   Úoutputs_listúlist[Tensor]c                óT  ‡‡— t          j        d„ |D ¦   «         ¦  «        t          j        d„ |D ¦   «         ¦  «        dœ}|                      ||t          |¦  «        z  d¬¦  «        Št	          d„ |D ¦   «         ¦  «        Šˆˆfd„t          d‰j        d	         ‰¦  «        D ¦   «         S )
a\  Compute every layer's compact detection cost matrix in one stacked pass.

        Folds the layer dimension into the batch dimension and reuses
        :meth:`_compute_compact_detection_cost_matrix` on the concatenation, so target padding, the
        class gather, ``cdist``, and the vmapped GIoU each launch once for all layers instead of
        once per layer. The concatenated call sees ``len(outputs_list) * len(targets)`` images
        whose per-image target counts repeat layer-major, so its output columns are each layer's
        compact matrix laid side by side. Slicing them apart reproduces the per-layer results within
        floating-point tolerance; only the kernel-launch count changes.

        Callers must guarantee every layer shares the prediction query count (dtype, device, and
        class count are already enforced by :meth:`_match_many`). Target labels are clamped exactly
        as :meth:`_match_many`'s per-layer calls do.

        Examples:
            >>> matcher = HungarianMatcher()
            >>> outputs = {"pred_logits": torch.zeros(2, 4, 5), "pred_boxes": torch.rand(2, 4, 4)}
            >>> targets = [
            ...     {"boxes": torch.rand(1, 4), "labels": torch.tensor([0])},
            ...     {"boxes": torch.rand(2, 4), "labels": torch.tensor([1, 2])},
            ... ]
            >>> [m.shape for m in matcher._compute_stacked_compact_cost_matrices([outputs, outputs], targets)]
            [torch.Size([4, 3]), torch.Size([4, 3])]

        Args:
            outputs_list: Per-layer detection outputs with identical ``pred_logits``/``pred_boxes``
                shapes.
            targets: Per-image target dicts shared by every layer.

        Returns:
            One ``[num_queries, sum(sizes)]`` cost matrix per layer, in ``outputs_list`` order,
            each a column slice of the single stacked computation.
        c                ó   — g | ]
}|d          ‘ŒS )r™   r,   ©rˆ   r—   s     r.   rŠ   zKHungarianMatcher._compute_stacked_compact_cost_matrices.<locals>.<listcomp>Ÿ  s   € Ð%YÐ%YÐ%YÀ g¨mÔ&<Ð%YÐ%YÐ%Yr-   c                ó   — g | ]
}|d          ‘ŒS )r¸   r,   rå   s     r.   rŠ   zKHungarianMatcher._compute_stacked_compact_cost_matrices.<locals>.<listcomp>   s   € Ð$WÐ$WÐ$W¸w W¨\Ô%:Ð$WÐ$WÐ$Wr-   )r™   r¸   TrÂ   c              3  ó@   K  — | ]}t          |d          ¦  «        V — ŒdS )r�   Nrª   r‡   s     r.   ú	<genexpr>zJHungarianMatcher._compute_stacked_compact_cost_matrices.<locals>.<genexpr>¥  s.   è è € ÐGÐG°V�C  w¤Ñ0Ô0ÐGÐGÐGÐGÐGÐGr-   c                ó2   •— g | ]}‰d d …||‰z   …f         ‘ŒS rÌ   r,   )rˆ   ÚoffsetÚstacked_matrixÚtotal_targetss     €€r.   rŠ   zKHungarianMatcher._compute_stacked_compact_cost_matrices.<locals>.<listcomp>¦  sA   ø€ ð 
ð 
ð 
àð ˜1˜1˜1˜f v°Ñ'=Ð=Ð=Ô>ð
ð 
ð 
r-   r   r1   )rX   rŽ   rà   r«   r®   Úrangerž   )rM   rá   r    Ústacked_outputsrë   rì   s       @@r.   Ú&_compute_stacked_compact_cost_matricesz7HungarianMatcher._compute_stacked_compact_cost_matricesz  sÞ   øø€ õJ !œ9Ð%YÐ%YÈLÐ%YÑ%YÔ%YÑZÔZÝœ)Ð$WÐ$WÈ,Ð$WÑ$WÔ$WÑXÔXð
ð 
ˆð ×DÒDØ˜W¥s¨<Ñ'8Ô'8Ñ8Èdð Eñ 
ô 
ˆõ ÐGÐG¸wÐGÑGÔGÑGÔGˆð
ð 
ð 
ð 
ð 
å  >Ô#7¸Ô#:¸MÑJÔJð
ñ 
ô 
ð 	
r-   Ú
group_detrú(list[list[tuple[Tensor, Tensor]]] | Nonec                ó²  ‡ ‡‡‡‡‡‡— t          |¦  «        dk     st          ˆ ˆfd„|D ¦   «         ¦  «        sdS |d         d         Š|d         d         Š‰j        d         Št          ˆˆˆfd„|d	d…         D ¦   «         ¦  «        rdS t          ˆˆfd
„‰D ¦   «         ¦  «        rdS |�<|j        ‰u r3|j        ‰j        k    r#|j        ‰j        k    r|j	        ‰k    r|j
        }n"‰                      ‰j        ‰j        ‰‰¦  «        }d„ ‰D ¦   «         Št          ‰¦  «        }|dk    rdS t          j        ‰j        ¦  «        j        dz  dz  }d„ |D ¦   «         }d}	t          |¦  «        d	k    rkt          |¦  «        t          ‰¦  «        z  t!          t#          |¦  «        ¦  «        z  t          ‰¦  «        z  t$          k    r‰                      |‰¦  «        }	g }
|g}t)          |¦  «        D �]\  }}|d         }|                     t          j        |¦  «                             ¦   «         |                     ¦   «         |k                         ¦   «         z  ¦  «         |	€+‰                      |‰d¬¦  «                             ¦   «         }n|	|                              ¦   «         }|
                     |¦  «         |                     t          j        |¦  «                             ¦   «         ¦  «         �Œ	t5          t          j        |¦  «                             ¦   «         ¦  «        sdS ‰j        rt;          j        |
‰‰¦  «        S ˆˆ ˆfd„|
D ¦   «         S )aI  Solve every compatible detection layer in one batched pass, or decline to preserve fallback behavior.

        This private fast path is used only by ``SetCriterion`` for final, auxiliary, and encoder outputs from one
        training step. It leaves unusual input shapes and unsafe values to :meth:`forward`, whose full-cartesian
        fallback carries the established error and non-finite-cost behavior.

        Every layer's cost matrix is built and left on its own device, then all of them are handed to
        :func:`~rfdetr.models._assignment.assign_many_bucketed`, which groups same-shaped problems across layers so the
        solver sees far more work per call than any single layer could supply.

        Args:
            outputs_list: Detection outputs for the final, auxiliary, and encoder layers to match
                together.
            targets: Per-image target dicts shared by every layer in ``outputs_list``.
            group_detr: Number of query groups to solve independently within each layer.
            target_side_safety: Optional precomputed target-side safety result for these exact
                ``targets`` and the reference layer's box dtype, device, and class count.

        Returns:
            ``list[list[tuple[Tensor, Tensor]]] | None`` containing per-image assignments for each
            layer, or ``None``. ``None`` is the decline contract: the caller MUST execute the
            per-layer fallback. A decline is all-or-nothing and can only be detected after every
            layer's cost matrix has been built. The reduced safety gate performs one explicit host
            read; solver internals may synchronize separately, so a single layer with non-finite
            ``pred_boxes`` or a failed safety flag discards the work done for all of them and pays
            for the sequential redo on top.
        r¨   c              3  óD   •K  — | ]}‰                      |‰¦  «        V — Œd S rÌ   )r    )rˆ   r—   rM   r    s     €€r.   rè   z/HungarianMatcher._match_many.<locals>.<genexpr>Î  sD   øè è € ð ,
ð ,
Ø@GˆD×)Ò)¨'°7Ñ;Ô;ð,
ð ,
ð ,
ð ,
ð ,
ð ,
r-   Nr   r¸   r™   r¹   c              3  óö   •K  — | ]s}|d          j         ‰j         k    pX|d          j        ‰j        k    pB|d         j         ‰j         k    p,|d         j        ‰j        k    p|d         j        d         ‰k    V — ŒtdS )r¸   r™   r¹   N)rd   rƒ   rž   )rˆ   r—   Úreference_boxesÚreference_classesÚreference_logitss     €€€r.   rè   z/HungarianMatcher._match_many.<locals>.<genexpr>Ö  sµ   øè è € ð 
ð 
ð ð �LÔ!Ô'¨?Ô+@Ò@ð EØ�|Ô$Ô+¨Ô/EÒEðEà�}Ô%Ô+Ð/?Ô/EÒEðEð �}Ô%Ô,°Ô0FÒFðEð �}Ô%Ô+¨BÔ/Ð3DÒDð
ð 
ð 
ð 
ð 
ð 
r-   r1   c              3  óà   •K  — | ]h}|d          j         ‰j         k    pM|d          j        ‰j        k    p7|d         j        ‰j        k    p!|d         j         ‰d         d         j         k    V — ŒidS )r�   r€   r   N)rd   rƒ   )rˆ   r‰   rõ   r    s     €€r.   rè   z/HungarianMatcher._match_many.<locals>.<genexpr>ß  s�   øè è € ð 
ð 
ð
 ð	 �7ŒOÔ! _Ô%:Ò:ð DØ�gŒÔ%¨Ô)?Ò?ðDà�hÔÔ&¨/Ô*@Ò@ðDð �hÔÔ%¨°¬°HÔ)=Ô)CÒCð	
ð 
ð 
ð 
ð 
ð 
r-   c                ó8   — g | ]}t          |d          ¦  «        ‘ŒS r†   rª   r‡   s     r.   rŠ   z0HungarianMatcher._match_many.<locals>.<listcomp>õ  r¬   r-   r„   r3   c                ó4   — h | ]}|d          j         d         ’ŒS )r™   r1   r�   rå   s     r.   ú	<setcomp>z/HungarianMatcher._match_many.<locals>.<setcomp>ÿ  s%   € ÐTÐTÐT¸G˜ Ô.Ô4°QÔ7ÐTÐTÐTr-   TrÂ   c                ób   •— g | ]+}‰                      |                     ¦   «         ‰‰¦  «        ‘Œ,S r,   )Ú_assign_compact_cost_matrixÚcpu)rˆ   r^   rð   rM   r²   s     €€€r.   rŠ   z0HungarianMatcher._match_many.<locals>.<listcomp>!  s6   ø€ ÐxÐxÐxÐ[f�×0Ò0°·²Ñ1BÔ1BÀEÈ:ÑVÔVÐxÐxÐxr-   )r«   rb   rž   re   r    r"   rd   r$   rƒ   r&   r   r–   r®   rX   rc   r`   ÚnextÚiterÚ_STACKED_COST_ELEMENT_LIMITrï   rØ   r�   ra   rf   rà   r6   r;   r�   r¥   r   Úassign_many_bucketed)rM   rá   r    rð   r½   Útarget_saferì   r“   Úquery_countsÚstacked_cost_matricesÚcost_matricesÚsafety_flagsÚlayer_indexr—   r¸   r^   rõ   rö   r÷   r²   s   ` ``            @@@@r.   Ú_match_manyzHungarianMatcher._match_many«  sô  øøøøøøø€ õF ˆ|ÑÔ˜qÒ Ð ­ð ,
ð ,
ð ,
ð ,
ð ,
ØKWð,
ñ ,
ô ,
ñ )
ô )
Ð ð �4à& qœ/¨,Ô7ˆØ'¨œ?¨=Ô9ÐØ,Ô2°2Ô6ÐÝð 
ð 
ð 
ð 
ð 
ð 
ð (¨¨¨Ô+ð
ñ 
ô 
ñ 
ô 
ð 	ð �4Ýð 
ð 
ð 
ð 
ð 
ð
 "ð
ñ 
ô 
ñ 
ô 
ð 	ð �4ð Ð*Ø"Ô*¨gÐ5Ð5Ø"Ô3°Ô7LÒLÐLØ"Ô4¸Ô8NÒNÐNØ"Ô.Ð2CÒCÐCà,Ô1ˆKˆKà×4Ò4ØÔ% Ô'=Ð?PÐRYñô ˆKð =Ð<°GÐ<Ñ<Ô<ˆÝ˜E™
œ
ˆØ˜AÒÐØ�4å œ; Ô'<Ñ=Ô=ÔAÀSÑHÈ2ÑMÐð
 UÐTÀ|ÐTÑTÔTˆØ $Ðå�ÑÔ Ò"Ð"Ý�LÑ!Ô!¥C¨¡L¤LÑ0µ4½¸\Ñ8JÔ8JÑ3KÔ3KÑKÍcÐRWÉjÌjÑXÕ\wÒwÐwà$(×$OÒ$OÐP\Ð^eÑ$fÔ$fÐ!à&(ˆð '2 ]ˆÝ$-¨lÑ$;Ô$;ð 
	Cñ 
	CÑ ˆK˜Ø  Ô.ˆJØ×Ò¥¤¨zÑ :Ô :× >Ò >Ñ @Ô @ÀJÇNÂNÑDTÔDTÐXhÒDh×CmÒCmÑCoÔCoÑ oÑpÔpÐpØ$Ð,Ø"×IÒIØ˜W¸$ð Jñ ô ç’%‘'”'ð �ð 4°KÔ@×FÒFÑHÔH�Ø× Ò  Ñ-Ô-Ð-Ø×Ò¥¤¨{Ñ ;Ô ;× ?Ò ?Ñ AÔ AÑBÔBÐBÑBõ •E”K Ñ-Ô-×1Ò1Ñ3Ô3Ñ4Ô4ð 	Ø�4ð
 Ô"ð 	VÝÔ3°MÀ5È*ÑUÔUÐUØxÐxÐxÐxÐxÐxÐjwÐxÑxÔxÐxr-   r²   ú	list[int]úlist[tuple[Tensor, Tensor]]c                óº  ‡‡	‡
‡— dgŠ|D ] }‰                      ‰d         |z   ¦  «         Œ!| j        d         }||z  dk    rt          d|› d|› d�¦  «        ‚||z  Š	g }t          |¦  «        D ]cŠ‰‰	z  }| ||‰	z   …         Š
ˆ
ˆfd„t          t	          |¦  «        ¦  «        D ¦   «         }‰dk    r|}ŒFˆˆ	fd„t          ||¦  «        D ¦   «         }Œdd„ |D ¦   «         S )	uY  Solve a compact ``[queries, total_targets]`` matrix by group and image.

        Shared by both the compact and the full-cartesian ``forward`` paths â€” "compact" in the name
        refers to the padded-to-``max(sizes)`` matrix layout this helper solves, not to which path
        calls it.

        Args:
            cost_matrix: Compact cost matrix of shape ``[num_queries, sum(sizes)]``, as returned by
                ``_compute_compact_detection_cost_matrix``.
            sizes: Each image's real (unpadded) target count, in batch order.
            group_detr: Number of query groups; ``num_queries`` must be evenly divisible by it.

        Returns:
            One ``(row_indices, col_indices)`` index pair per image, in batch order, with each group's
            assignment concatenated onto the same image's pair from every other group.
        r   r¹   znum_queries (z#) must be divisible by group_detr (ú)c           
     ód   •— g | ],}t          ‰d d …‰|         ‰|dz            …f         ¦  «        ‘Œ-S ©Nr1   r
   )rˆ   rÍ   Úgrouped_cost_matrixÚtarget_offsetss     €€r.   rŠ   z@HungarianMatcher._assign_compact_cost_matrix.<locals>.<listcomp>E  sW   ø€ ð ð ð àõ &Ð&9¸!¸!¸!¸^ÈEÔ=RÐUcÐdiÐlmÑdmÔUnÐ=nÐ:nÔ&oÑpÔpðð ð r-   c                óª   •— g | ]O\  }}t          j        |d          |d          ‰‰z  z   g¦  «        t          j        |d         |d         g¦  «        f‘ŒPS )r   r1   )ÚnpÚconcatenate)rˆ   ÚpreviousÚcurrentÚgroup_indexÚgroup_num_queriess      €€r.   rŠ   z@HungarianMatcher._assign_compact_cost_matrix.<locals>.<listcomp>L  sq   ø€ ð ð ð ñ
 *˜ 'õ œ¨°¬°W¸Q´ZÐBSÐVaÑBaÑ5aÐ'bÑcÔcÝœ¨°¬°W¸Q´ZÐ'@ÑAÔAððð ð r-   c                ó”   — g | ]E\  }}t          j        |t           j        ¬ ¦  «        t          j        |t           j        ¬ ¦  «        f‘ŒFS ))rd   )rX   Ú	as_tensorÚint64)rˆ   ÚiÚjs      r.   rŠ   z@HungarianMatcher._assign_compact_cost_matrix.<locals>.<listcomp>S  sH   € ÐsÐsÐsÑcgÐcdÐfg•” ­%¬+Ð6Ñ6Ô6½¼ÈÕQVÔQ\Ð8]Ñ8]Ô8]Ð^ÐsÐsÐsr-   )r�   rž   Ú
ValueErrorrí   r«   Úzip)r^   r²   rð   rÎ   r±   ÚindicesÚgroup_startÚgroup_indicesr  r  r  r  s           @@@@r.   rý   z,HungarianMatcher._assign_compact_cost_matrix#  si  øøøø€ ð, ˜ˆØð 	=ð 	=ˆDØ×!Ò! .°Ô"4°tÑ";Ñ<Ô<Ð<Ð<à!Ô'¨Ô*ˆØ˜Ñ# qÒ(Ð(ÝÐj¨[ÐjÐjÐ]gÐjÐjÐjÑkÔkÐkØ'¨:Ñ5ÐØˆÝ  Ñ,Ô,ð 	ð 	ˆKØ%Ð(9Ñ9ˆKØ"-¨k¸KÐJ[Ñ<[Ð.[Ô"\Ððð ð ð ð å"¥3 u¡:¤:Ñ.Ô.ðñ ô ˆMð ˜aÒÐØ'��ðð ð ð ð õ
 .1°¸-Ñ-HÔ-Hðñ ô ��ð tÐsÐkrÐsÑsÔsÐsr-   útuple[Tensor, Tensor]c                ó¢  — t          j        d„ |D ¦   «         ¦  «        }t          |d         t          ¦  «        rµ|d                              dd¦  «        }|j        d         |j        d         z  | j        z  }t          j        d|d|j        ¬¦  «        }t          | 
                    d¦  «        |                     |j        d         dd¦  «        d	¬
¦  «                             d¦  «        }nË|d         d         }|d         d         }	|d         d         }
|j        d         |j        d         z  | j        z  }t          j        d|d|j        ¬¦  «        }t          ||                     |j        d         dd¦  «        d	¬
¦  «        }t          j        d||	¦  «        |
z   }|                     dd¦  «        }|                     |j        ¦  «        }t          | 
                    d¦  «        |                     |j        d         dd¦  «        d	d¬¦  «                             d¦  «        }t!          ||¦  «        }t#          ||¦  «        }||fS )ur  Compute pairwise mask BCE and Dice costs over the whole batch.

        Shared by the full-cartesian ``masks_present`` path and the compact-hybrid path in
        :meth:`forward`: both need the identical ``[batch_size * num_queries, total_targets]``
        pairwise mask cost, sampled at the same randomly drawn ``point_coords`` (the predicted and
        target mask samples must share one draw to be comparable pointwise).

        Args:
            outputs: Model outputs containing ``pred_masks`` â€” either a ``Tensor`` of raw mask
                logits, or a dict of ``spatial_features``/``query_features``/``bias`` for the
                projected mask head.
            targets: Per-image target dicts containing ``masks``.

        Returns:
            ``(cost_mask_ce, cost_mask_dice)``, each of shape
            ``[batch_size * num_queries, total_targets]``.
        c                ó   — g | ]
}|d          ‘ŒS )rš   r,   r‡   s     r.   rŠ   z8HungarianMatcher._compute_mask_costs.<locals>.<listcomp>g  s   € ÐEÐEÐE°6˜v gœÐEÐEÐEr-   Ú
pred_masksr   r1   éþÿÿÿr¹   r¨   r‚   F)Úalign_cornersÚspatial_featuresÚquery_featuresÚbiaszbcp,bnc->bnpÚnearest)r(  Úmode)rX   rŽ   Ú
isinstancer   Úflattenrž   r=   Úrandrƒ   r   Ú	unsqueezeÚrepeatÚsqueezeÚeinsumrÕ   rd   r   r   )rM   r—   r    Ú	tgt_masksÚ	out_masksÚ
num_pointsÚpoint_coordsÚpred_masks_logitsr)  r*  r+  Útgt_masks_flatr>   r?   s                 r.   Ú_compute_mask_costsz$HungarianMatcher._compute_mask_costsU  s`  € õ$ ”IÐEÐE¸WÐEÑEÔEÑFÔFˆ	å�g˜lÔ+­VÑ4Ô4ð 	@Ø Ô-×5Ò5°a¸Ñ;Ô;ˆIà"œ¨Ô,¨y¬¸rÔ/BÑBÀdÔFbÑbˆJå œ: a¨°Q¸yÔ?OÐPÑPÔPˆLÝ ,Ø×#Ò# AÑ&Ô&¨×(;Ò(;¸I¼OÈAÔ<NÐPQÐSTÑ(UÔ(UÐejð!ñ !ô !çŠg�a‰jŒjð Ðð  ' |Ô4Ð5GÔHÐØ$ \Ô2Ð3CÔDˆNØ˜<Ô(¨Ô0ˆDà)Ô/°Ô3Ð6FÔ6LÈRÔ6PÑPÐTXÔTpÑpˆJÝ œ: a¨°QÐ?OÔ?VÐWÑWÔWˆLÝ ,Ø  ,×"5Ò"5Ð6FÔ6LÈQÔ6OÐQRÐTUÑ"VÔ"VÐfkð!ñ !ô !Ðõ !&¤¨^Ð=NÐP^Ñ _Ô _ÐbfÑ fÐØ 1× 9Ò 9¸!¸QÑ ?Ô ?Ðà—L’LÐ!2Ô!8Ñ9Ô9ˆ	Ý%Ø×Ò Ñ"Ô"Ø×Ò 	¤°Ô 2°A°qÑ9Ô9ØØð	
ñ 
ô 
÷
 Š'�!‰*Œ*ð 	õ -Ð->ÀÑOÔOˆõ )Ð):¸NÑKÔKˆØ˜^Ð+Ð+r-   c                óÖ  ‡'‡(‡)‡*— |d         j         dd…         \  }}d|d         v }d|v o	d|d         v }d}	|                      ||¦  «        o|                      |||¦  «        }
|
r²d„ |D ¦   «         }|                      ||¦  «                             ¦   «         }|j        s|                     ¦   «         }t          j        |¦  «         	                    ¦   «         r;|j        rt          j        |g||¦  «        d         S |                      |||¦  «        S �nî|                      |¦  «        �rØ|                      ||¦  «        �rÁ|                      ||¦  «        �rª|                      |||¦  «        �r’d	„ |D ¦   «         }|                      ||¦  «        }|                      ||¦  «        \  }}||f}	| j        |z                       ||d
¦  «        Š)| j        |z                       ||d
¦  «        Š*dgŠ(|D ] }‰(                     ‰(d
         |z   ¦  «         Œ!t          j        ˆ(ˆ)fd„t-          |¦  «        D ¦   «         d
¬¦  «        }t          j        ˆ(ˆ*fd„t-          |¦  «        D ¦   «         d
¬¦  «        }||z   }||z                        ¦   «         }t          j        |¦  «         	                    ¦   «         rM|j        rt          j        |g||¦  «        d         S |                      |                     ¦   «         ||¦  «        S |d                              dd¦  «        }|d                              dd¦  «        }t          j        d„ |D ¦   «         ¦  «        }t          j        d„ |D ¦   «         ¦  «        }d}|r t          j        d„ |D ¦   «         d¬¦  «        }t1          t3          |¦  «        t3          |¦  «        ¦  «        }| }|dd…|f         }|                      |¦  «        }|j        |j        k    r|                      ¦   «         nt:          } |||¦  «        }|r|	�|	n|                      ||¦  «        \  }}|r—|�•|dd…df         |dd…df         z  }t=          |d         |||| j        ¬¦  «        \  } }!}"}#|                      dd¦  «        } |!                     dd¦  «        }!|"                     dd¦  «        }"|#                     dd¦  «        }#| j         |z  | j!        |z  z   | j"        |z  z   Š'|r‰'| j        |z  z   | j        |z  z   Š'|r.‰'| j#        | z  z   | j$        |!z  z   | j%        |"z  z   | j&        |#z  z   Š'‰'                     ||d
¦  «                             ¦   «         Š'd|d         v r]t          j        d„ |D ¦   «         ¦  «         '                    ‰'j(        ¦  «        }$‰' )                    |$dddd…f          tT          ¦  «        Š't          j        ‰'¦  «         	                    ¦   «          +                    ¦   «         }%|%sQ‰'                     ¦   «         Š'| j,        s!tZ           .                    d¦  «         d| _,        |  /                    ‰'¦  «        Š'd„ |D ¦   «         }dgŠ(|D ] }‰(                     ‰(d
         |z   ¦  «         Œ!t          j        ˆ'ˆ(fd„t-          |¦  «        D ¦   «         d
¬¦  «                             ¦   «         }&|                      |&||¦  «        S )aÙ  Performs the matching

        Args:
            outputs: Dict containing at least these entries:
                 "pred_logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits
                 "pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates
            targets: List of targets (len(targets) = batch_size), where each target is a dict containing:
                 "labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth
                           objects in the target) containing the class labels
                 "boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates "masks": Tensor of
                 dim [num_target_boxes, H, W] containing the target mask coordinates
            group_detr: Number of groups used for matching.
            target_side_safety: An optional precomputed result from
                :meth:`_precompute_target_side_safety`, forwarded to
                :meth:`_detection_inputs_are_safe` to skip recomputing the target-side half of the
                compact-path safety gate when it still applies.

        Returns:
            A list of size batch_size, containing tuples of (index_i, index_j) where:
                - index_i is the indices of the selected predictions (in order)
                - index_j is the indices of the corresponding selected targets (in order)
            For each batch element, it holds len(index_i) == len(index_j). With group_detr == 1 this
            length is min(num_queries, num_target_boxes); with group_detr > 1 the per-group matches are
            concatenated, so the length is that quantity summed over the groups.
        r™   Nr¨   rš   r   r›   rœ   c                ó8   — g | ]}t          |d          ¦  «        ‘ŒS r†   rª   r‡   s     r.   rŠ   z,HungarianMatcher.forward.<locals>.<listcomp>½  ó$   € Ð@Ð@Ð@¨f•S˜ œÑ)Ô)Ð@Ð@Ð@r-   c                ó8   — g | ]}t          |d          ¦  «        ‘ŒS r†   rª   r‡   s     r.   rŠ   z,HungarianMatcher.forward.<locals>.<listcomp>à  r>  r-   r¹   c           	     óL   •— g | ] }‰|d d …‰|         ‰|dz            …f         ‘Œ!S r  r,   )rˆ   rÍ   r  Úweighted_mask_ces     €€r.   rŠ   z,HungarianMatcher.forward.<locals>.<listcomp>ê  sA   ø€ ÐvÐvÐvÐchÐ! %¨¨¨¨N¸5Ô,AÀNÐSXÐ[\ÑS\ÔD]Ð,]Ð"]Ô^ÐvÐvÐvr-   rÐ   c           	     óL   •— g | ] }‰|d d …‰|         ‰|dz            …f         ‘Œ!S r  r,   )rˆ   rÍ   r  Úweighted_mask_dices     €€r.   rŠ   z,HungarianMatcher.forward.<locals>.<listcomp>î  sO   ø€ ð ð ð àð ' u¨a¨a¨a°ÀÔ1FÈÐX]Ð`aÑXaÔIbÐ1bÐ'bÔcðð ð r-   r1   r¸   c                ó   — g | ]
}|d          ‘ŒS rŒ   r,   ©rˆ   Úvs     r.   rŠ   z,HungarianMatcher.forward.<locals>.<listcomp>  s   € Ð:Ð:Ð:¨Q˜Q˜xœ[Ð:Ð:Ð:r-   c                ó   — g | ]
}|d          ‘ŒS r†   r,   rE  s     r.   rŠ   z,HungarianMatcher.forward.<locals>.<listcomp>	  s   € Ð:Ð:Ð:¨Q˜a œjÐ:Ð:Ð:r-   c                ó   — g | ]
}|d          ‘ŒS )rœ   r,   rE  s     r.   rŠ   z,HungarianMatcher.forward.<locals>.<listcomp>  s   € Ð&GÐ&GÐ&G¸! q¨¤~Ð&GÐ&GÐ&Gr-   é   )Úall_pred_keypointsÚtarget_keypointsÚtarget_classesÚtarget_areasr@   r¢   c                ó   — g | ]
}|d          ‘ŒS rÊ   r,   r‡   s     r.   rŠ   z,HungarianMatcher.forward.<locals>.<listcomp>O  s   € Ð"IÐ"IÐ"I°v 6¨'¤?Ð"IÐ"IÐ"Ir-   zsNon-finite values detected in matcher cost matrix; replacing with finite sentinel. Check for numerical instability.Tc                ó8   — g | ]}t          |d          ¦  «        ‘ŒS r†   rª   rE  s     r.   rŠ   z,HungarianMatcher.forward.<locals>.<listcomp>`  s"   € Ð2Ð2Ð2 Q•�Q�w”Z‘”Ð2Ð2Ð2r-   c           	     óL   •— g | ] }‰|d d …‰|         ‰|dz            …f         ‘Œ!S r  r,   )rˆ   r  r^   r  s     €€r.   rŠ   z,HungarianMatcher.forward.<locals>.<listcomp>e  s<   ø€ Ð]Ð]Ð]Èaˆ[˜˜A˜A˜A˜~¨aÔ0°>À!ÀaÁ%Ô3HÐHÐHÔIÐ]Ð]Ð]r-   )0rž   r    rÁ   rà   r6   r¥   rþ   rX   ra   rb   r   r  rý   r¦   r£   rµ   r;  r>   Úviewr?   r�   rŽ   rí   r/  r   r   r~   rd   rZ   r   r   r@   r7   r5   r8   rB   rC   rD   rE   rÕ   rƒ   rÖ   r×   ÚitemrI   ÚloggerÚwarningrq   )+rM   r—   r    rð   r½   Úbsr±   Úmasks_presentÚkeypoints_presentÚprecomputed_mask_costsÚcompact_eligibler²   Úcompact_cost_matrixÚcompact_class_bbox_giour>   r?   rÎ   Úmask_ce_diagonalÚmask_dice_diagonalÚcombined_cost_matrixÚflat_pred_logitsÚout_bboxÚtgt_idsÚtgt_bboxÚtgt_keypointsÚgiour8   Ú
tgt_logitsr5   Úl1_costr7   rM  Úcost_l1Úcost_findableÚcost_visibleÚcost_nllÚ	tgt_validÚ
all_finiteÚdiagonal_cost_matrixr^   r  rA  rC  s+                                          @@@@r.   ÚforwardzHungarianMatcher.forwardŽ  sA  øøøø€ ðB " -Ô0Ô6°r¸°rÔ:‰ˆˆKà 7¨1¤:Ð-ˆØ,°Ð7ÐU¸KÈ7ÐSTÌ:Ð<UÐð @DÐØ×8Ò8¸À'ÑJÔJð 
Èt×OnÒOnØ�WÐ0ñP
ô P
Ðð ð @	gØ@Ð@¸Ð@Ñ@Ô@ˆEØ"&×"MÒ"MÈgÐW^Ñ"_Ô"_×"eÒ"eÑ"gÔ"gÐð 'Ô.ð @Ø&9×&=Ò&=Ñ&?Ô&?Ð#ÝŒ~Ð1Ñ2Ô2×6Ò6Ñ8Ô8ð `Ø&Ô.ð iÝ&Ô;Ð=PÐ<QÐSXÐZdÑeÔeÐfgÔhÐhØ×7Ò7Ð8KÈUÐT^Ñ_Ô_Ð_ñ`ð ×/Ò/°Ñ8Ô8ñ*	gà×2Ò2°7¸GÑDÔDñ*	gð ×+Ò+¨G°WÑ=Ô=ñ*	gð ×/Ò/°¸ÐBTÑUÔUñ	*	gð AÐ@¸Ð@Ñ@Ô@ˆEØ&*×&QÒ&QÐRYÐ[bÑ&cÔ&cÐ#Ø+/×+CÒ+CÀGÈWÑ+UÔ+UÑ(ˆL˜.Ø&2°NÐ%CÐ"Ø $Ô 1°LÑ @×FÒFÀrÈ;ÐXZÑ[Ô[ÐØ"&Ô"5¸Ñ"F×!LÒ!LÈRÐQ\Ð^`Ñ!aÔ!aÐØ˜SˆNØð Að A�Ø×%Ò% n°RÔ&8¸4Ñ&?Ñ@Ô@Ð@Ð@Ý$œyØvÐvÐvÐvÐvÕlqÐrtÑluÔluÐvÑvÔvØð ñ  ô  Ðõ "'¤ðð ð ð ð å!& r¡¤ðñ ô ð ð"ñ "ô "Ðð $;Ð=MÑ#MÐ Ø$8Ð;MÑ$M×#TÒ#TÑ#VÔ#VÐ ÝŒ~Ð2Ñ3Ô3×7Ò7Ñ9Ô9ð gØ'Ô/ð jÝ&Ô;Ð=QÐ<RÐTYÐ[eÑfÔfÐghÔiÐiØ×7Ò7Ð8L×8PÒ8PÑ8RÔ8RÐTYÐ[eÑfÔfÐfð # =Ô1×9Ò9¸!¸QÑ?Ô?ÐØ˜<Ô(×0Ò0°°AÑ6Ô6ˆõ ”)Ð:Ð:°'Ð:Ñ:Ô:Ñ;Ô;ˆÝ”9Ð:Ð:°'Ð:Ñ:Ô:Ñ;Ô;ˆØˆàð 	PÝ!œIÐ&GÐ&G¸wÐ&GÑ&GÔ&GÈQÐOÑOÔOˆMõ #Õ#5°hÑ#?Ô#?ÕASÐT\ÑA]ÔA]Ñ^Ô^ˆØ�Eˆ	ð & a a a¨ jÔ1ˆ
Ø×4Ò4°ZÑ@Ô@ˆ
ð
 .6¬^¸x¼~Ò-MÐ-M�$×'Ò'Ñ)Ô)Ð)ÕSgˆØ�G˜H hÑ/Ô/ˆ	àð 		ð *Ð5ð 'Ð&à×-Ò-¨g°wÑ?Ô?ñ )ˆL˜.ð ð 	. Ð!:Ø# A A A q Dœ>¨H°Q°Q°Q¸°T¬NÑ:ˆLÝ=[Ø#*Ð+;Ô#<Ø!.Ø&Ø)Ø(,Ô(Dð>ñ >ô >Ñ:ˆG�] L°(ð —o’o a¨Ñ+Ô+ˆGØ)×1Ò1°!°QÑ7Ô7ˆMØ'×/Ò/°°1Ñ5Ô5ˆLØ×'Ò'¨¨1Ñ-Ô-ˆHð #œn¨yÑ8¸4¼?ÈZÑ;WÑWÐZ^ÔZhÐktÑZtÑtˆØð 	pØ%¨Ô(9¸LÑ(HÑHÈ4ÔK^ÐaoÑKoÑoˆKØð 	àØÔ,¨wÑ6ñ7àÔ2°]ÑBñCð Ô1°LÑ@ñAð Ô-°Ñ8ñ	9ð ð "×&Ò& r¨;¸Ñ;Ô;×AÒAÑCÔCˆØ�g˜a”jÐ Ð õ œ	Ð"IÐ"IÀÐ"IÑ"IÔ"IÑJÔJ×MÒMÈkÔN`ÑaÔaˆIØ%×1Ò1°9¸TÀ4ÈÈÈ¸]Ô3KÐ2KÕM`ÑaÔaˆKõ ”^ KÑ0Ô0×4Ò4Ñ6Ô6×;Ò;Ñ=Ô=ˆ
Øð 		BØ%Ÿ/š/Ñ+Ô+ˆKØÔ0ð 5Ý—’ð7ñô ð ð
 15�Ô-Ø×4Ò4°[ÑAÔAˆKà2Ð2¨'Ð2Ñ2Ô2ˆØ˜ˆØð 	=ð 	=ˆDØ×!Ò! .°Ô"4°tÑ";Ñ<Ô<Ð<Ð<Ý',¤yØ]Ð]Ð]Ð]Ð]ÕSXÐY[ÑS\ÔS\Ð]Ñ]Ô]Ðceð(
ñ (
ô (
ç
Š#‰%Œ%ð 	ð ×/Ò/Ð0DÀeÈZÑXÔXÐXr-   )r1   r1   r1   r2   FFr3   r1   r1   Nr4   r4   r4   r4   )r5   r6   r7   r6   r8   r6   r9   r6   r:   r;   r<   r;   r=   r%   r>   r6   r?   r6   r@   rA   rB   r6   rC   r6   rD   r6   rE   r6   rÌ   )rO   rP   rQ   rR   )rQ   rU   )rQ   r   )r^   r   rQ   r   )rr   r   rQ   r   )
r"   r!   r$   r#   r&   r%   r    r   rQ   r   )r—   r   r    r   rQ   r;   )r—   r   rQ   r;   )r—   r   r    r   rQ   r¶   )r—   r   r    r   r½   r¶   rQ   r;   )r—   r   r    r   rÃ   r;   rQ   r   )rá   r   r    r   rQ   râ   )r1   N)
rá   r   r    r   rð   r%   r½   r¶   rQ   rñ   )r^   r   r²   r
  rð   r%   rQ   r  )r—   r   r    r   rQ   r#  )
r—   r   r    r   rð   r%   r½   r¶   rQ   r  )r'   r(   r)   r*   rH   rT   rZ   r\   Ústaticmethodrq   r~   r–   r    r£   r¦   rµ   rX   Úno_gradr¼   rÁ   rà   rï   r	  rý   r;  rn  Ú__classcell__)rN   s   @r.   r0   r0   z   sý  ø€ € € € € ð	ð 	ð ØØØ!Ø"Ø,1Ø')ØØ !Ø48Ø'*Ø-0Ø,/Ø(+ð1Qð 1Qð 1Qð 1Qð 1Qð 1Qð 1Qðf&ð &ð &ð &ð &ð.&ð &ð &ð &ð4ð 4ð 4ð 4ð 4ð 4ð ð%%ð %%ð %%ñ „\ð%%ðNð ð ð ð4 ð=)ð =)ð =)ñ „\ð=)ð~ ð
ð 
ð 
ñ „\ð
ð6 ð"
ð "
ð "
ñ „\ð"
ðH ð4ð 4ð 4ñ „\ð4ð ðIð Ið Iñ „\ðIð8 €U„]�_„_ð1bð 1bð 1bñ „_ð1bðf ð 8<ð8Kð 8Kð 8Kð 8Kñ „\ð8Kð~ %*ð:
ð :
ð :
ð :
ð :
ð :
ðx/
ð /
ð /
ð /
ðb €U„]�_„_ð
 Ø7;ðuyð uyð uyð uyñ „_ðuyðn ð/tð /tð /tñ „\ð/tðb7,ð 7,ð 7,ð 7,ðr €U„]�_„_ð
 Ø7;ðXYð XYð XYð XYñ „_ðXYð XYð XYð XYð XYr-   r0   Úargsr   rQ   c                ó@  — | j         | j        | j        | j        t	          | dg ¦  «        t	          | dd¦  «        t	          | dd¦  «        t	          | dd¦  «        t	          | dd¦  «        dœ	}| j        r!t          d
i |¤| j        | j        | j	        dœ¤ŽS t          d
i |¤ŽS )ao  Build a HungarianMatcher from a training argument namespace.

    Args:
        args: Namespace supplying ``focal_alpha``, ``set_cost_class``, ``set_cost_bbox``,
            ``set_cost_giou``, ``segmentation_head``, and optional keypoint cost
            coefficients (``keypoint_l1_loss_coef``, ``keypoint_findable_loss_coef``,
            ``keypoint_visible_loss_coef``, ``keypoint_nll_loss_coef``). When
            ``segmentation_head`` is truthy, also requires ``mask_ce_loss_coef``,
            ``mask_dice_loss_coef``, and ``mask_point_sample_ratio``.

    Returns:
        Configured HungarianMatcher instance.
    r@   rB   r4   rC   rD   rE   )	r5   r7   r8   r9   r@   rB   rC   rD   rE   )r>   r?   r=   Nr,   )
Úset_cost_classÚset_cost_bboxÚset_cost_giour9   ÚgetattrÚsegmentation_headr0   Úmask_ce_loss_coefÚmask_dice_loss_coefr=   )rr  Úcommon_kwargss     r.   Úbuild_matcherr|  j  sÝ   € ð  Ô)ØÔ'ØÔ'ØÔ'Ý#*¨4Ð1JÈBÑ#OÔ#OÝ!(¨Ð/FÈÑ!LÔ!LÝ'.¨tÐ5RÐTWÑ'XÔ'XÝ&-¨dÐ4PÐRUÑ&VÔ&VÝ")¨$Ð0HÈ#Ñ"NÔ"Nð
ð 
€Mð Ôð 1Ýð 
ð 
Øð
àÔ/ØÔ3Ø$(Ô$@ð	
ð 
ð 
ð 
ð 	
õ  Ð0Ð0 -Ð0Ð0Ð0r-   )rr  r   rQ   r0   )7r*   Ú
__future__r   Úcollections.abcr   r   Útypingr   r   r   Únumpyr  rX   Útorch.nn.functionalr   Ú
functionalrv   Únumpy.typingr	   Úscipy.optimizer   Ú_linear_sum_assignmentr   Útorch.nn.utils.rnnr   Úrfdetr.modelsr   Úrfdetr.models.heads.keypointsr   Ú rfdetr.models.heads.segmentationr   Úrfdetr.utilities.box_opsr   r   r   r   r   Úrfdetr.utilities.loggerr   rS  rg   rt   r  Útupler  Ú_LinearSumAssignmentr   r+   r   r×   r¯   r   ÚModuler0   r|  r,   r-   r.   ú<module>r�     sŒ  ðð$ MÐ LÐ Là "Ð "Ð "Ð "Ð "Ð "à -Ð -Ð -Ð -Ð -Ð -Ð -Ð -Ø (Ð (Ð (Ð (Ð (Ð (Ð (Ð (Ð (Ð (à Ð Ð Ð Ø €€€Ø Ð Ð Ð Ð Ð Ð Ð Ð Ø  Ð  Ð  Ð  Ð  Ð  Ø JÐ JÐ JÐ JÐ JÐ JØ Ð Ð Ð Ð Ð Ð Ð Ø +Ð +Ð +Ð +Ð +Ð +à %Ð %Ð %Ð %Ð %Ð %Ø HÐ HÐ HÐ HÐ HÐ HØ 9Ð 9Ð 9Ð 9Ð 9Ð 9ðð ð ð ð ð ð ð ð ð ð ð ð ð ð /Ð .Ð .Ð .Ð .Ð .à	ˆ‰Œ€ØÐ ØÐ ð
 &Ð Ø   u¨W°R´XÔ->ÀÈÌÔ@QÐ-QÔ'RÐ RÔSÐ ð ,5°dÐ*;Ð Ð ;Ð ;Ð ;Ñ ;ð -@ÀÐ+GÐ Ð GÐ GÐ GÑ GØ˜Ð1Ð3IÑJÔJÐ ð Ð ð %,Ð !ðð ð ð ð ˜
ñ ô ð ð<mYð mYð mYð mYð mY�r”yñ mYô mYð mYð`"1ð "1ð "1ð "1ð "1ð "1r-   