§
    ‚Štjã.  ã                   óè   — d dl 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  e¦   «         rd dlmZ 	 	 dd	e j        d
e j        dededef
d„Z G d„ de¦  «        Z G d„ de	¦  «        Z	 	 	 	 dd„ZdS )é    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                 ó  — |                       ¦   «         }t          j                             | |d¬¦  «        }||z  d|z
  d|z
  z  z   }|d|z
  |z  z  }|dk    r||z  d|z
  d|z
  z  z   }	|	|z  }|                     ¦   «         |z  S )aR  
    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
             úc/var/www/html/CA-Chatbot/venv/lib/python3.11/site-packages/transformers/loss/loss_grounding_dino.pyÚsigmoid_focal_lossr!      sž   € ð4 �>Š>ÑÔ€DÝŒm×<Ò<¸VÀWÐX^Ð<Ñ_Ô_€Gà
�‰.˜A ™H¨¨W©Ñ5Ñ
5€CØ�q˜3‘w 5Ñ(Ñ)€Dà�‚z€zØ˜'‘/ Q¨¡Y°1°w±;Ñ$?Ñ?ˆØ˜‰~ˆà�8Š8‰:Œ:˜	Ñ!Ð!ó    c                   ó>   — e Zd Z ej        ¦   «         d„ ¦   «         ZdS )ÚGroundingDinoHungarianMatcherc                 ó  — |d         j         dd…         \  }}|d                              dd¦  «                             ¦   «         }|d                              dd¦  «        }|d         }t          j        d„ t          ||¦  «        D ¦   «         ¦  «        }||                     d	d
¬¦  «        z  }t          j        d„ |D ¦   «         ¦  «        }d}	d}
d|	z
  ||
z  z  d|z
  dz                        ¦   «          z  }|	d|z
  |
z  z  |dz                        ¦   «          z  }||z
  |                     ¦   «         z  }t          j	        ||d¬¦  «        }t          t          |¦  «        t          |¦  «        ¦  «         }| j        |z  | j        |z  z   | j        |z  z   }|                     ||d	¦  «                             ¦   «         }d„ |D ¦   «         }d„ t#          |                     |d	¦  «        ¦  «        D ¦   «         }d„ |D ¦   «         S )aô  
        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_mapsc                 ó0   — g | ]\  }}||d                   ‘ŒS ©Úclass_labels© )Ú.0Ú	label_mapÚtargets      r    ú
<listcomp>z9GroundingDinoHungarianMatcher.forward.<locals>.<listcomp>b   s(   € ÐtÐtÐtÑFWÀiÐQW 	¨&°Ô*@Ô AÐtÐtÐtr"   éÿÿÿÿT)ÚdimÚkeepdimc                 ó   — g | ]
}|d          ‘ŒS ©Úboxesr,   ©r-   Úvs     r    r0   z9GroundingDinoHungarianMatcher.forward.<locals>.<listcomp>g   s   € Ð =Ð =Ð =°  7¤Ð =Ð =Ð =r"   r   ç       @g:Œ0âŽyE>)Úpc                 ó8   — g | ]}t          |d          ¦  «        ‘ŒS r5   ©Úlenr7   s     r    r0   z9GroundingDinoHungarianMatcher.forward.<locals>.<listcomp>{   s"   € Ð2Ð2Ð2 Q•�Q�w”Z‘”Ð2Ð2Ð2r"   c                 ó>   — g | ]\  }}t          ||         ¦  «        ‘ŒS r,   r   )r-   ÚiÚcs      r    r0   z9GroundingDinoHungarianMatcher.forward.<locals>.<listcomp>|   s)   € ÐcÐcÐc±4°1°aÕ(¨¨1¬Ñ.Ô.ÐcÐcÐcr"   c                 ó”   — g | ]E\  }}t          j        |t           j        ¬ ¦  «        t          j        |t           j        ¬ ¦  «        f‘ŒFS ))Údtype)ÚtorchÚ	as_tensorÚint64)r-   r?   Újs      r    r0   z9GroundingDinoHungarianMatcher.forward.<locals>.<listcomp>}   sH   € ÐsÐsÐsÑcgÐcdÐfg•” ­%¬+Ð6Ñ6Ô6½¼ÈÕQVÔQ\Ð8]Ñ8]Ô8]Ð^ÐsÐsÐsr"   )ÚshapeÚflattenr   rC   ÚcatÚzipr   ÚlogÚtÚcdistr
   r   Ú	bbox_costÚ
class_costÚ	giou_costÚviewÚcpuÚ	enumerateÚsplit)ÚselfÚoutputsr   Ú
batch_sizeÚnum_queriesÚout_probÚout_bboxr(   Útarget_bboxr   r   Úneg_cost_classÚpos_cost_classrO   rN   rP   Úcost_matrixÚsizesÚindicess                      r    Úforwardz%GroundingDinoHungarianMatcher.forwardD   s/  € ð, #*¨(Ô"3Ô"9¸"¸1¸"Ô"=Ñˆ
�Kð ˜8Ô$×,Ò,¨Q°Ñ2Ô2×:Ò:Ñ<Ô<ˆØ˜<Ô(×0Ò0°°AÑ6Ô6ˆØ˜\Ô*ˆ
õ ”YÐtÐtÕ[^Ð_iÐkrÑ[sÔ[sÐtÑtÔtÑuÔuˆ
à *§.¢.°RÀ .Ñ"FÔ"FÑFˆ
õ ”iÐ =Ð =°WÐ =Ñ =Ô =Ñ>Ô>ˆð ˆØˆØ˜e™)¨°%©Ñ8¸aÀ(¹lÈTÑ>Q×=VÒ=VÑ=XÔ=XÐ<XÑYˆØ 1 x¡<°EÑ"9Ñ:ÀÈ4Á×?TÒ?TÑ?VÔ?VÐ>VÑWˆà$ ~Ñ5¸¿º¹¼ÑGˆ
õ ”K ¨+¸Ð;Ñ;Ô;ˆ	õ )Õ)AÀ(Ñ)KÔ)KÕMeÐfqÑMrÔMrÑsÔsÐsˆ	ð ”n yÑ0°4´?ÀZÑ3OÑOÐRVÔR`ÐclÑRlÑlˆØ!×&Ò& z°;ÀÑCÔC×GÒGÑIÔIˆà2Ð2¨'Ð2Ñ2Ô2ˆØcÐc½9À[×EVÒEVÐW\Ð^`ÑEaÔEaÑ;bÔ;bÐcÑcÔcˆØsÐsÐkrÐsÑsÔsÐsr"   N)Ú__name__Ú
__module__Ú__qualname__rC   Úno_gradra   r,   r"   r    r$   r$   C   s:   € € € € € Ø€U„]�_„_ð8tð 8tñ „_ð8tð 8tð 8tr"   r$   c                   óT   — e Zd ZdZd„ Z ej        ¦   «         d„ ¦   «         Zd„ Zd„ Z	dS )ÚGroundingDinoImageLossa†  
    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                 ón   — t           j                             | ¦  «         || _        || _        || _        d S ©N)r   ÚModuleÚ__init__ÚmatcherÚfocal_alphaÚlosses)rU   rl   rm   rn   s       r    rk   zGroundingDinoImageLoss.__init__�   s2   € Ý
Œ	×Ò˜4Ñ Ô Ð ØˆŒØ&ˆÔØˆŒˆˆr"   c                 óz  — |d         }|j         }t          j        d„ |D ¦   «         |¬¦  «        }|                     ¦   «                              d¦  «        j        dk                         d¦  «        }t          j         	                    | 
                    ¦   «         | 
                    ¦   «         ¦  «        }	d|	i}
|
S )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&   c                 ó8   — g | ]}t          |d          ¦  «        ‘ŒS r*   r<   r7   s     r    r0   z;GroundingDinoImageLoss.loss_cardinality.<locals>.<listcomp>ž   s%   € Ð)RÐ)RÐ)RÀQ­#¨a°Ô.?Ñ*@Ô*@Ð)RÐ)RÐ)Rr"   )Údevicer1   g      à?r   Úcardinality_error)rq   rC   rD   r   ÚmaxÚvaluesr   r   r   Úl1_lossÚfloat)rU   rV   r   r`   r   r&   rq   Útarget_lengthsÚ	card_predÚcard_errrn   s              r    Úloss_cardinalityz'GroundingDinoImageLoss.loss_cardinality•   s¨   € ð ˜Ô"ˆØ”ˆÝœÐ)RÐ)RÈ'Ð)RÑ)RÔ)RÐ[aÐbÑbÔbˆà—^’^Ñ%Ô%×)Ò)¨"Ñ-Ô-Ô4°sÒ:×?Ò?ÀÑBÔBˆ	Ý”=×(Ò(¨¯ªÑ):Ô):¸N×<PÒ<PÑ<RÔ<RÑSÔSˆØ% xÐ0ˆØˆr"   c           	      óŒ  ‡— ‰d         }t          j        ˆfd„t          t          ||¦  «        ¦  «        D ¦   «         ¦  «        }t          j        ‰d         d¬¦  «        }|                      |¦  «        }t          j        ||j        t           j        ¬¦  «        }||                              t           j        ¦  «        ||<   |S )z>
        Create one_hot based on the matching indices
        r&   c                 óž   •— g | ]I\  }\  }\  }}|d k    r*|d         |         t          ‰d         |         ¦  «        z   n|d         |         ‘ŒJS )r   r+   r(   r<   )r-   r?   r/   Ú_ÚJrV   s        €r    r0   zFGroundingDinoImageLoss._get_target_classes_one_hot.<locals>.<listcomp>¬   st   ø€ ð ð ð á'�AÑ'˜¡  Að NOÐQRÊUÈU��~Ô& qÔ)­C°¸Ô0EÀaÔ0HÑ,IÔ,IÑIÐIÐX^Ð_mÔXnÐopÔXqðð ð r"   r(   r   )r2   )rq   rB   )	rC   rI   rS   rJ   Ú_get_source_permutation_idxÚ
zeros_likerq   ÚlongÚto)	rU   rV   r   r`   r&   r+   r(   ÚidxÚtarget_classes_onehots	    `       r    Ú_get_target_classes_one_hotz2GroundingDinoImageLoss._get_target_classes_one_hot¥   sÊ   ø€ ð ˜Ô"ˆå”yðð ð ð å+4µS¸À'Ñ5JÔ5JÑ+KÔ+Kðñ ô ñ
ô 
ˆõ ”Y˜w |Ô4¸!Ð<Ñ<Ô<ˆ
à×.Ò.¨wÑ7Ô7ˆÝ %Ô 0°ÀÄÕUZÔU_Ð `Ñ `Ô `ÐØ%/°Ô%=×%@Ò%@ÅÄÑ%LÔ%LÐ˜cÑ"à$Ð$r"   c                 óV  — d|vrt          d¦  «        ‚d|vrt          d¦  «        ‚|                      |||¦  «        }|d         }|d         }t          j        ||¦  «        }t          j        ||¦  «        }|                     ¦   «         }t          |||| j        d¬¦  «        }d|i}	|	S )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…   rC   Úmasked_selectrv   r!   rm   )
rU   rV   r   r`   r   r„   Úsource_logitsr‡   rˆ   rn   s
             r    Úloss_labelsz"GroundingDinoImageLoss.loss_labels¹   sÖ   € ð
 ˜7Ð"Ð"ÝÐ@ÑAÔAÐAØ˜gÐ%Ð%ÝÐCÑDÔDÐDà $× @Ò @ÀÈ'ÐSZÑ [Ô [ÐØ Ô)ˆØ˜KÔ(ˆ	õ Ô+¨M¸9ÑEÔEˆÝ %Ô 3Ð4IÈ9Ñ UÔ UÐà 5× ;Ò ;Ñ =Ô =ÐÝ$Ø Ø)ØØÔ"Øð
ñ 
ô 
ˆð ˜WÐ%ˆàˆr"   N)
rb   rc   rd   Ú__doc__rk   rC   re   rz   r…   rŒ   r,   r"   r    rg   rg   €   sn   € € € € € ðð ðð ð ð €U„]�_„_ðð ñ „_ðð%ð %ð %ð(ð ð ð ð r"   rg   c                 óŽ  ‡‡‡— t          |j        |j        |j        ¬¦  «        }g d¢}t	          ||j        |¬¦  «        }|                     |¦  «         i }| |d<   ||d<   ||d<   ||d<   d }|j        r$t          ||¦  «        }|D ]}||d<   ||d<   Œ||d<    |||¦  «        Š|j	        rF|	|
||d	œ} |||¦  «        }d
„ | 
                    ¦   «         D ¦   «         }‰                     |¦  «         d|j        |j        dœŠ|j	        r3d„ ‰ 
                    ¦   «         D ¦   «         }‰                     |¦  «         |j        rdi }t          |j        dz
  ¦  «        D ]5Š|                     ˆfd„‰ 
                    ¦   «         D ¦   «         ¦  «         Œ6‰                     |¦  «         t!          ˆˆfd„‰D ¦   «         ¦  «        }|‰|fS )N)rO   rN   rP   )Úlabelsr6   Úcardinality)rl   rm   rn   r&   r'   r(   r‡   Úauxiliary_outputs)r&   r'   r(   r‡   c                 ó    — i | ]\  }}|d z   |“ŒS ©Ú_encr,   ©r-   Úkr8   s      r    ú
<dictcomp>z7GroundingDinoForObjectDetectionLoss.<locals>.<dictcomp>  s"   € ÐQÐQÐQ©t¨q°!˜Q ™Z¨ÐQÐQÐQr"   r9   )rˆ   Ú	loss_bboxÚ	loss_giouc                 ó    — i | ]\  }}|d z   |“ŒS r“   r,   r•   s      r    r—   z7GroundingDinoForObjectDetectionLoss.<locals>.<dictcomp>  s"   € ÐIÐIÐI©T¨Q°˜1˜v™: qÐIÐIÐIr"   r   c                 ó(   •— i | ]\  }}|d ‰› �z   |“ŒS )r}   r,   )r-   r–   r8   r?   s      €r    r—   z7GroundingDinoForObjectDetectionLoss.<locals>.<dictcomp>  s)   ø€ Ð#SÐ#SÐ#S±t°q¸! A¨¨A¨¨¡K°Ð#SÐ#SÐ#Sr"   c              3   óB   •K  — | ]}|‰v ¯‰|         ‰|         z  V — Œd S ri   r,   )r-   r–   Ú	loss_dictÚweight_dicts     €€r    ú	<genexpr>z6GroundingDinoForObjectDetectionLoss.<locals>.<genexpr>  s:   øè è € ÐTÐT°À1ÈÐCSÐCSˆy˜Œ|˜k¨!œnÑ,ÐCSÐCSÐCSÐCSÐTÐTr"   )r$   rO   rN   rP   rg   rm   r‚   Úauxiliary_lossr	   Ú	two_stageÚitemsÚupdateÚbbox_loss_coefficientÚgiou_loss_coefficientÚrangeÚdecoder_layersr   )r&   r�   rq   r'   Úconfigr(   r‡   Úoutputs_classÚoutputs_coordÚencoder_logitsÚencoder_pred_boxesrl   rn   Ú	criterionÚoutputs_lossr‘   Ú
aux_outputÚencoder_outputs_lossÚencoder_loss_dictÚenc_weight_dictÚaux_weight_dictr   r?   r�   rž   s                         @@@r    Ú#GroundingDinoForObjectDetectionLossr´   Ù   sx  øøø€ õ ,ØÔ$°Ô0@ÈFÔL\ðñ ô €Gð 0Ð/Ð/€FÝ&ØØÔ&Øðñ ô €Ið
 ‡L‚L�ÑÔÐà€LØ#€L�ÑØ!+€L�ÑØ!+€L�ÑØ )€L�ÑàÐØÔð >Ý)¨-¸ÑGÔGÐØ+ð 	0ð 	0ˆJØ'1ˆJ�|Ñ$Ø&/ˆJ�{Ñ#Ð#Ø,=ˆÐ(Ñ)à�	˜,¨Ñ/Ô/€IàÔð 	,à$Ø,Ø$Ø"ð	 
ð  
Ðð &˜IÐ&:¸FÑCÔCÐØQÐQÐ7H×7NÒ7NÑ7PÔ7PÐQÑQÔQÐØ×ÒÐ*Ñ+Ô+Ð+ð ØÔ1ØÔ1ðð €Kð Ôð ,ØIÐI°[×5FÒ5FÑ5HÔ5HÐIÑIÔIˆØ×Ò˜?Ñ+Ô+Ð+àÔð ,ØˆÝ�vÔ,¨qÑ0Ñ1Ô1ð 	Uð 	UˆAØ×"Ò"Ð#SÐ#SÐ#SÐ#S¸{×?PÒ?PÑ?RÔ?RÐ#SÑ#SÔ#SÑTÔTÐTÐTØ×Ò˜?Ñ+Ô+Ð+åÐTÐTÐTÐTÐT°iÐTÑTÔTÑTÔT€DØ�Ð-Ð-Ð-r"   )r   r   )NNNN)rC   Útorch.nnr   Úimage_transformsr   Úutilsr   Úloss_for_object_detectionr   r   r	   r
   Úscipy.optimizer   ÚTensorÚintrv   r!   r$   rg   r´   r,   r"   r    ú<module>r¼      s|  ðð €€€Ø Ð Ð Ð Ð Ð à 7Ð 7Ð 7Ð 7Ð 7Ð 7Ø &Ð &Ð &Ð &Ð &Ð &Ø fÐ fÐ fÐ fÐ fÐ fÐ fÐ fÐ fÐ fÐ fÐ fð ÐÑÔð 5Ø4Ð4Ð4Ð4Ð4Ð4ð Øð$"ð $"ØŒLð$"àŒ\ð$"ð ð$"ð ð	$"ð
 ð$"ð $"ð $"ð $"ðN:tð :tð :tð :tð :tÐ$4ñ :tô :tð :tðzVð Vð Vð Vð V˜Yñ Vô Vð VðB ØØØðF.ð F.ð F.ð F.ð F.ð F.r"   