
    Z j/                         S SK r S SKJs  Jr  SSKJr  SSKJrJ	r	J
r
  SSKJr  \" 5       (       a  S SKJr   " S S	\5      r       SS
 jrg)    N   )is_vision_available   )	DFineLoss_set_aux_loss_set_aux_loss2)box_iou)center_to_corners_formatc                   F   ^  \ rS rSrU 4S jrS rS rS rU 4S jrSr	U =r
$ )
Deimv2Loss   c                    > [         TU ]  U5        UR                  UR                  UR                  UR
                  UR                  S.U l        / SQU l        UR                  U l	        UR                  U l
        g )N)loss_mal	loss_bbox	loss_giouloss_fglloss_ddf)malboxeslocal)super__init__weight_loss_malweight_loss_bboxweight_loss_giouweight_loss_fglweight_loss_ddfweight_dictlosses	mal_alphause_dense_one_to_one)selfconfig	__class__s     n/root/GenerationalWealth/GenerationalWealth/venv/lib/python3.13/site-packages/transformers/loss/loss_deimv2.pyr   Deimv2Loss.__init__   sk     ..0000....
 0))$*$?$?!    c           	      >   U R                  U5      nUS   U   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5      [        U
5      5      u  p[        R                  " U5      R                  5       nUS   n[        R                  " [        X#5       VVV	s/ s H  u  nu  pUS   U	   PM     sn	nn5      n[        R                  " UR                  SS U R                  [        R                  UR                  S	9nXU'   [        R                  " XR                  S
-   S9SSS24   n[        R                  " XR                   S9nUR#                  UR                   5      UU'   UR%                  S5      U-  n[        R&                  " U5      R                  5       nUR)                  U R*                  5      nU R,                  b2  U R,                  UR)                  U R*                  5      -  S
U-
  -  U-   nO$UR)                  U R*                  5      S
U-
  -  U-   n[        R.                  " UUUSS9nUR1                  S
5      R3                  5       UR                  S
   -  U-  nSU0$ s  sn	nnf s  sn	nnf )zCompute the Matching Aware Loss (MAL), which uses IoU-weighted soft labels
instead of hard one-hot targets, with focal-style weighting controlled by `mal_alpha`.

pred_boxesr   r   dimlogitsclass_labelsNr   dtypedevicer   )num_classes.)r/   none)weight	reductionr   )_get_source_permutation_idxtorchcatzipr	   r
   diagdetachfullshaper1   int64r0   Fone_hot
zeros_liker/   to	unsqueezesigmoidpowgammar     binary_cross_entropy_with_logitsmeansum)r"   outputstargetsindices	num_boxesidx	src_boxest_itarget_boxesious
src_logitstarget_classes_originaltarget_classestargettarget_score_originaltarget_score
pred_scorer4   losss                        r%   loss_labels_malDeimv2Loss.loss_labels_mal*   sR    ..w7L)#.	yyWAV!WAVIAv!G*Q-AV!W]^_29=?WXd?efzz$&&(X&
"'))SVW^Sh,iShia!Q~->q-ASh,i"jRa $"2"2%++jN_N_
 6s>7G7G!7KLSRUSURUXV % 0 0GWGW X%)WW-B-H-H%Ic",66r:VCYYz*113
#''

3>>%^^jnnTZZ&@@AJORXXF^^DJJ/1v:>GF11*lSYeklyy|!J$4$4Q$77)CD!!3 "X
 -js   J Jc                    / nU Hy  n[        UR                  5       UR                  5       5       VVs/ s HA  u  pV[        R                  " US   US   /5      [        R                  " US   US   /5      4PMC     nnnM{     U Vs/ s H0  n[        R                  " US   S S 2S 4   US   S S 2S 4   /S5      PM2     sn GH  n[        R                  " USSS9u  p[        R
                  " U
SS9nX   n0 nU H4  nUS   R                  5       US   R                  5       nnX;  d  M0  UX'   M6     [        R                  " [        UR                  5       5      UR                  S9n[        R                  " [        UR                  5       5      UR                  S9nUR                  UR                  5       UR                  5       45        GM     U$ s  snnf s  snf )Nr   r   T)return_countsr+   )
descending)r0   )r9   copyr7   r8   uniqueargsortitemtensorlistkeysr0   valuesappendlong)r"   rL   indices_aux_listresultsindices_auxidx1idx2rN   indexrc   countscount_sort_indicesunique_sortedcolumn_to_rowidx_pairrow_idxcol_idx
final_rows
final_colss                      r%   _get_dense_o2o_indices!Deimv2Loss._get_dense_o2o_indicesL   s   +K #&gllnk6F6F6H"I"IJD DGT!W-.		47DG:L0MN"I  G , SZZRY3eiiQ4#a&D/ BAFRYZE"\\%tKNF!&v$!G"6MM)#+A;#3#3#5x{7G7G7I/-4M* * d=+=+=+?&@VJd=+?+?+A&B5<<XJNNJOO-z/@AB [ #
 [s   AG7Gc                     U R                   U R                  U R                  U R                  U R                  U R
                  S.nX;  a  [        SU S35      eXa   " X#XE5      $ )N)cardinalityr   r   focalvflr   zLoss z not supported)loss_cardinality
loss_local
loss_boxesloss_labels_focalloss_labels_vflr]   
ValueError)r"   r\   rJ   rK   rL   rM   loss_maps          r%   get_lossDeimv2Loss.get_lossb   sf    00____++''''
 uTF.9::~gCCr'   c           
      \  > U R                   (       d  [        TU ]	  X5      $ UR                  5        VVs0 s H  u  p4SU;  d  M  X4_M     nnnU R	                  XR5      n[        S U 5       5      n[        R                  " U/[        R                  [        [        UR                  5       5      5      R                  S9n[        R                  " USS9R                  5       n/ n/ n	SU;   a?  US    H6  n
U R	                  X5      nUR                  U5        U	R                  U5        M8     U R!                  Xi5      n[        S U 5       5      n[        R                  " U/[        R                  [        [        UR                  5       5      5      R                  S9n[        R                  " USS9R                  5       n0 nU R"                   Hz  nUS;   nU(       a  UOUnU(       a  UOUnU R%                  XUUU5      nU Vs0 s H*  o3U R&                  ;   d  M  UUU   U R&                  U   -  _M,     nnUR)                  U5        M|     SU;   a  [+        US   5       H  u  nn
U R"                   H  nUS;   nU(       a  UOUU   nU(       a  UOUnU R%                  XUUU5      nU Vs0 s H*  o3U R&                  ;   d  M  UUU   U R&                  U   -  _M,     nnUR                  5        VVs0 s H  u  p4USU 3-   U_M     nnnUR)                  U5        M     M     S	U;   a  S
U;  a  [-        S5      eU R/                  US
   U5      nXqS
   S   -  n[+        US	   5       H  u  nn
U R"                   H  nU R%                  XUUU5      nU Vs0 s H*  o3U R&                  ;   d  M  UUU   U R&                  U   -  _M,     nnUR                  5        VVs0 s H  u  p4USU 3-   U_M     nnnUR)                  U5        M     M     U$ s  snnf s  snf s  snf s  snnf s  snf s  snnf )aj  
This performs the loss computation.

Args:
     outputs (`dict`, *optional*):
        Dictionary of tensors, see the output specification of the model for the format.
     targets (`list[dict]`, *optional*):
        List of dicts, such that `len(targets) == batch_size`. The expected keys in each dict depends on the
        losses applied, see each loss' doc.
auxiliary_outputsc              3   >   #    U  H  n[        US    5      v   M     g7f)r-   Nlen).0rP   s     r%   	<genexpr>%Deimv2Loss.forward.<locals>.<genexpr>   s     @1An-..   r.   r   )minc              3   >   #    U  H  n[        US    5      v   M     g7f)r   Nr   )r   xs     r%   r   r      s     9j3qt99jr   )r   r   _aux_dn_auxiliary_outputsdenoising_meta_valuesz}The output must have the 'denoising_meta_values` key. Please, ensure that 'outputs' includes a 'denoising_meta_values' entry.dn_num_group_dn_)r!   r   forwarditemsmatcherrI   r7   	as_tensorfloatnextiterri   r0   clampre   rj   r{   r   r   r   update	enumerater   get_cdn_matched_indices)r"   rJ   rK   kvoutputs_without_auxrL   rM   cached_indicesrl   r   aux_indices
indices_gonum_boxes_gor   r\   	use_union
indices_innum_boxes_inl_dictrR   
dn_indicesdn_num_boxesr$   s                          r%   r   Deimv2Loss.forwardo   s    ((7?744 18`CV^_C_tqt`,,2< @@@	OOYKu{{4PTU\UcUcUePfKgKnKno	KK	q1668	 ')%,-@%A!"ll+<F%%k2 ''4 &B 00K
9j99~U[[QUVZ[b[i[i[kVlQmQtQtu{{<Q7<<> KKD 22I'0gJ+4<)L]]4':|TFBHb&QQUQaQaLa8aT%5%5a%888&FbMM&!   ')(1':M2N(O$$ KKD $(: :I/8nQ>OJ3<<)L!]]4GZYefFJPj&QY]YiYiTi@aT-=-=a-@!@@&Fj=C\\^L^TQaE!+oq0^FLMM&) ( )P "W,&g5 ^  55g>U6VX_`J$/F'G'WWL(1':P2Q(R$$ KKD!]]4GZYefFJPj&QY]YiYiTi@aT-=-=a-@!@@&Fj<BLLNKNDAaD*na/NFKMM&)	 ( )S { a< c kL kKs;   PPPP,PP2P
P#+P#P(
)r   r    r!   r   )__name__
__module____qualname____firstlineno__r   r]   r{   r   r   __static_attributes____classcell__)r$   s   @r%   r   r      s&    @ "D,DL Lr'   r   c           
         [        U5      nUR                  U5        XR                  SSS9S.nS nUR                  (       Ga  U	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
                  " X	S   SS9u  nn[        R
                  " X9S   SS9u  nn[        R
                  " XS   SS9u  nn[        R
                  " XS   SS9u  nnUUS'   UR                  SSS9US	'   OUR                  SSS9nUnU
nU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	bg  [        WR                  SS5      WR                  SS5      WR                  SS5      W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   max)r,   r)   dn_num_splitr   r*   r,   r)   r2   r   r   r   )r   rB   r   auxiliary_lossr7   splitr   	transposeextendr   rI   ri   )r,   labelsr0   r)   r#   outputs_classoutputs_coordenc_topk_logitsenc_topk_bboxesr   predicted_cornersinitial_reference_pointskwargs	criterionoutputs_lossr   dn_out_coordnormal_out_coorddn_out_classnormal_out_classrQ   normal_logitsnormal_pred_boxesdn_out_cornersout_cornersdn_out_refsout_refsr   	loss_dictr\   s                                 r%   Deimv2ForObjectDetectionLossr      s    6"ILL$4D4DPQ4D4RSL ,-2[[##q#13H3X^_.*L* .3[[^lHmst-u*L*  %{{63X^_`A}#(;;zQ_;`fg#h A */++6G_mIntu*v'NK$)KK0H`nJouv$w!K%2L"):)@)@QA)@)NL&,22qa2@,+K/H*QV$..q!4QV$..q!43B3))!Q/QV&&q!,2QU#
 ->()()00?+o.C.Cq.C.Q-RS	
 !,#1&&q!,&&q!,((A.%%a+q"u%QU#$  4HL/04I01,/Iy!"D---r'   )NNNNNNN)r7   torch.nn.functionalnn
functionalr?   utilsr   loss_d_finer   r   r   loss_for_object_detectionr	   transformers.image_transformsr
   r   r    r'   r%   <module>r      sV        ' A A . F_ _P !G.r'   