Ë
    ëÓ^jV@  ã                  óÒ   — d Z ddl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 ddlmZ ddlmZmZmZmZ dd	lmZ  e«       Zd
ZdZ G d„ dej4                  «      Zdd„Zy)zFModules to compute the matching cost and solve the corresponding LSAP.é    )ÚannotationsN)Úlinear_sum_assignment)Únn)Úcompute_keypoint_matching_cost)Úpoint_sample)Úbatch_dice_lossÚbatch_sigmoid_ce_lossÚbox_cxcywh_to_xyxyÚgeneralized_box_iou)Ú
get_loggerg      ð?g       @c                  óÌ   ‡ — e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dˆ fd„Zedd„«       Z ej                  «       	 d	 	 	 	 	 	 	 d	d„«       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.
    c                ó  •— t         ‰| �  «        || _        || _        || _        |dk7  s|dk7  s|dk7  sJ d«       ‚|| _        || _        || _        |	| _        |
xs g | _	        || _
        || _        || _        || _        d| _        y)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__Ú
cost_classÚ	cost_bboxÚ	cost_giouÚfocal_alphaÚmask_point_sample_ratioÚcost_mask_ceÚcost_mask_diceÚnum_keypoints_per_classÚkeypoint_l1_loss_coefÚkeypoint_findable_loss_coefÚkeypoint_visible_loss_coefÚkeypoint_nll_loss_coefÚ_warned_non_finite_costs)Úselfr   r   r   r   Úuse_pos_onlyÚuse_position_modulated_costr   r   r   r   r   r   r   r   Ú	__class__s                  €ú`/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/rfdetr/models/matcher.pyr   zHungarianMatcher.__init__2   s™   ø€ ô< 	‰ÑÔØ$ˆŒØ"ˆŒØ"ˆŒØ˜QŠ )¨q¢.°IÀ²NÐZÐDZÓZÐBØ&ˆÔØ'>ˆÔ$Ø(ˆÔØ,ˆÔØ'>Ò'DÀ"ˆÔ$Ø%:ˆÔ"Ø+FˆÔ(Ø*DˆÔ'Ø&<ˆÔ#Ø(-ˆÕ%ó    c                ó4  — t        j                  | «      }|j                  «       r| S t        j                  | j                  «      }|j                  «       r�| |   }|j                  «       }||j                  «       j                  «       z   t        z   }t        j                  |«      s| j                  |j                  «      }n=t        j                  ||j                  ¬«      }n| j                  |j                  «      }| 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)ÚtorchÚisfiniteÚallÚfinfoÚdtypeÚanyr&   ÚabsÚ_SANITIZED_COST_MARGINÚ
new_tensorÚclampÚclone)Úcost_matrixÚfinite_maskÚ
dtype_infoÚfinite_costsÚmax_costÚreplacement_costÚsanitized_cost_matrixs          r#   Ú_sanitize_cost_matrixz&HungarianMatcher._sanitize_cost_matrix`   sî   € ô  —n‘n [Ó1ˆØ�?‰?ÔØÐä—[‘[ ×!2Ñ!2Ó3ˆ
Ø�?‰?ÔØ& {Ñ3ˆLØ#×'Ñ'Ó)ˆHð  (¨,×*:Ñ*:Ó*<×*@Ñ*@Ó*BÑBÔE[Ñ[Ðä—>‘>Ð"2Ô3Ø#.×#9Ñ#9¸*¿.¹.Ó#IÑ ä#(§;¡;Ð/?ÀZÇ^Á^Ô#TÑ ð  +×5Ñ5°j·n±nÓEÐà +× 1Ñ 1Ó 3ÐØ.>Ð˜{˜lÑ+Ø$Ð$r$   c                óŠ  — |d   j                   dd \  }}|d   j                  dd«      }|j                  «       }|d   j                  dd«      }t        j                  |D �	cg c]  }	|	d   ‘Œ	 c}	«      }
t        j                  |D �	cg c]  }	|	d   ‘Œ	 c}	«      }d}d	|d   v }d
|v xr d|d   v }|r(t        j                  |D �	cg c]  }	|	d   ‘Œ	 c}	d¬«      }t        t        |«      t        |«      «      }| }| j                  }t        }d|z
  ||z  z  t        j                  | «       z  }|d|z
  |z  z  t        j                  |«       z  }|dd…|
f   |dd…|
f   z
  }t        j                  ||d¬«      }|�r/t        j                  |D �	cg c]  }	|	d	   ‘Œ	 c}	«      }t        |d   t        j                  «      r¯|d   j                  dd«      }|j                   d   |j                   d   z  | j                  z  }t        j                  d|d|j                   ¬«      }t#        |j%                  d«      |j'                  |j                   d   dd«      d¬«      j)                  d«      }n¿|d   d   }|d   d   }|d   d   }|j                   d   |j                   d   z  | j                  z  }t        j                  d|d|j                   ¬«      }t#        ||j'                  |j                   d   dd«      d¬«      }t        j*                  d||«      |z   }|j                  dd«      }|j-                  |j.                  «      }t#        |j%                  d«      |j'                  |j                   d   dd«      dd¬«      j)                  d«      }t1        ||«      } t3        ||«      }!|r|�}|dd…df   |dd…df   z  }"t5        |d
   ||
|"| j6                  ¬«      \  }#}$}%}&|#j                  dd«      }#|$j                  dd«      }$|%j                  dd«      }%|&j                  dd«      }&| j8                  |z  | j:                  |z  z   | j<                  |z  z   }'|r"|'| j>                   z  z   | j@                  !z  z   }'|rB|'| jB                  #z  z   | jD                  $z  z   | jF                  %z  z   | jH                  &z  z   }'|'jK                  ||d«      jM                  «       jO                  «       }'t        jP                  |'«      }(|(jS                  «       s9| jT                  stV        jY                  d«       d| _*        | j[                  |'«      }'|D �	cg c]  }	t]        |	d   «      ‘Œ })}	g }*||z  }+|'j_                  |+d¬«      },ta        |«      D ]¤  }-|,|-   }.tc        |.j_                  |)d«      «      D �/�0cg c]  \  }/}0te        |0|/   «      ‘Œ }1}/}0|-dk(  r|1}*ŒItg        |*|1«      D �2�3cg c]E  \  }2}3ti        jj                  |2d   |3d   |+|-z  z   g«      ti        jj                  |2d   |3d   g«      f‘ŒG }*}2}3Œ¦ |*D �/�4cg c]O  \  }/}4t        jl                  |/t        jn                  ¬«      t        jl                  |4t        jn                  ¬«      f‘ŒQ c}4}/S c c}	w c c}	w c c}	w c c}	w c c}	w c c}0}/w c c}3}2w c c}4}/w )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.

        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) = min(num_queries, num_target_boxes)
        Úpred_logitsNé   r   é   Ú
pred_boxesÚlabelsÚboxesÚmasksÚpred_keypointsÚ	keypoints)Údim)ÚpÚ
pred_maskséþÿÿÿéÿÿÿÿ)ÚdeviceF)Úalign_cornersÚspatial_featuresÚquery_featuresÚbiaszbcp,bnc->bnpÚnearest)rJ   Úmodeé   )Úall_pred_keypointsÚtarget_keypointsÚtarget_classesÚtarget_areasr   zsNon-finite values detected in matcher cost matrix; replacing with finite sentinel. Check for numerical instability.T)r+   )8ÚshapeÚflattenÚsigmoidr'   Úcatr   r
   r   Ú_FOCAL_LOSS_GAMMAÚFÚ
logsigmoidÚcdistÚ
isinstanceÚTensorr   ÚrandrI   r   Ú	unsqueezeÚrepeatÚsqueezeÚeinsumÚtor+   r	   r   r   r   r   r   r   r   r   r   r   r   r   ÚviewÚfloatÚcpur(   r)   r   ÚloggerÚwarningr9   ÚlenÚsplitÚrangeÚ	enumerater   ÚzipÚnpÚconcatenateÚ	as_tensorÚint64)5r   ÚoutputsÚtargetsÚ
group_detrÚbsÚnum_queriesÚflat_pred_logitsÚout_probÚout_bboxÚvÚtgt_idsÚtgt_bboxÚtgt_keypointsÚmasks_presentÚkeypoints_presentÚgiour   ÚalphaÚgammaÚneg_cost_classÚpos_cost_classr   r   Ú	tgt_masksÚ	out_masksÚ
num_pointsÚpoint_coordsÚpred_masks_logitsrK   rL   rM   Útgt_masks_flatr   r   rT   Úcost_l1Úcost_findableÚcost_visibleÚcost_nllr2   r3   ÚsizesÚindicesÚg_num_queriesÚcost_matrix_listÚg_iÚgrouped_cost_matrixÚiÚcÚ	indices_gÚindice1Úindice2Újs5                                                        r#   ÚforwardzHungarianMatcher.forwardˆ   s  € ð6 " -Ñ0×6Ñ6°r¸Ð:‰ˆˆKð # =Ñ1×9Ñ9¸!¸QÓ?ÐØ#×+Ñ+Ó-ˆØ˜<Ñ(×0Ñ0°°AÓ6ˆô —)‘)°'Ö:¨Q˜Q˜x›[Ò:Ó;ˆÜ—9‘9°'Ö:¨Q˜a ›jÒ:Ó;ˆØˆà 7¨1¡:Ð-ˆØ,°Ð7ÒU¸KÈ7ÐSTÉ:Ð<UÐÙÜ!ŸI™I¸wÖ&G¸! q¨£~Ò&GÈQÔOˆMô #Ô#5°hÓ#?ÔASÐT\ÓA]Ó^ˆØ�Eˆ	ð × Ñ ˆÜ!ˆð
 ˜e™)¨°%©Ñ8¼Q¿\¹\ÐK[ÐJ[Ó=\Ð<\Ñ]ˆØ 1 x¡<°EÑ"9Ñ:¼q¿|¹|ÐL\Ó?]Ð>]Ñ^ˆØ#¢A w JÑ/°.ÂÀGÀÑ2LÑLˆ
ô —K‘K ¨(°aÔ8ˆ	âÜŸ	™	°wÖ"?°! 1 W£:Ò"?Ó@ˆIä˜' ,Ñ/´·±Ô>Ø# LÑ1×9Ñ9¸!¸QÓ?�	à&Ÿ_™_¨RÑ0°9·?±?À2Ñ3FÑFÈ$×JfÑJfÑf�
ä$Ÿz™z¨!¨Z¸À9×CSÑCSÔT�Ü$0Ø×'Ñ'¨Ó*¨L×,?Ñ,?À	ÇÁÐPQÑ@RÐTUÐWXÓ,YÐinô%ç‘'˜!“*ñ "ð $+¨<Ñ#8Ð9KÑ#LÐ Ø!(¨Ñ!6Ð7GÑ!H�Ø˜|Ñ,¨VÑ4�à-×3Ñ3°BÑ7Ð:J×:PÑ:PÐQSÑ:TÑTÐX\×XtÑXtÑt�
Ü$Ÿz™z¨!¨Z¸ÐCS×CZÑCZÔ[�Ü$0Ø$ l×&9Ñ&9Ð:J×:PÑ:PÐQRÑ:SÐUVÐXYÓ&ZÐjoô%Ð!ô %*§L¡L°ÐARÐTbÓ$cÐfjÑ$jÐ!Ø$5×$=Ñ$=¸aÀÓ$CÐ!à!Ÿ™Ð%6×%<Ñ%<Ó=ˆIÜ)Ø×#Ñ# AÓ&Ø×#Ñ# I§O¡O°AÑ$6¸¸1Ó=Ø#Øô	÷
 ‰g�a‹jð ô 1Ð1BÀNÓSˆLô -Ð->ÀÓOˆNá Ð!:Ø#¢A q D™>¨H²Q¸°T©NÑ:ˆLÜ=[Ø#*Ð+;Ñ#<Ø!.Ø&Ø)Ø(,×(DÑ(Dô>Ñ:ˆG�] L°(ð —o‘o a¨Ó+ˆGØ)×1Ñ1°!°QÓ7ˆMØ'×/Ñ/°°1Ó5ˆLØ×'Ñ'¨¨1Ó-ˆHð —n‘n yÑ0°4·?±?ÀZÑ3OÑOÐRV×R`ÑR`ÐclÑRlÑlˆÙØ%¨×(9Ñ(9¸LÑ(HÑHÈ4×K^ÑK^ÐaoÑKoÑoˆKÙàØ×,Ñ,¨wÑ6ñ7à×2Ñ2°]ÑBñCð ×1Ñ1°LÑ@ñAð ×-Ñ-°Ñ8ñ	9ð ð ×Ñ˜R ¨bÓ1×7Ñ7Ó9×=Ñ=Ó?ð 	ô —n‘n [Ó1ˆØ�‰Ô Ø×0Ò0Ü—‘ð7ôð
 15�Ô-Ø×4Ñ4°[ÓAˆKà*1Ö2 Q”�Q�w‘Z•Ð2ˆÐ2ØˆØ# zÑ1ˆØ&×,Ñ,¨]ÀÐ,ÓBÐÜ˜Ó$ò 	ˆCØ"2°3Ñ"7ÐÜAJÐK^×KdÑKdÐejÐlnÓKoÓAp×q¹¸¸AÔ.¨q°©tÕ4ÐqˆIÑqØ�aŠxØ#‘ô -0°¸Ó,C÷ñ
 )˜ ô Ÿ™¨°©
°G¸A±JÀÐQTÑATÑ4TÐ'UÓVÜŸ™¨°©
°G¸A±JÐ'?Ó@òð�ò ð	ð ls×sÑcgÐcdÐfg”—‘ ¬%¯+©+Ô6¼¿¹ÈÔQV×Q\ÑQ\Ô8]Ò^ÓsÐsùò ;ùÚ:ùò 'Hùò* #@ùòd 3ùó rùóùó ts2   Á#ZÂ	ZÃZ$ÆZ)ÕZ.Ö<Z3×.A
Z9ÙAZ?)r=   r=   r=   g      Ð?FFé   r=   r=   Nç        rž   rž   rž   )r   rf   r   rf   r   rf   r   rf   r    Úboolr!   rŸ   r   Úintr   rf   r   rf   r   zlist[int] | Noner   rf   r   rf   r   rf   r   rf   )r2   útorch.TensorÚreturnr¡   )r=   )rs   Údictrt   Úlistru   r    r¢   z'list[tuple[torch.Tensor, torch.Tensor]])Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Ústaticmethodr9   r'   Úno_gradrœ   Ú__classcell__)r"   s   @r#   r   r   &   s,  ø„ ñ	ð ØØØ!Ø"Ø,1Ø')ØØ !Ø48Ø'*Ø-0Ø,/Ø(+ð,.àð,.ð ð,.ð ð	,.ð
 ð,.ð ð,.ð &*ð,.ð "%ð,.ð ð,.ð ð,.ð "2ð,.ð  %ð,.ð &+ð,.ð %*ð,.ð !&õ,.ð\ ò%%ó ð%%ðN €U‡]�]ƒ_ð
 ð	atàðatð ðatð ð	atð
 
1òató ôatr$   r   c                ód  — | 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   r   rž   r   r   r   )	r   r   r   r   r   r   r   r   r   )r   r   r   © )
Úset_cost_classÚset_cost_bboxÚset_cost_giour   ÚgetattrÚsegmentation_headr   Úmask_ce_loss_coefÚmask_dice_loss_coefr   )ÚargsÚcommon_kwargss     r#   Úbuild_matcherr·   -  sÂ   € ð  ×)Ñ)Ø×'Ñ'Ø×'Ñ'Ø×'Ñ'Ü#*¨4Ð1JÈBÓ#OÜ!(¨Ð/FÈÓ!LÜ'.¨tÐ5RÐTWÓ'XÜ&-¨dÐ4PÐRUÓ&VÜ")¨$Ð0HÈ#Ó"Nñ
€Mð ×ÒÜñ 
Øð
à×/Ñ/Ø×3Ñ3Ø$(×$@Ñ$@ó	
ð 	
ô  Ñ0 -Ñ0Ð0r$   )r¢   r   )r¨   Ú
__future__r   Únumpyro   r'   Útorch.nn.functionalr   Ú
functionalrZ   Úscipy.optimizer   Úrfdetr.models.heads.keypointsr   Ú rfdetr.models.heads.segmentationr   Úrfdetr.utilities.box_opsr   r	   r
   r   Úrfdetr.utilities.loggerr   rh   r.   rY   ÚModuler   r·   r­   r$   r#   ú<module>rÂ      s\   ðñ$ Må "ã Û ß Ð Ý 0Ý å HÝ 9ß tÓ tÝ .á	‹€ØÐ ØÐ ôDt�r—y‘yô DtôN"1r$   