
    ^jv                    j   d Z ddlmZ ddlm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mZmZ ddlmZ dd	lmZ dd
lmZmZ dddZdddZdddZ	 	 	 	 	 	 ddZej6                  j9                  e      Z	 	 	 	 	 	 ddZej6                  j9                  e      Z G d dej@                        Z!y)z2Loss functions and criterion for RF-DETR training.    )annotations)AnyN)nn)compute_l1_keypoint_loss)calculate_uncertainty*get_uncertain_point_coords_with_randomnesspoint_sample)accuracy)box_ops)get_world_sizeis_dist_avail_and_initializedc                   | j                         }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  }|j                  d      j	                         |z  S )a  
    Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002.

    Args:
        inputs: A float tensor of arbitrary shape.
                The predictions for each example.
        targets: A float tensor with the same shape as inputs. Stores the binary
                 classification label for each element in inputs
                (0 for the negative class and 1 for the positive class).
        alpha: (optional) Weighting factor in range (0,1) to balance
                positive vs negative examples. Default = -1 (no weighting).
        gamma: Exponent of the modulating factor (1 - p_t) to
               balance easy vs hard examples.

    Returns:
        Loss tensor
    none	reduction   r   )sigmoidF binary_cross_entropy_with_logitsmeansum)
inputstargets	num_boxesalphagammaprobce_lossp_tlossalpha_ts
             b/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/rfdetr/models/criterion.pysigmoid_focal_lossr#      s    $ >>D00FSG
.AHW5
5Cq3w5()Dz'/QY1w;$??~99Q<	))    c                F   | j                         }||dkD  j                         z  d|z
  ||z
  j                         j                  |      z  |dk  j                         z  z   }t	        j
                  | |d      }||z  }|j                  d      j                         |z  S )N        r   r   r   )r   floatabspowr   r   r   r   )	r   r   r   r   r   r   focal_weightr   r    s	            r"   sigmoid_varifocal_lossr+   =   s    >>D7S=''))QY4'>:N:N:P:T:TUZ:[,[_fjm_m^t^t^v,vv  00FSG\!D99Q<	))r$   c                F   | j                         }t        j                  | |d      }|t        j                  ||z
        |z  z  }|dk\  r5||dkD  j                         z  d|z
  |dk  j                         z  z   }||z  }|j                  d      j                         |z  S )Nr   r   r   r&   r   )r   r   r   torchr(   r'   r   r   )	r   r   r   r   r   r   r   r    r!   s	            r"   position_supervised_lossr.   H   s    >>D00FSGeii$/589Dz7S=//11QY7c>BXBXBZ4ZZ~99Q<	))r$   c                    | j                         } | j                  d      } d| |z  j                  d      z  }| j                  d      |j                  d      z   }d|dz   |dz   z  z
  }|j                         |z  S )a  Compute the DICE loss, similar to generalized IOU for masks.

    Args:
        inputs: A float tensor of arbitrary shape.
                The predictions for each example.
        targets: A float tensor with the same shape as inputs. Stores the binary
                 classification label for each element in inputs
                (0 for the negative class and 1 for the positive class).
    r      )r   flattenr   )r   r   	num_masks	numeratordenominatorr    s         r"   	dice_lossr6   T   sz     ^^F^^AFVg%**2..I**R.7;;r?2K	A+/22D88:	!!r$   c                v    t        j                  | |d      }|j                  d      j                         |z  S )aq  
    Args:
        inputs: A float tensor of arbitrary shape.
                The predictions for each example.
        targets: A float tensor with the same shape as inputs. Stores the binary
                 classification label for each element in inputs
                (0 for the negative class and 1 for the positive class).

    Returns:
        Loss tensor
    r   r   r   )r   r   r   r   )r   r   r3   r    s       r"   sigmoid_ce_lossr8   m   s4      --fgPD99Q<	))r$   c                       e Zd ZU dZdZded<   	 	 	 	 	 	 	 d	 	 	 d fdZedd       Z	 	 	 	 	 	 ddZ	ddZ
 ej                         d	        Zd
 Zd Z	 	 	 	 	 	 	 	 	 	 ddZd Zd Zd Z	 d	 	 	 	 	 	 	 ddZ xZS )SetCriteriona  This class computes the loss for Conditional DETR.

    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).
    Tbool!supports_loss_normalizer_overridec                    t         |           || _        || _        || _        || _        || _        || _        || _        || _	        |	| _
        |
| _        || _        |xs g | _        y)a4  Create the criterion.

        Parameters:
            num_classes: number of object categories, omitting the special no-object category
            matcher: module able to compute a matching between targets and proposals
            weight_dict: dict containing as key the names of the losses and as values their relative weight.
            losses: list of all the losses to be applied. See get_loss for list of available losses.
            focal_alpha: alpha in Focal Loss
            group_detr: Number of groups to speed detr training. Default is 1.
        N)super__init__num_classesmatcherweight_dictlossesfocal_alpha
group_detrsum_group_lossesuse_varifocal_lossuse_position_supervised_lossia_bce_lossmask_point_sample_rationum_keypoints_per_class)selfr@   rA   rB   rD   rC   rE   rF   rG   rH   rI   rJ   rK   	__class__s                r"   r?   zSetCriterion.__init__   sr    2 	&&&$ 0"4,H)&'>$'>'D"$r$   c                    | j                         D ]%  }t        j                  |      s|j                  c S  t	        d      )a  Return the device used by tensor outputs.

        Args:
            outputs: Model output dictionary. Top-level values are probed for tensors;
                nested structures (lists, nested dicts) are not traversed.

        Returns:
            Device of the first tensor value found in ``outputs``.

        Raises:
            ValueError: If no tensor output is present.
        zJSetCriterion requires at least one tensor output to infer the loss device.)valuesr-   	is_tensordevice
ValueError)outputsvalues     r"   _output_devicezSetCriterion._output_device   s>     ^^% 	$Eu%||#	$ effr$   c                |   | j                   r| j                  nd}t        d |D              }| j                  s||z  }t	        j
                  |t        j                  | j                  |            }t               rt        j                  j                  |       t	        j                  |t               z  d      S )a  Compute the distributed target-box denominator for a target batch.

        The denominator is the total number of ground-truth boxes in the batch, multiplied by the active number of
        DETR groups (unless ``sum_group_losses`` collapses them), reduced across all distributed ranks, divided by the
        world size, and finally clamped to be at least ``1.0`` so divide-by-zero never occurs on empty batches.

        Args:
            outputs: Model output dictionary; used only to infer the device for the
                returned scalar tensor.
            targets: Per-image target dictionaries for the current batch. Each must
                contain a ``"labels"`` tensor whose length equals the number of
                ground-truth boxes for that image.

        Returns:
            Scalar tensor on the same device as the model outputs, holding the
            average box-count denominator used to normalize criterion losses.

        Note:
            When ``torch.distributed`` is initialized this method performs an
            in-place ``all_reduce`` collective on the returned tensor. Every rank
            must reach this call together or the program will deadlock.

        Note:
            ``group_detr`` is multiplied in only when ``self.training`` is ``True``.
            During evaluation (``self.training`` is ``False``) the denominator
            collapses to a single group, so train-time and eval-time normalizers
            cannot be compared directly.

        Examples:
            >>> import torch
            >>> from rfdetr.models.criterion import SetCriterion
            >>> criterion = SetCriterion.__new__(SetCriterion)
            >>> criterion.training = False
            >>> criterion.group_detr = 1
            >>> criterion.sum_group_losses = False
            >>> outputs = {"pred_logits": torch.zeros(1, 1, 1)}
            >>> targets = [{"labels": torch.tensor([0, 1, 2])}]
            >>> criterion.num_boxes_for_targets(outputs, targets).item()
            3.0
        r   c              3  8   K   | ]  }t        |d            yw)labelsN)len).0ts     r"   	<genexpr>z5SetCriterion.num_boxes_for_targets.<locals>.<genexpr>   s     :QAhK(:s   dtyperQ   g      ?)min)trainingrE   r   rF   r-   	as_tensorr'   rU   r   distributed
all_reduceclampr   )rL   rS   r   rE   r   num_boxes_tensors         r"   num_boxes_for_targetsz"SetCriterion.num_boxes_for_targets   s    Z )-T__1
:'::	$$!J.I ??9EKKPTPcPcdkPlm(*(()9:{{+n.>>CHHr$   c           	        d|v sJ |d   }| j                  |      }t        j                  t        ||      D 	
cg c]  \  }\  }	}
|d   |
    c}
}	}      }| j                  r| j
                  }d}|d   |   }t        j                  t        ||      D 	cg c]  \  }\  }	}|d   |    c}}	}d      }t        j                  t        j                  t        j                  |j                               t        j                  |            d         }|j                         j                         }|j                         }t        j                  |      }||z  }|D cg c]  }| }}|j                  |       |t        |         j!                  |      |j!                  d|z
        z  }t        j"                  |d	      j                         }|j%                  |j&                        |t        |      <   d|j%                  |j&                        z
  |t        |      <   ||z  t)        j*                  |      ||z   z  z
  }|j-                         |z  }n\| j.                  r|d   |   }t        j                  t        ||      D 	cg c]  \  }\  }	}|d   |    c}}	}d      }t        j                  t        j                  t        j                  |j                               t        j                  |            d         }|j                         j                         }|}t        j0                  |j2                  d   |j2                  d   | j4                  f|j&                  |j6                  
      }|D cg c]  }| }}|j                  |       |j%                  |j&                        }||t        |      <   ||j9                  |j2                  d   dd      j;                  dd      dz   z  }t=        |||| j
                  d      |j2                  d   z  }n| j>                  rr|d   |   }t        j                  t        ||      D 	cg c]  \  }\  }	}|d   |    c}}	}d      }t        j                  t        j                  t        j                  |j                               t        j                  |            d         }|j                         j                         }t        j0                  |j2                  d   |j2                  d   | j4                  f|j&                  |j6                  
      }|D cg c]  }| }}|j                  |       ||t        |      <   tA        |||| j
                  d      |j2                  d   z  }nt        jB                  |j2                  dd | j4                  t        jD                  |j6                  
      }|||<   t        j0                  |j2                  d   |j2                  d   |j2                  d   dz   g|j&                  |jF                  |j6                        }|jI                  d|jK                  d      d       |ddddddf   }tM        |||| j
                  d      |j2                  d   z  }d|i}|rdtO        ||   |      d   z
  |d<   |S c c}
}	}w c c}}	}w c c}w c c}}	}w c c}w c c}}	}w c c}w )zClassification loss (Binary focal loss) targets dicts must contain the key "labels" containing a tensor of
        dim [nb_target_boxes]pred_logitsrX   r0   
pred_boxesboxesr   dimr   g{Gz?r]   r1   Tg:0yE>)r   r   N)r^   layoutrQ   loss_ced   class_error)(_get_src_permutation_idxr-   catziprI   rD   diagr   box_ioubox_cxcywh_to_xyxydetachcloner   
zeros_likeappendtupler)   rd   tor^   r   
logsigmoidr   rH   zerosshaper@   rQ   viewamaxr.   rG   r+   fullint64rm   scatter_	unsqueezer#   r
   ) rL   rS   r   indicesr   log
src_logitsidxr[   _Jtarget_classes_or   r   	src_boxesitarget_boxesiou_targetspos_iousr   pos_weightsneg_weightsidpos_indrn   pos_ious_funccls_iou_func_targetsnorm_cls_iou_func_targetscls_iou_targetstarget_classestarget_classes_onehotrC   s                                    r"   loss_labelszSetCriterion.loss_labels  s    ''']+
++G4 99c'SZF[%\%\FQak!n%\]$$EE-c2I 99SRYEZ%[%[	6Aqajm%[abcL**..y/?/?/AB..|< K #((*113H%%'D**:6K+K$'(br(G(NN+,U7^$((/(,,q5y2IIAAt$++-A*+$${/@/@*AKg'*+add;3D3D.E*EKg' "J.j1I[[fMf1ggGkkmi/G..-c2I 99SRYEZ%[%[	6Aqajm%[abcL**..y/?/?/AB..|< K #((*113H$M#(;;!!!$j&6&6q&94;K;KL &&!(($  %((br(G(NN+,),,-A-G-GHM3@ w0(<$))*>*D*DQ*GQOTTUVX\]`dd)% )-** ""1%&  $$-c2I 99SRYEZ%[%[	6Aqajm%[abcL**..y/?/?/AB..|< K #((*113H#kk!!!$j&6&6q&94;K;KL &&!((O %((br(G(NN+,.6OE'N+&#** ""1%&  #ZZ  !$  kk!((	N #3N3$)KK!!!$j&6&6q&9:;K;KA;NQR;RS &&!((!((	%! "**1n.F.Fr.JAN$9!Q)$D!")** ""1%&  W%$'(:c?DT*UVW*X$XF=!O &] &\ ) &\$ )( &\  )s)   [[$(	[+[0	[7'[<	\c           	     f   |d   }|j                   }t        j                  |D cg c]  }t        |d          c}|      }|j	                  d      |j
                  d   dz
  k7  j                  d      }	t        j                  |	j                         |j                               }
d|
i}|S c c}w )zCompute the cardinality error, ie 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
        rh   rX   rQ   r1   r   cardinality_error)
rQ   r-   ra   rY   argmaxr   r   r   l1_lossr'   )rL   rS   r   r   r   rh   rQ   vtgt_lengths	card_predcard_errrC   s               r"   loss_cardinalityzSetCriterion.loss_cardinality  s     m,##oo&IAs1X;'7&IRXY ''+{/@/@/Dq/HHMMaP	99Y__.0A0A0CD%x0 'Js   B.c           	         d|v sJ | j                  |      }|d   |   }t        j                  t        ||      D 	cg c]  \  }\  }}	|d   |	    c}	}}d      }
t	        j
                  ||
d      }i }|j                         |z  |d<   dt        j                  t        j                  t        j                  |      t        j                  |
                  z
  }|j                         |z  |d	<   |S c c}	}}w )
a'  Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss targets dicts must
        contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4] The target boxes are expected in format
        (center_x, center_y, w, h), normalized by the image size.ri   rj   r   rk   r   r   	loss_bboxr   	loss_giou)rq   r-   rr   rs   r   r   r   rt   r   generalized_box_iourv   )rL   rS   r   r   r   r   r   r[   r   r   r   r   rC   r   s                 r"   
loss_boxeszSetCriterion.loss_boxes  s     w&&&++G4L)#.	yyWgAV!W!WIAv1!G*Q-!W]^_IIiH	'mmo	9{

''**95**<8
 
	 (mmo	9{ "Xs   C9c           	     v   d|v sJ d       | j                  |      }|d   }t        |t        j                        r||   }nD|d   d   }|d   d   }	|d   d   }
|d   j	                         dk(  r$|j
                  }t        j                  g |      }ng }|d   j                  d	      d
   }t        j                  t        j                  |dd
       |fd      j                  d      }t        |j                  d         D ]j  }|d   ||   ||d
z       }|d
   ||   ||d
z       }|	||f   }||d   ||d
z      d
z
        }t        j                  d||      |
z   }|j                  |       l t        j                  |      }|j	                         dk(  r!|j                         |j                         dS t        j                  t!        ||      D cg c]  \  }\  }}|d   |    c}}}d      }|j#                  d
      }|j#                  d
      j%                         }t'        |j                  d   |j                  d   |j                  d   z  | j(                  z        }t        j*                         5  t-        |d |dd      }ddd       t/        |d      j1                  d
      }t        j*                         5  t/        ||dd      j1                  d
      }ddd       t%        |      }t3        ||      t5        |||      d}~~|S c c}}}w # 1 sw Y   xY w# 1 sw Y   FxY w)zCompute BCE-with-logits and Dice losses for segmentation masks on matched pairs.

        Expects outputs to contain 'pred_masks' of shape [B, Q, H, W] and targets with key 'masks'.
        
pred_masksz#pred_masks missing in model outputsspatial_featuresquery_featuresbiasr   r   T)return_countsr   Nrk   zchw,nc->nhw)loss_mask_celoss_mask_dicemasksr1   c                    t        |       S N)r   )logitss    r"   <lambda>z)SetCriterion.loss_masks.<locals>.<lambda>  s    4V< r$      g      ?F)align_cornersnearest)r   mode)rq   
isinstancer-   TensornumelrQ   tensoruniquerr   ry   cumsumranger   einsumrz   r   rs   r   r'   maxrJ   no_gradr   r	   squeezesigmoid_ce_loss_jitdice_loss_jit)rL   rS   r   r   r   r   r   	src_masksr   r   r   rQ   batched_selected_masksper_batch_countsbatch_indicesr   batch_indicatorbox_indicatorthis_batch_queriesthis_batch_spatial_featuresthis_batch_masksr[   r   jtarget_masks
num_pointspoint_coordspoint_logitspoint_labelsnum_boxes_scalarrC   s                                  r"   
loss_maskszSetCriterion.loss_masks  s   
 w&M(MM&++G4\*
j%,,/ #3I&|45GH$\23CDN<(0D1v||~")00!LLF;	)+&#&q6==t=#DQ#G  %		5+;+;<LRa<P+QSc*djk l s stu v/55a89 DA&)!f]1-=aRSe@T&UO$'F=+;mAPQE>R$SM)7-8X)Y&2B3q6-XY\]X]J^abJbCc2d/ )7.
  % +112BC!D$ "II&<=	??! )"+--/ 
 yyWgAV!W!WIAv1!G*Q-!W]^_ ''*	#--a0668OOBOOB)//""559U9UU


 ]]_ 	E<L	 $
 '!*	 	 ]]_ 	'#	
 gaj 	" !+/lL\]+L,HXY

 k "X	 	 	 	s   LL#L/#L,/L8c           	     t   d|v sJ | j                  |      }|d   |   }t        j                  t        ||      D 	cg c]  \  }\  }}	|d   |	    c}	}}d      }
t        j                  t        ||      D 	cg c]  \  }\  }}	|d   |	    c}	}}d      }t        j                  t        ||      D 	cg c]  \  }\  }}	|d   |	    c}	}}d      }|dddf   |ddd	f   z  }t	        ||
j                  |j                        |j                  |j                        |j                  |j                        | j                  
      \  }}}}|j                         |z  |j                         |z  |j                         |z  |j                         |z  dS c c}	}}w c c}	}}w c c}	}}w )z;Compute keypoint losses on matched prediction/target pairs.pred_keypoints	keypointsr   rk   rX   rj   Nr0   r   )all_pred_keypointstarget_keypointsr   target_areasrK   )loss_keypoints_l1loss_keypoints_findableloss_keypoints_visibleloss_keypoints_nll)	rq   r-   rr   rs   r   r|   rQ   rK   r   )rL   rS   r   r   r   r   src_keypointstargetr   r   r   r   r   r   loss_l1loss_findableloss_visibleloss_nlls                     r"   loss_keypointszSetCriterion.loss_keypoints%  s     7***++G4 01#6 99SVW^`gSh%i%i!Qf[&9!&<%iopqcRY[bNc#d#dNFFQF8$4Q$7#djklyy3wX_K`!a!a!Q&/!"4!aghi#AqD)LA,>>9Q,-001E1EF),,]-A-AB%)=)=>$($@$@:
6h ")!:'4'8'8':Y'F&2&6&6&89&D"*,,.9"<	
 	
 &j#d!as   F%>F,=F3c                   t        j                  t        |      D cg c]  \  }\  }}t        j                  ||        c}}}      }t        j                  |D cg c]  \  }}|	 c}}      }||fS c c}}}w c c}}w r   r-   rr   	enumerate	full_like)rL   r   r   srcr   	batch_idxsrc_idxs          r"   rq   z%SetCriterion._get_src_permutation_idxD  sh    II)T[J\]];1hsAusA6]^	))9Xc1S9:'!! ^9   #A7A>
c                   t        j                  t        |      D cg c]  \  }\  }}t        j                  ||        c}}}      }t        j                  |D cg c]  \  }}|	 c}}      }||fS c c}}}w c c}}w r   r   )rL   r   r   r   tgtr   tgt_idxs          r"   _get_tgt_permutation_idxz%SetCriterion._get_tgt_permutation_idxJ  sh    II)T[J\]];1hq#usA6]^	))9XaS9:'!! ^9r   c                    | j                   | j                  | j                  | j                  | j                  d}||v sJ d| d        ||   ||||fi |S )N)rX   cardinalityrj   r   r   zdo you really want to compute z loss?)r   r   r   r   r   )rL   r    rS   r   r   r   kwargsloss_maps           r"   get_losszSetCriterion.get_lossP  sm    &&00____,,
 xN#A$v!NNx~gwMfMMr$   c           
        | j                   r| j                  nd}|j                         D ci c]  \  }}|dk7  s|| }}}| j                  |||      }|| j	                  ||      }n{t        j                  |      s6t        j                  |t
        j                  | j                  |            }n0|j                  | j                  |      t
        j                        }i }	| j                  D ]&  }
|	j                  | j                  |
||||             ( d|v rt        |d         D ]  \  }}| j                  |||      }| j                  D ]^  }
i }|
dk(  rddi} | j                  |
||||fi |}|j                         D ci c]  \  }}|d	| z   | }}}|	j                  |       `  d
|v r|d
   }| j                  |||      }| j                  D ]\  }
i }|
dk(  rd|d<    | j                  |
||||fi |}|j                         D ci c]  \  }}|dz   | }}}|	j                  |       ^ |	S c c}}w c c}}w c c}}w )u   Compute every configured loss for one (outputs, targets) pair.

        The Hungarian matcher is invoked on the last layer's outputs and reused for the auxiliary intermediate layers
        and the optional encoder outputs; each loss is then evaluated on the matched indices and normalized by
        ``num_boxes``.

        Args:
            outputs: Model output dictionary. Must contain the tensors required by
                every loss in ``self.losses`` (for example ``"pred_logits"``,
                ``"pred_boxes"``, ``"pred_masks"``, ``"pred_keypoints"``). May also
                contain ``"aux_outputs"`` (list of layer-wise outputs) and
                ``"enc_outputs"`` (encoder outputs); both are processed identically
                to the last layer and contribute prefixed keys to the returned dict.
            targets: Per-image target dictionaries; ``len(targets) == batch_size``.
                The expected keys depend on the losses being applied — see each
                ``loss_*`` method for its target requirements.
            num_boxes: Optional explicit box-count denominator.

                - ``None`` (default): call :meth:`num_boxes_for_targets` to derive
                  the distributed-reduced normalizer for the current batch.
                - ``float`` / ``int``: cast to a tensor on the model output device
                  and used verbatim. Passing ``1.0`` yields *unnormalized* loss
                  numerators (used by the manual-optimization path so the caller
                  can apply its own accumulated denominator).
                - ``torch.Tensor``: moved to the model output device and used
                  verbatim. The caller is responsible for any cross-rank reduction;
                  no extra all-reduce is performed in this branch.

        Returns:
            Dictionary of named loss tensors. Last-layer losses keep their base
            names (``"loss_ce"``, ``"loss_bbox"``, ``"loss_giou"``,
            ``"loss_mask_ce"``, ``"loss_mask_dice"``, ``"loss_keypoints_*"``).
            Auxiliary-layer losses get a ``"_<i>"`` suffix; encoder-layer losses
            get an ``"_enc"`` suffix.

        Examples:
            >>> import torch
            >>> from unittest.mock import MagicMock
            >>> from rfdetr.models.criterion import SetCriterion
            >>> criterion = SetCriterion.__new__(SetCriterion)
            >>> criterion.training = False
            >>> criterion.group_detr = 1
            >>> criterion.sum_group_losses = False
            >>> criterion.losses = []
            >>> criterion.matcher = MagicMock(return_value=[])
            >>> outputs = {"pred_logits": torch.zeros(1, 1, 1)}
            >>> targets = [{"labels": torch.tensor([0])}]
            >>> criterion.forward(outputs, targets, num_boxes=1.0)
            {}
        r   aux_outputs)rE   r]   )rQ   r^   rX   r   Fr   enc_outputs_enc)r`   rE   itemsrA   rf   r-   rP   ra   r'   rU   r|   rC   updater   r   )rL   rS   r   r   rE   kr   outputs_without_auxr   rC   r    r   r   r   l_dictr   s                   r"   forwardzSetCriterion.forward[  sm   p )-T__1
07V11CUq!tVV ,,2G
,S227GDI+	TM`M`ahMijI!D,?,?,HPUP[P[\I KK 	UDMM$--gwST	U G#"+GM,B"C 	*;,,{G
,S KK *DFx'"'*T]]4gwPYd]cdF9?HAaAaS'k1nHFHMM&)*	* G#!-0Kll;JlOG &8#$)F5M&t['7I`Y_`4:LLNCDAq!f*a-CCf%& U W6 I Ds   III

I)r   FFFF   N)rJ   intrK   zlist[int] | None)rS   dict[str, Any]returnztorch.device)rS   r
  r   list[dict[str, torch.Tensor]]r  torch.Tensor)T)
rS   dictr   listr   r  r   r'   r  dict[str, torch.Tensor]r   )rS   r
  r   r  r   ztorch.Tensor | float | Noner  r  )__name__
__module____qualname____doc__r<   __annotations__r?   staticmethodrU   rf   r   r-   r   r   r   r   r   rq   r   r   r  __classcell__)rM   s   @r"   r:   r:      s.    /3%t2  %*')48%E "%%E "2%EN g g$4I4I /4I 
	4IlN` U]]_ .iV

 
 	

 
 
!
>""	N 26	cc /c /	c
 
!cr$   r:   )g      ?r0   )r   r'   r   r'   )r   r  r   r  r3   r'   )"r  
__future__r   typingr   r-   torch.nn.functionalr   
functionalr   rfdetr.models.heads.keypointsr    rfdetr.models.heads.segmentationr   r   r	   rfdetr.models.mathr
   rfdetr.utilitiesr   rfdetr.utilities.distributedr   r   r#   r+   r.   r6   jitscriptr   r8   r   Moduler:    r$   r"   <module>r%     s    9 "      B 
 ( $ V*<*	*""" ", 		  +*** ** ii&&7 y299 yr$   