ó
    pyüiã.  ã                   óø   • S SK r S SKJr  SSKJr  SSKJr  SSKJrJ	r	J
r
Jr  \" 5       (       a  S SKJr    SS\ R                  S	\ R                  S
\S\S\4
S jjr " S S\5      r " S S\	5      r    SS jrg)é    Né   )Úcenter_to_corners_format)Úis_scipy_availableé   )ÚHungarianMatcherÚ	ImageLossÚ_set_aux_lossÚgeneralized_box_iou)Úlinear_sum_assignmentÚinputsÚtargetsÚ	num_boxesÚalphaÚgammac                 óî   • U R                  5       n[        R                  R                  XSS9nXQ-  SU-
  SU-
  -  -   nUSU-
  U-  -  nUS:¼  a  X1-  SU-
  SU-
  -  -   n	X˜-  nUR	                  5       U-  $ )a  
Loss used in RetinaNet for dense detection: https://huggingface.co/papers/1708.02002.

Args:
    inputs (`torch.FloatTensor` of arbitrary shape):
        The predictions for each example.
    targets (`torch.FloatTensor` with the same shape as `inputs`)
        A tensor storing the binary classification label for each element in the `inputs` (0 for the negative class
        and 1 for the positive class).
    num_boxes (`int`):
        The total number of boxes in the batch.
    alpha (`float`, *optional*, defaults to 0.25):
        Optional weighting factor in the range (0,1) to balance positive vs. negative examples.
    gamma (`int`, *optional*, defaults to 2):
        Exponent of the modulating factor (1 - p_t) to balance easy vs hard examples.

Returns:
    Loss tensor
Únone)Ú	reductionr   r   )ÚsigmoidÚnnÚ
functionalÚ binary_cross_entropy_with_logitsÚsum)
r   r   r   r   r   ÚprobÚce_lossÚp_tÚlossÚalpha_ts
             Úb/home/mande/repo/quber/.venv/lib/python3.13/site-packages/transformers/loss/loss_grounding_dino.pyÚsigmoid_focal_lossr      sŽ   € ð4 �>‰>Ó€DÜ�m‰m×<Ñ<¸VÐX^Ð<Ð_€Gà
‰.˜A ™H¨¨W©Ñ5Ñ
5€CØ�q˜3‘w 5Ñ(Ñ)€Dà�ƒzØ‘/ Q¨¡Y°1°w±;Ñ$?Ñ?ˆØ‰~ˆà�8‰8‹:˜	Ñ!Ð!ó    c                   óB   • \ rS rSr\R
                  " 5       S 5       rSrg)ÚGroundingDinoHungarianMatcheréC   c           
      óì  • US   R                   SS u  p4US   R                  SS5      R                  5       nUS   R                  SS5      nUS   n[        R                  " [        Xr5       VV	s/ s H  u  p‰X‰S      PM     sn	n5      nXwR                  S	S
S9-  n[        R                  " U V
s/ s H  oªS   PM	     sn
5      nSnSnSU-
  X]-  -  SU-
  S-   R                  5       * -  nUSU-
  U-  -  US-   R                  5       * -  nXþ-
  UR                  5       -  n[        R                  " XkSS9n[        [        U5      [        U5      5      * nU R                  U-  U R                  U-  -   U R                  U-  -   nUR                  X4S	5      R!                  5       nU V
s/ s H  n
[#        U
S   5      PM     nn
[%        UR'                  US	5      5       VVs/ s H  u  nn[)        UU   5      PM     nnnU VVs/ s HL  u  nn[        R*                  " U[        R,                  S9[        R*                  " U[        R,                  S94PMN     snn$ s  sn	nf s  sn
f s  sn
f s  snnf s  snnf )ad  
Args:
    outputs (`dict`):
        A dictionary that contains at least these entries:
        * "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.
        * "label_maps": Tuple of tensors of dim [num_classes, hidden_dim].
    targets (`list[dict]`):
        A list of targets (len(targets) = batch_size), where each target is a dict containing:
        * "class_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.

Returns:
    `list[Tuple]`: 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)
ÚlogitsNr   r   r   Ú
pred_boxesÚ
label_mapsÚclass_labelséÿÿÿÿT)ÚdimÚkeepdimÚboxesç      Ð?ç       @g:Œ0âŽyE>)Úp)Údtype)ÚshapeÚflattenr   ÚtorchÚcatÚzipr   ÚlogÚtÚcdistr
   r   Ú	bbox_costÚ
class_costÚ	giou_costÚviewÚcpuÚlenÚ	enumerateÚsplitr   Ú	as_tensorÚint64)ÚselfÚoutputsr   Ú
batch_sizeÚnum_queriesÚout_probÚout_bboxr'   Ú	label_mapÚtargetÚvÚtarget_bboxr   r   Úneg_cost_classÚpos_cost_classr:   r9   r;   Úcost_matrixÚsizesÚiÚcÚindicesÚjs                            r   ÚforwardÚ%GroundingDinoHungarianMatcher.forwardD   sd  € ð, #*¨(Ñ"3×"9Ñ"9¸"¸1Ð"=Ñˆ
ð ˜8Ñ$×,Ñ,¨Q°Ó2×:Ñ:Ó<ˆØ˜<Ñ(×0Ñ0°°AÓ6ˆØ˜\Ñ*ˆ
ô —Y’YÔ[^Ð_iÔ[sÔtÒ[sÑFWÀi 	°Ñ*@Ô AÑ[sÒtÓuˆ
à§.¡.°RÀ .Ð"FÑFˆ
ô —i’i±WÓ =²W° 7¤±WÑ =Ó>ˆð ˆØˆØ˜e™)¨©Ñ8¸aÀ(¹lÈTÑ>Q×=VÑ=VÓ=XÐ<XÑYˆØ 1 x¡<°EÑ"9Ñ:ÀÈ4Á×?TÑ?TÓ?VÐ>VÑWˆà$Ñ5¸¿¹»ÑGˆ
ô —K’K ¸Ñ;ˆ	ô )Ô)AÀ(Ó)KÔMeÐfqÓMrÓsÐsˆ	ð —n‘n yÑ0°4·?±?ÀZÑ3OÑOÐRV×R`ÑR`ÐclÑRlÑlˆØ!×&Ñ& zÀÓC×GÑGÓIˆá*1Ó2ª' Q”�Q�w‘Z–©'ˆÐ2Ü;DÀ[×EVÑEVÐW\Ð^`ÓEaÔ;bÔcÒ;b±4°1°aÔ(¨¨1©Ö.Ñ;bˆÑcÙkrÔsÒkrÑcgÐcdÐfg”—’ ¬%¯+©+Ñ6¼¿ºÈÔQV×Q\ÑQ\Ñ8]Ó^ÑkrÒsÐsùó7  uùò
 !>ùò( 3ùÛcùÛss   Á0I
Â1I Æ(I%Ç I*ÈAI0© N)Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__r3   Úno_gradrU   Ú__static_attributes__rW   r    r   r"   r"   C   s   † Ø
‡]‚]ƒ_ñ8tó ó8tr    r"   c                   óX   • \ rS rSrSrS r\R                  " 5       S 5       rS r	S r
Srg)	ÚGroundingDinoImageLossé€   aZ  
This class computes the losses for `GroundingDinoForObjectDetection`. The process happens in two steps: 1) we
compute hungarian assignment between ground truth boxes and the outputs of the model 2) we supervise each pair of
matched ground-truth / prediction (supervise class and box).

Args:
    matcher (`GroundingDinoHungarianMatcher`):
        Module able to compute a matching between targets and proposals.
    focal_alpha (`float`):
        Alpha parameter in focal loss.
    losses (`list[str]`):
        List of all the losses to be applied. See `get_loss` for a list of all available losses.
c                 óf   • [         R                  R                  U 5        Xl        X l        X0l        g ©N)r   ÚModuleÚ__init__ÚmatcherÚfocal_alphaÚlosses)rC   re   rf   rg   s       r   rd   ÚGroundingDinoImageLoss.__init__�   s$   € Ü
�	‰	×Ñ˜4Ô ØŒØ&ÔØ�r    c           	      óŒ  • US   nUR                   n[        R                  " U Vs/ s H  n[        US   5      PM     snUS9nUR	                  5       R                  S5      R                  S:„  R                  S5      n	[        R                  R                  U	R                  5       UR                  5       5      n
SU
0nU$ s  snf )zÊ
Compute the cardinality error, i.e. the absolute error in the number of predicted non-empty boxes.

This is not really a loss, it is intended for logging purposes only. It doesn't propagate gradients.
r%   r(   )Údevicer)   g      à?r   Úcardinality_error)rj   r3   rA   r>   r   ÚmaxÚvaluesr   r   r   Úl1_lossÚfloat)rC   rD   r   rS   r   r%   rj   rK   Útarget_lengthsÚ	card_predÚcard_errrg   s               r   Úloss_cardinalityÚ'GroundingDinoImageLoss.loss_cardinality•   s©   € ð ˜Ñ"ˆØ—‘ˆÜŸšÉ'Ó)RÊ'ÀQ¬#¨a°Ñ.?Ö*@É'Ñ)RÐ[aÑbˆà—^‘^Ó%×)Ñ)¨"Ó-×4Ñ4°sÑ:×?Ñ?ÀÓBˆ	Ü—=‘=×(Ñ(¨¯©Ó):¸N×<PÑ<PÓ<RÓSˆØ% xÐ0ˆØˆùò *Ss   ¦Cc                 óì  • US   n[         R                  " [        [        X#5      5       VVVVs/ s H3  u  nu  nu  pxUS:”  a  US   U   [	        US   U   5      -   OUS   U   PM5     snnnn5      n	[         R                  " US   SS9n
U R                  U5      n[         R                  " XDR                  [         R                  S9nX©   R                  [         R                  5      XË'   U$ s  snnnnf )z.
Create one_hot based on the matching indices
r%   r   r(   r'   )r*   )rj   r0   )
r3   r4   r?   r5   r>   Ú_get_source_permutation_idxÚ
zeros_likerj   ÚlongÚto)rC   rD   r   rS   r%   rQ   rJ   Ú_ÚJr(   r'   ÚidxÚtarget_classes_onehots                r   Ú_get_target_classes_one_hotÚ2GroundingDinoImageLoss._get_target_classes_one_hot¥   só   € ð ˜Ñ"ˆä—y’yô ,5´S¸Ó5JÔ+Köâ+KÑ'�AÑ'˜¡ ð NOÐQRËU��~Ñ& qÑ)¬C°¸Ñ0EÀaÑ0HÓ,IÒIÐX^Ð_mÑXnÐopÑXqÒqÙ+Kôó
ˆô —Y’Y˜w |Ñ4¸!Ñ<ˆ
à×.Ñ.¨wÓ7ˆÜ %× 0Ò 0°ÇÁÔUZ×U_ÑU_Ñ `ÐØ%/Ñ%=×%@Ñ%@ÄÇÁÓ%LÐÑ"à$Ð$ùõs   ¯:C.c                 ó0  • SU;  a  [        S5      eSU;  a  [        S5      eU R                  XU5      nUS   nUS   n[        R                  " Xg5      n[        R                  " XW5      nUR	                  5       n[        UUUU R                  SS9nSU0n	U	$ )zˆ
Classification loss (Binary focal loss) targets dicts must contain the key "class_labels" containing a tensor
of dim [nb_target_boxes]
r%   z#No logits were found in the outputsÚ	text_maskz&No text_mask were found in the outputsr   )r   r   r   r   r   Úloss_ce)ÚKeyErrorr~   r3   Úmasked_selectro   r   rf   )
rC   rD   r   rS   r   r}   Úsource_logitsr�   r‚   rg   s
             r   Úloss_labelsÚ"GroundingDinoImageLoss.loss_labels¹   s·   € ð
 ˜7Ó"ÜÐ@ÓAÐAØ˜gÓ%ÜÐCÓDÐDà $× @Ñ @ÀÐSZÓ [ÐØ Ñ)ˆØ˜KÑ(ˆ	ô ×+Ò+¨MÓEˆÜ %× 3Ò 3Ð4IÓ UÐà 5× ;Ñ ;Ó =ÐÜ$Ø Ø)ØØ×"Ñ"Øñ
ˆð ˜WÐ%ˆàˆr    )rf   rg   re   N)rX   rY   rZ   r[   Ú__doc__rd   r3   r\   rs   r~   r†   r]   rW   r    r   r_   r_   €   s0   † ñòð ‡]‚]ƒ_ñó ðò%õ(r    r_   c           
      ó"  ^^• [        UR                  UR                  UR                  S9n/ SQn[	        UUR
                  US9nUR                  U5        0 nXS'   X>S'   X^S'   XnS'   S nUR                  (       a"  [        Xx5      nU H  nUUS'   UUS'   M     XþS'   U" Xá5      mUR                  (       aJ  U	U
UUS	.nU" UU5      nUR                  5        VVs0 s H  u  nnUS
-   U_M     nnnTR                  U5        SUR                  UR                  S.mUR                  (       a:  TR                  5        VVs0 s H  u  nnUS
-   U_M     nnnTR                  U5        UR                  (       an  0 n[        UR                  S-
  5       H?  nUR                  TR                  5        VVs0 s H  u  nnUSU 3-   U_M     snn5        MA     TR                  U5        [!        UU4S jT 5       5      nUTU4$ s  snnf s  snnf s  snnf )N)r:   r9   r;   )Úlabelsr,   Úcardinality)re   rf   rg   r%   r&   r'   r�   Úauxiliary_outputs)r%   r&   r'   r�   Ú_encr.   )r‚   Ú	loss_bboxÚ	loss_giour   rz   c              3   óH   >#   • U  H  oT;   d  M
  TU   TU   -  v •  M     g 7frb   rW   )Ú.0ÚkÚ	loss_dictÚweight_dicts     €€r   Ú	<genexpr>Ú6GroundingDinoForObjectDetectionLoss.<locals>.<genexpr>  s&   øé € ÐT²i°ÈÑCSÓ,ˆy˜‰|˜k¨!™nÖ,²iùs   ƒ	"�")r"   r:   r9   r;   r_   rf   ry   Úauxiliary_lossr	   Ú	two_stageÚitemsÚupdateÚbbox_loss_coefficientÚgiou_loss_coefficientÚrangeÚdecoder_layersr   )r%   rŠ   rj   r&   Úconfigr'   r�   Úoutputs_classÚoutputs_coordÚencoder_logitsÚencoder_pred_boxesre   rg   Ú	criterionÚoutputs_lossrŒ   Ú
aux_outputÚencoder_outputs_lossÚencoder_loss_dictr’   rK   Úenc_weight_dictÚaux_weight_dictrQ   r   r“   r”   s                            @@r   Ú#GroundingDinoForObjectDetectionLossr«   Ù   s2  ù€ ô ,Ø×$Ñ$°×0@Ñ0@ÈF×L\ÑL\ñ€Gò 0€FÜ&ØØ×&Ñ&Øñ€Ið
 ‡L�L�Ôà€LØ#�ÑØ!+�ÑØ!+�ÑØ )�ÑàÐØ××Ü)¨-ÓGÐÛ+ˆJØ'1ˆJ�|Ñ$Ø&/ˆJ�{Ó#ñ ,ð ->Ð(Ñ)á˜,Ó/€Ià××à$Ø,Ø$Ø"ñ	 
Ðñ &Ð&:¸FÓCÐØ7H×7NÑ7NÔ7PÔQÒ7P©t¨q°!˜Q ™Z¨š]Ñ7PÐÑQØ×ÑÐ*Ô+ð Ø×1Ñ1Ø×1Ñ1ñ€Kð ××Ø5@×5FÑ5FÔ5HÔIÒ5H©T¨Q°˜1˜v™: qš=Ñ5HˆÑIØ×Ñ˜?Ô+à××ØˆÜ�v×,Ñ,¨qÑ0Ö1ˆAØ×"Ñ"¸{×?PÑ?PÔ?RÔ#SÒ?R±t°q¸! A¨!¨A¨3¨¡K°¢NÑ?RÒ#SÖTñ 2à×Ñ˜?Ô+äÕT±iÓTÓT€DØ�Ð-Ð-Ð-ùó) Rùó Jùó $Ts   ÃG?Ä>HÆ1H)r-   r   )NNNN)r3   Útorch.nnr   Úimage_transformsr   Úutilsr   Úloss_for_object_detectionr   r   r	   r
   Úscipy.optimizer   ÚTensorÚintro   r   r"   r_   r«   rW   r    r   Ú<module>r³      sž   ðó Ý å 7Ý &ß fÓ fñ ×ÑÝ4ð Øñ$"Ø�L‰Lð$"à�\‰\ð$"ð ð$"ð ð	$"ð
 õ$"ôN:tÐ$4ô :tôzV˜Yô VðB ØØØõF.r    