
    eTh	>                        S SK r S SKJr  S SKJs  Jr  SSKJr  SSKJ	r	  SSK
JrJr  \" 5       (       a  S SKJr  \ R                  R                   S 5       r\ R                  R                    SS	 j5       rS
\S\ R(                  S\S\ R(                  4S jrS\ R(                  S
\S\S\ R(                  4S jrSS jr " S S\5      r       SS jrg)    N   )is_vision_available   )box_iou)RTDetrHungarianMatcher
RTDetrLoss)center_to_corners_formatc                 R    [        X5       VVs/ s H	  u  p#X#S.PM     snn$ s  snnf )N)logits
pred_boxeszip)outputs_classoutputs_coordabs       U/var/www/auris/envauris/lib/python3.13/site-packages/transformers/loss/loss_d_fine.py_set_aux_lossr      s(    
 8;=7XY7Xtqq*7XYYYs   #c                 l    [        XX#5       VVVV	s/ s H  u  pgpUUUU	UUS.PM     sn	nnn$ s  sn	nnnf )N)r   r   pred_corners
ref_pointsteacher_cornersteacher_logitsr   )
r   r   outputs_cornersoutputs_refr   r   r   r   cds
             r   _set_aux_loss2r   '   sN      mOY
 ZJA! .,	
 Z
 
 
s   .
max_num_binsup	reg_scalereturnc                 :   [        US   5      [        U5      -  n[        US   5      [        U5      -  S-  nUS-   SU S-
  -  -  n[        U S-  S-
  SS5       Vs/ s H  oeU-  * S-   PM     nn[        SU S-  5       Vs/ s H
  oeU-  S-
  PM     nnU* /U-   [        R                  " US   S   5      /-   U-   U/-   n	U	 V
s/ s H)  oR	                  5       S:  a  U
OU
R                  S5      PM+     n	n
[        R                  " U	S5      n	U	$ s  snf s  snf s  sn
f )u  
Generates the non-uniform Weighting Function W(n) for bounding box regression.

Args:
    max_num_bins (int): Max number of the discrete bins.
    up (Tensor): Controls upper bounds of the sequence,
                 where maximum offset is ±up * H / W.
    reg_scale (float): Controls the curvature of the Weighting Function.
                       Larger values result in flatter weights near the central axis W(max_num_bins/2)=0
                       and steeper weights at both ends.
Returns:
    Tensor: Sequence of Weighting Function.
r   r   r   N)absrangetorch
zeros_likedim	unsqueezecat)r   r    r!   upper_bound1upper_bound2stepileft_valuesright_valuesvaluesvs              r   weighting_functionr4   ;   s+    r!u:I.Lr!u:I.2L1!|a'7"89D/4\Q5F5JAr/RS/R!q[>A%/RKS-21la6G-HI-HaK!O-HLIm_{*e.>.>r!uT{.K-LL|[_k^llF<BCFq557Q;aAKKN2FFCYYvq!FM TICs   D D0Dgtc                 n   U R                  S5      n [        XU5      nUR                  S5      U R                  S5      -
  nUS:*  n[        R                  " USS9S-
  nUR                  5       n[        R                  " U5      n	[        R                  " U5      n
US:  X:  -  nX   R                  5       nXL   nXLS-      n[        R                  " X   U-
  5      n[        R                  " XU   -
  5      nXU-   -  X'   SX   -
  X'   US:  nSU	U'   SU
U'   SUU'   X:  nSU	U'   SU
U'   US-
  UU'   XU
4$ )a  
Decodes bounding box ground truth (GT) values into distribution-based GT representations.

This function maps continuous GT values into discrete distribution bins, which can be used
for regression tasks in object detection models. It calculates the indices of the closest
bins to each GT value and assigns interpolation weights to these bins based on their proximity
to the GT value.

Args:
    gt (Tensor): Ground truth bounding box values, shape (N, ).
    max_num_bins (int): Maximum number of discrete bins for the distribution.
    reg_scale (float): Controls the curvature of the Weighting Function.
    up (Tensor): Controls the upper bounds of the Weighting Function.

Returns:
    Tuple[Tensor, Tensor, Tensor]:
        - indices (Tensor): Index of the left bin closest to each GT value, shape (N, ).
        - weight_right (Tensor): Weight assigned to the right bin, shape (N, ).
        - weight_left (Tensor): Weight assigned to the left bin, shape (N, ).
r$   r   r   r)   g      ?g        皙?)	reshaper4   r*   r'   sumfloatr(   longr%   )r5   r   r!   r    function_valuesdiffsmaskclosest_left_indicesindicesweight_rightweight_leftvalid_idx_maskvalid_indicesr0   r1   
left_diffsright_diffsinvalid_idx_mask_neginvalid_idx_mask_poss                      r   translate_gtrJ   T   sy   * 
BB(9EO %%a(2<<?:EA:D 99Tq1A5 #((*G##G,L""7+Klw'=>N+002M "0K"1#45L2-;<J))Ln+==>K $.k1I#JL "%(D"DK #Q;),L%&(+K$%$'G !"2),L%&(+K$%$03$6G !+--    c                 6   [        U5      nU SS2S4   USS2S4   -
  U S   U-  S-   -  SU-  -
  nU SS2S4   USS2S4   -
  U S   U-  S-   -  SU-  -
  nUSS2S4   U SS2S4   -
  U S   U-  S-   -  SU-  -
  nUSS2S	4   U SS2S4   -
  U S   U-  S-   -  SU-  -
  n	[        R                  " XgX/S
5      n
[        XX45      u  pnUb  U
R	                  SX%-
  S9n
U
R                  S
5      R                  5       UR                  5       UR                  5       4$ )a  
Converts bounding box coordinates to distances from a reference point.

Args:
    points (Tensor): (n, 4) [x, y, w, h], where (x, y) is the center.
    bbox (Tensor): (n, 4) bounding boxes in "xyxy" format.
    max_num_bins (float): Maximum bin value.
    reg_scale (float): Controlling curvarture of W(n).
    up (Tensor): Controlling upper bounds of W(n).
    eps (float): Small value to ensure target < max_num_bins.

Returns:
    Tensor: Decoded distances.
Nr   ).r   gؗҜ<      ?r   ).   r   rN   r$   minmax)r%   r'   stackrJ   clampr9   detach)pointsbboxr   r!   r    epslefttoprightbottom	four_lensrB   rC   s                r   bbox2distancer]      sd     II1a4L41:%&.9*Du*LMPSV_P__D!Q$<$q!t*$))Ce)K
LsU^
^C!Q$Z&A,&6&>I+E+MNQTW`Q``E1a4j6!Q$<'F6NY,F,NORUXaRaaFT6;I+7	QZ+_(I[OO|/AOB	R '')<+>+>+@+BTBTBVVVrK   c                   H   ^  \ rS rSrSrU 4S jr SS jrS	S jrS rSr	U =r
$ )
	DFineLoss   a=  
This class computes the losses for D-FINE. 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 (`DetrHungarianMatcher`):
        Module able to compute a matching between targets and proposals.
    weight_dict (`Dict`):
        Dictionary relating each loss with its weights. These losses are configured in DFineConf as
        `weight_loss_vfl`, `weight_loss_bbox`, `weight_loss_giou`, `weight_loss_fgl`, `weight_loss_ddf`
    losses (`List[str]`):
        List of all the losses to be applied. See `get_loss` for a list of all available losses.
    alpha (`float`):
        Parameter alpha used to compute the focal loss.
    gamma (`float`):
        Parameter gamma used to compute the focal loss.
    eos_coef (`float`):
        Relative classification weight applied to the no-object category.
    num_classes (`int`):
        Number of object categories, omitting the special no-object category.
c                   > [         TU ]  U5        [        U5      U l        UR                  U l        UR
                  UR                  UR                  UR                  UR                  S.U l
        / SQU l        UR                  U l        [        R                  " [        R                   " UR"                  /5      SS9U l        g )N)loss_vfl	loss_bbox	loss_giouloss_fglloss_ddf)vflboxeslocalF)requires_grad)super__init__r   matcherr   weight_loss_vflweight_loss_bboxweight_loss_giouweight_loss_fglweight_loss_ddfweight_dictlossesr!   nn	Parameterr'   tensorr    )selfconfig	__class__s     r   rl   DFineLoss.__init__   s     -f5"//..0000....
 0)),,u||VYYK8NrK   c                    UR                  5       nUS-   n	[        R                  " XSS9UR                  S5      -  [        R                  " XSS9UR                  S5      -  -   n
Ub  UR	                  5       nX-  n
Ub  U
R                  5       U-  n
U
$ US:X  a  U
R                  5       n
U
$ US:X  a  U
R                  5       n
U
$ )Nr   none	reductionr$   meanr:   )r<   Fcross_entropyr9   r;   r:   r   )rx   predlabelrB   rC   weightr   
avg_factordis_left	dis_rightlosss              r    unimodal_distribution_focal_loss*DFineLoss.unimodal_distribution_focal_loss   s     ::<qL	t@;CVCVWYCZZ]^]l]lv^
  $^% % \\^F=D!88:
*D  & 99;D  %88:DrK   c           	         0 nSU;   Ga0  U R                  U5      n[        R                  " [        X#5       VV	V
s/ s H  u  nu  pUS   U
   PM     sn
n	nSS9nUS   U   R	                  SU R
                  S-   5      nUS   U   R                  5       n[        R                  " 5          [        U[        U5      U R
                  U R                  U R                  5      U l        SSS5        U R                  u  pn[        R                  " [        [        US	   U   5      [        U5      5      S   5      nUR                  S5      R!                  SSS
5      R	                  S5      R                  5       nU R#                  UUUUUUS9US'   US   R	                  SU R
                  S-   5      nUS   R	                  SU R
                  S-   5      n[        R$                  " X5      (       a  UR'                  5       S-  US'   U$ US   R)                  5       R+                  SS9S   n[        R,                  " U[        R.                  S9nSUU'   UR                  S5      R!                  SSS
5      R	                  S5      nUR1                  UU   5      R3                  UR4                  5      UU'   UR                  S5      R!                  SSS
5      R	                  S5      R                  5       nUUS-  -  [6        R8                  " SS9" [:        R<                  " X-  SS9[:        R>                  " UR                  5       U-  SS95      R'                  S5      -  nSUS	   R@                  S   -  nUR'                  5       U-  S-  U) R'                  5       U-  S-  sU l!        U l"        URG                  5       (       a  UU   RI                  5       OSnU) RG                  5       (       a  UU)    RI                  5       OSnUU RB                  -  UU RD                  -  -   U RB                  U RD                  -   -  US'   U$ s  sn
n	nf ! , (       d  f       GNe= f)zYCompute Fine-Grained Localization (FGL) Loss
and Decoupled Distillation Focal (DDF) Loss.r   rh   r   r7   r$   r   r   Nr      )r   re   r   rf   r   )dtypeTr   r}   r~   rM   )%_get_source_permutation_idxr'   r+   r   r9   r   rT   no_gradr]   r	   r!   r    fgl_targetsdiagr   r*   repeatr   equalr:   sigmoidrQ   r(   bool
reshape_astor   ru   	KLDivLossr   log_softmaxsoftmaxshapenum_posnum_neganyr   )rx   outputstargetsrA   	num_boxesTrt   idxt_r/   target_boxesr   r   target_cornersrB   rC   iousweight_targetsweight_targets_localr?   loss_match_localbatch_scaleloss_match_local1loss_match_local2s                            r   
loss_localDFineLoss.loss_local   s     W$227;C 99SEZ%[EZ	6AajmEZ%[abcL">237??TEVEVYZEZ\L .s3::<J#0,\:%%NNGG$  ! 9=8H8H5N+::01Fs1KLNfgsNtuD
 "^^B/66q!Q?GGKRRTN!%!F!F$ "G "F: #>2::2@Q@QTU@UWL$%67??TEVEVYZEZ\N{{<88%1%5%5%7!%;z"@ = (//?'@'H'H'J'N'NSU'N'VWX'Y$''(<EJJO S	~~b)00Aq9AA"E,0OO<PQT<U,V,Y,YZnZtZt,u$S)';'E'Eb'I'P'PQRTUWX'Y'a'abd'e'l'l'n$ )!t v6MM,*:BIIn&;&;&=&AqI c"g !  ',"7"="=a"@@XXZ+-#5e[[][0S8 +dl FJXXZZ$4T$:$?$?$AUV!HLukkmm$4dU$;$@$@$BYZ!&7$,,&FIZ]a]i]iIi&iLL4<</&z" E &\ !s   P<)<Q
Qc                     U R                   U R                  U R                  U R                  U R                  S.nX;  a  [        SU S35      eXa   " X#XE5      $ )N)cardinalityri   rh   focalrg   zLoss z not supported)loss_cardinalityr   
loss_boxesloss_labels_focalloss_labels_vfl
ValueError)rx   r   r   r   rA   r   loss_maps          r   get_lossDFineLoss.get_loss9  s]    00____++''
 uTF.9::~gCCrK   )	r   rt   rm   r   r   r   r!   r    rs   )Nr:   N)   )__name__
__module____qualname____firstlineno____doc__rl   r   r   r   __static_attributes____classcell__)rz   s   @r   r_   r_      s-    .O" `d.IV
D 
DrK   r_   c           
         [        U5      nUR                  U5        0 nXS'   UR                  SSS9US'   S nUR                  (       Ga  U	Gb  [        R
                  " UR                  SSS9U	S   SS9u  nn[        R
                  " XYS   SS9u  nn[        R
                  " XS   SS9u  nn[        R
                  " XS   SS9u  nn[        US S 2S S	24   R                  SS5      US S 2S S	24   R                  SS5      US S 2S S	24   R                  SS5      US S 2S S	24   R                  SS5      US S 2S	4   US S 2S	4   5      nXS
'   US
   R                  [        U/UR                  SSS9/5      5        [        UR                  SS5      UR                  SS5      UR                  SS5      UR                  SS5      US S 2S	4   US S 2S	4   5      nUUS'   XS'   U" X5      n[        UR                  5       5      nUUU4$ )Nr   r   r   rO   r   dn_num_splitr   r7   r$   auxiliary_outputsdn_auxiliary_outputsdenoising_meta_values)r_   r   rS   auxiliary_lossr'   splitr   	transposeextendr   r:   r2   )r   labelsdevicer   ry   r   r   enc_topk_logitsenc_topk_bboxesr   predicted_cornersinitial_reference_pointskwargs	criterionoutputs_lossr   dn_out_coorddn_out_classdn_out_cornersout_cornersdn_out_refsout_refsr   	loss_dictr   s                            r   DFineForObjectDetectionLossr   F  sa    &!ILLL#!+!1!1aQ!1!?L ,*/++##q#13H3X^_+'L- +0++m[iEjpq*r'L-*/++6G_mIntu*v'NK$)KK0H`nJouv$w!K .a"f%//15a"f%//15AssF#--a3CRC **1a0ArE"ae$! 1B,-,-44//2G2GAST2G2U1VW $2&&q!,&&q!,((A.%%a+q"u%QU#$  4HL/04I01,/Iy!"D---rK   )NN)r8   )NNNNNNN)r'   torch.nnru   torch.nn.functional
functionalr   utilsr   loss_for_object_detectionr   loss_rt_detrr   r   transformers.image_transformsr	   jitunusedr   r   intTensorr4   rJ   r]   r_   r    rK   r   <module>r      s         ' = F Z Z ei &S ell s u|| 2<.U\\ <. <. <.%,, <.~W8TD
 TDz !;.rK   