Ë
    S^(hS ã            
       ó  — d Z ddlZddlZddlZddlZddlmZ ddlmZ ddl	m
Z
mZmZmZmZ ddlZddlmc mZ ddlmZm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m Z m!Z!m"Z" d	dl#m$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/m0Z0 d	dl1m2Z2 ddl3m4Z4  e/jj                  e6«      Z7da8d„ Z9 G d„ de«      Z: e,«       rddl;m<Z< ddl=m>Z>  e!«       rddl?m@Z@  e.«       rddlAmBZB  e«       rddlCmDZD  e/jj                  e6«      Z7dZEdZFe G d„ de«      «       ZGe G d „ d!e«      «       ZHe G d"„ d#e«      «       ZId$„ ZJdid%„ZK G d&„ d'ej˜                  «      ZMd(„ ZN G d)„ d*ej˜                  «      ZO G d+„ d,ej˜                  «      ZP G d-„ d.ej˜                  «      ZQd/„ ZRd0ed1ed2ed3ed4ef
d5„ZS G d6„ d7ej˜                  «      ZT G d8„ d9ej˜                  «      ZU G d:„ d;ej˜                  «      ZV G d<„ d=ej˜                  «      ZW G d>„ d?e(«      ZXd@ZYdAZZ G dB„ dCeX«      Z[ G dD„ dEeX«      Z\ edFeY«       G dG„ dHeX«      «       Z] edIeY«       G dJ„ dKeX«      «       Z^dL„ Z_djdMe`dNe`fdO„Za G dP„ dQej˜                  «      Zb G dR„ dSej˜                  «      Zc G dT„ dUej˜                  «      ZddVed4efdW„ZedXed4efdY„ZfdZ„ Zgd[„ Zhd\„ Zi G d]„ d^«      Zjd_ej(                  d`ekdae`dbekfdc„Zldd„ Zm G de„ dfej˜                  «      Zn G dg„ dhej˜                  «      Zoy)kzPyTorch DETA model.é    N)Ú	dataclass)ÚPath)ÚDictÚListÚOptionalÚTupleÚUnion)ÚTensorÚnn)ÚFunction)Úonce_differentiableé   )ÚACT2FN)ÚModelOutputÚadd_start_docstringsÚ%add_start_docstrings_to_model_forwardÚis_scipy_availableÚis_torch_cuda_availableÚis_vision_availableÚreplace_return_docstrings)Ú_prepare_4d_attention_mask)ÚBaseModelOutput)ÚPreTrainedModel)Úmeshgrid)Úis_accelerate_availableÚis_ninja_availableÚis_torchvision_availableÚloggingÚrequires_backends)Úload_backboneé   )Ú
DetaConfigc            	      ót  — ddl m}  t        t        «      j	                  «       j
                  j
                  j
                  dz  dz  }dt        j                  j                  dd«      t        j                  j                  dd	«      fD �cg c]  }||z  ‘Œ	 }} | d
|dt        |«      gdgg d¢¬«       y c c}w )Nr   )ÚloadÚkernelsÚdetaz
vision.cppÚcpuzms_deform_attn_cpu.cppÚcudazms_deform_attn_cuda.cuÚMultiScaleDeformableAttentionTz-DWITH_CUDA=1)z-DCUDA_HAS_FP16=1z-D__CUDA_NO_HALF_OPERATORS__z-D__CUDA_NO_HALF_CONVERSIONS__z-D__CUDA_NO_HALF2_OPERATORS__)Ú	with_cudaÚextra_include_pathsÚextra_cflagsÚextra_cuda_cflags)
Útorch.utils.cpp_extensionr$   r   Ú__file__ÚresolveÚparentÚosÚpathÚjoinÚstr)r$   ÚrootÚfilenameÚ	src_filess       úo/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/modeling_deta.pyÚload_cuda_kernelsr:   7   s¯   € Ý.ô ”‹>×!Ñ!Ó#×*Ñ*×1Ñ1×8Ñ8¸9ÑDÀvÑM€Dð Ü�G‰G�L‰L˜Ð 8Ó9Ü�G‰G�L‰L˜Ð!9Ó:ð
öàð 	ˆx‹ð€Ið ñ 	Ø'ØØÜ  ›Y˜KØ%Ð&ò
öùòs   ÂB5c                   ó6   — e Zd Zed„ «       Zeed„ «       «       Zy)Ú%MultiScaleDeformableAttentionFunctionc                 ó†   — || _         t        j                  |||||| j                   «      }| j                  |||||«       |S ©N)Úim2col_stepr)   Úms_deform_attn_forwardÚsave_for_backward)ÚcontextÚvalueÚvalue_spatial_shapesÚvalue_level_start_indexÚsampling_locationsÚattention_weightsr?   Úoutputs           r9   Úforwardz-MultiScaleDeformableAttentionFunction.forwardV   sZ   € ð *ˆÔÜ.×EÑEØØ Ø#ØØØ×Ñó
ˆð 	×!Ñ!ØÐ'Ð)@ÐBTÐVgô	
ð ˆó    c           	      óˆ   — | j                   \  }}}}}t        j                  ||||||| j                  «      \  }}}	|d d ||	d fS r>   )Úsaved_tensorsr)   Úms_deform_attn_backwardr?   )
rB   Úgrad_outputrC   rD   rE   rF   rG   Ú
grad_valueÚgrad_sampling_locÚgrad_attn_weights
             r9   Úbackwardz.MultiScaleDeformableAttentionFunction.backwardn   sl   € ð ×!Ñ!ñ	
ØØ Ø#ØØä:W×:oÑ:oØØ Ø#ØØØØ×Ñó;
Ñ7ˆ
Ð%Ð'7ð ˜4 Ð'8Ð:JÈDÐPÐPrJ   N)Ú__name__Ú
__module__Ú__qualname__ÚstaticmethodrI   r   rR   © rJ   r9   r<   r<   U   s2   „ Øñó ðð. ØñQó ó ñQrJ   r<   )ÚPartialState)Úreduce)Úcenter_to_corners_format)Úbatched_nms)Úlinear_sum_assignmentr"   zjozhang97/deta-swin-large-o365c                   ó  — e Zd ZU dZdZeej                     ed<   dZ	eej                     ed<   dZ
eej                     ed<   dZeeej                        ed<   dZeeej                        ed<   dZeeej                        ed<   y)	ÚDetaDecoderOutputa	  
    Base class for outputs of the DetaDecoder. This class adds two attributes to
    BaseModelOutputWithCrossAttentions, namely:
    - a stacked tensor of intermediate decoder hidden states (i.e. the output of each decoder layer)
    - a stacked tensor of intermediate reference points.

    Args:
        last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
            Sequence of hidden-states at the output of the last layer of the model.
        intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
            Stacked intermediate hidden states (output of each layer of the decoder).
        intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, sequence_length, hidden_size)`):
            Stacked intermediate reference points (reference points of each layer of the decoder).
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
            shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
            plus the initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
            the self-attention heads.
        cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax,
            used to compute the weighted average in the cross-attention heads.
    NÚlast_hidden_stateÚintermediate_hidden_statesÚintermediate_reference_pointsÚhidden_statesÚ
attentionsÚcross_attentions)rS   rT   rU   Ú__doc__r_   r   ÚtorchÚFloatTensorÚ__annotations__r`   ra   rb   r   rc   rd   rW   rJ   r9   r^   r^   ˜   sš   … ñð6 6:Ð�x × 1Ñ 1Ñ2Ó9Ø>BÐ ¨×):Ñ):Ñ ;ÓBØAEÐ! 8¨E×,=Ñ,=Ñ#>ÓEØ8<€M�8˜E %×"3Ñ"3Ñ4Ñ5Ó<Ø59€J�˜˜u×0Ñ0Ñ1Ñ2Ó9Ø;?Ð�h˜u U×%6Ñ%6Ñ7Ñ8Ô?rJ   r^   c                   ó8  — e Zd ZU dZdZeej                     ed<   dZ	eej                     ed<   dZ
eej                     ed<   dZeej                     ed<   dZeeej                        ed<   dZeeej                        ed<   dZeeej                        ed	<   dZeej                     ed
<   dZeeej                        ed<   dZeeej                        ed<   dZeej                     ed<   dZeej                     ed<   dZeej                     ed<   y)ÚDetaModelOutputaÔ  
    Base class for outputs of the Deformable DETR encoder-decoder model.

    Args:
        init_reference_points (`torch.FloatTensor` of shape  `(batch_size, num_queries, 4)`):
            Initial reference points sent through the Transformer decoder.
        last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
            Sequence of hidden-states at the output of the last layer of the decoder of the model.
        intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
            Stacked intermediate hidden states (output of each layer of the decoder).
        intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
            Stacked intermediate reference points (reference points of each layer of the decoder).
        decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
            shape `(batch_size, num_queries, hidden_size)`. Hidden-states of the decoder at the output of each layer
            plus the initial embedding outputs.
        decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, num_queries,
            num_queries)`. Attentions weights of the decoder, after the attention softmax, used to compute the weighted
            average in the self-attention heads.
        cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_queries, num_heads, 4, 4)`.
            Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the
            weighted average in the cross-attention heads.
        encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder of the model.
        encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
            shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the encoder at the output of each
            layer plus the initial embedding outputs.
        encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_queries, num_heads, 4, 4)`.
            Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
            self-attention heads.
        enc_outputs_class (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
            Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are
            picked as region proposals in the first stage. Output of bounding box binary classification (i.e.
            foreground and background).
        enc_outputs_coord_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
            Logits of predicted bounding boxes coordinates in the first stage.
        output_proposals (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.two_stage=True`):
            Logits of proposal bounding boxes coordinates in the gen_encoder_output_proposals.
    NÚinit_reference_pointsr_   r`   ra   Údecoder_hidden_statesÚdecoder_attentionsrd   Úencoder_last_hidden_stateÚencoder_hidden_statesÚencoder_attentionsÚenc_outputs_classÚenc_outputs_coord_logitsÚoutput_proposals)rS   rT   rU   re   rk   r   rf   rg   rh   r_   r`   ra   rl   r   rm   rd   rn   ro   rp   rq   rr   rs   rW   rJ   r9   rj   rj   ½   sA  … ñ*ðX :>Ð˜8 E×$5Ñ$5Ñ6Ó=Ø59Ð�x × 1Ñ 1Ñ2Ó9Ø>BÐ ¨×):Ñ):Ñ ;ÓBØAEÐ! 8¨E×,=Ñ,=Ñ#>ÓEØ@DÐ˜8 E¨%×*;Ñ*;Ñ$<Ñ=ÓDØ=AÐ˜  u×'8Ñ'8Ñ!9Ñ:ÓAØ;?Ð�h˜u U×%6Ñ%6Ñ7Ñ8Ó?Ø=AÐ˜x¨×(9Ñ(9Ñ:ÓAØ@DÐ˜8 E¨%×*;Ñ*;Ñ$<Ñ=ÓDØ=AÐ˜  u×'8Ñ'8Ñ!9Ñ:ÓAØ59Ð�x × 1Ñ 1Ñ2Ó9Ø<@Ð˜h u×'8Ñ'8Ñ9Ó@Ø48Ð�h˜u×0Ñ0Ñ1Ô8rJ   rj   c                   óª  — e Zd ZU dZdZeej                     ed<   dZ	ee
   ed<   dZeej                     ed<   dZeej                     ed<   dZeee
      ed<   dZeej                     ed<   dZeej                     ed	<   dZeej                     ed
<   dZeej                     ed<   dZeeej                        ed<   dZeeej                        ed<   dZeeej                        ed<   dZeej                     ed<   dZeeej                        ed<   dZeeej                        ed<   dZeed<   dZeed<   dZeej                     ed<   y)ÚDetaObjectDetectionOutputau  
    Output type of [`DetaForObjectDetection`].

    Args:
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
            Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
            bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
            scale-invariant IoU loss.
        loss_dict (`Dict`, *optional*):
            A dictionary containing the individual losses. Useful for logging.
        logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`):
            Classification logits (including no-object) for all queries.
        pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
            Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
            values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
            possible padding). You can use [`~DetaProcessor.post_process_object_detection`] to retrieve the
            unnormalized bounding boxes.
        auxiliary_outputs (`list[Dict]`, *optional*):
            Optional, only returned when auxilary losses are activated (i.e. `config.auxiliary_loss` is set to `True`)
            and labels are provided. It is a list of dictionaries containing the two above keys (`logits` and
            `pred_boxes`) for each decoder layer.
        last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the decoder of the model.
        decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
            shape `(batch_size, num_queries, hidden_size)`. Hidden-states of the decoder at the output of each layer
            plus the initial embedding outputs.
        decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, num_queries,
            num_queries)`. Attentions weights of the decoder, after the attention softmax, used to compute the weighted
            average in the self-attention heads.
        cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_queries, num_heads, 4, 4)`.
            Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the
            weighted average in the cross-attention heads.
        encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder of the model.
        encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
            shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the encoder at the output of each
            layer plus the initial embedding outputs.
        encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_heads, 4,
            4)`. Attentions weights of the encoder, after the attention softmax, used to compute the weighted average
            in the self-attention heads.
        intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
            Stacked intermediate hidden states (output of each layer of the decoder).
        intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
            Stacked intermediate reference points (reference points of each layer of the decoder).
        init_reference_points (`torch.FloatTensor` of shape  `(batch_size, num_queries, 4)`):
            Initial reference points sent through the Transformer decoder.
        enc_outputs_class (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
            Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are
            picked as region proposals in the first stage. Output of bounding box binary classification (i.e.
            foreground and background).
        enc_outputs_coord_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
            Logits of predicted bounding boxes coordinates in the first stage.
        output_proposals (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.two_stage=True`):
            Logits of proposal bounding boxes coordinates in the gen_encoder_output_proposals.
    NÚlossÚ	loss_dictÚlogitsÚ
pred_boxesÚauxiliary_outputsrk   r_   r`   ra   rl   rm   rd   rn   ro   rp   rq   rr   rs   )rS   rT   rU   re   rv   r   rf   rg   rh   rw   r   rx   ry   rz   r   rk   r_   r`   ra   rl   r   rm   rd   rn   ro   rp   rq   rr   rs   rW   rJ   r9   ru   ru   ú   sŒ  … ñ;ðz )-€Dˆ(�5×$Ñ$Ñ
%Ó,Ø $€Iˆx˜‰~Ó$Ø*.€FˆH�U×&Ñ&Ñ'Ó.Ø.2€J�˜×*Ñ*Ñ+Ó2Ø.2Ð�x  T¡
Ñ+Ó2Ø9=Ð˜8 E×$5Ñ$5Ñ6Ó=Ø59Ð�x × 1Ñ 1Ñ2Ó9Ø>BÐ ¨×):Ñ):Ñ ;ÓBØAEÐ! 8¨E×,=Ñ,=Ñ#>ÓEØ@DÐ˜8 E¨%×*;Ñ*;Ñ$<Ñ=ÓDØ=AÐ˜  u×'8Ñ'8Ñ!9Ñ:ÓAØ;?Ð�h˜u U×%6Ñ%6Ñ7Ñ8Ó?Ø=AÐ˜x¨×(9Ñ(9Ñ:ÓAØ@DÐ˜8 E¨%×*;Ñ*;Ñ$<Ñ=ÓDØ=AÐ˜  u×'8Ñ'8Ñ!9Ñ:ÓAØ"&Ð�xÓ&Ø)-Ð˜hÓ-Ø48Ð�h˜u×0Ñ0Ñ1Ô8rJ   ru   c                 óŠ   — t        j                  t        |«      D �cg c]  }t        j                  | «      ‘Œ c}«      S c c}w r>   )r   Ú
ModuleListÚrangeÚcopyÚdeepcopy)ÚmoduleÚNÚis      r9   Ú_get_clonesrƒ   M  s,   € Ü�=‰=¼¸q»ÖB°Aœ$Ÿ-™-¨Õ/ÒBÓCÐCùÒBs   �A c                 ó¦   — | j                  dd¬«      } | j                  |¬«      }d| z
  j                  |¬«      }t        j                  ||z  «      S )Nr   r!   ©ÚminÚmax©r†   )Úclamprf   Úlog)ÚxÚepsÚx1Úx2s       r9   Úinverse_sigmoidr�   Q  sK   € Ø	�‰�A˜1ˆÓ€AØ	
�‰�SˆÓ	€BØ
ˆa‰%�‰˜3ˆÓ	€BÜ�9‰9�R˜"‘WÓÐrJ   c                   ó2   ‡ — e Zd ZdZˆ fd„Zˆ fd„Zd„ Zˆ xZS )ÚDetaFrozenBatchNorm2dzú
    BatchNorm2d where the batch statistics and the affine parameters are fixed.

    Copy-paste from torchvision.misc.ops with added eps before rqsrt, without which any other models than
    torchvision.models.resnet[18,34,50,101] produce nans.
    c                 óJ  •— t         ‰| �  «        | j                  dt        j                  |«      «       | j                  dt        j
                  |«      «       | j                  dt        j
                  |«      «       | j                  dt        j                  |«      «       y )NÚweightÚbiasÚrunning_meanÚrunning_var)ÚsuperÚ__init__Úregister_bufferrf   ÚonesÚzeros)ÚselfÚnÚ	__class__s     €r9   r˜   zDetaFrozenBatchNorm2d.__init__`  sn   ø€ Ü‰ÑÔØ×Ñ˜X¤u§z¡z°!£}Ô5Ø×Ñ˜V¤U§[¡[°£^Ô4Ø×Ñ˜^¬U¯[©[¸«^Ô<Ø×Ñ˜]¬E¯J©J°q«MÕ:rJ   c           	      óH   •— |dz   }||v r||= t         ‰	| �  |||||||«       y )NÚnum_batches_tracked)r—   Ú_load_from_state_dict)
rœ   Ú
state_dictÚprefixÚlocal_metadataÚstrictÚmissing_keysÚunexpected_keysÚ
error_msgsÚnum_batches_tracked_keyrž   s
            €r9   r¡   z+DetaFrozenBatchNorm2d._load_from_state_dictg  s?   ø€ ð #)Ð+@Ñ"@ÐØ" jÑ0ØÐ2Ð3ä‰Ñ%Ø˜ °¸ÀoÐWaõ	
rJ   c                 óB  — | j                   j                  dddd«      }| j                  j                  dddd«      }| j                  j                  dddd«      }| j                  j                  dddd«      }d}|||z   j                  «       z  }|||z  z
  }||z  |z   S )Nr!   éÿÿÿÿçñhãˆµøä>)r“   Úreshaper”   r–   r•   Úrsqrt)rœ   r‹   r“   r”   r–   r•   ÚepsilonÚscales           r9   rI   zDetaFrozenBatchNorm2d.forwardr  s«   € ð —‘×$Ñ$ Q¨¨A¨qÓ1ˆØ�y‰y× Ñ   B¨¨1Ó-ˆØ×&Ñ&×.Ñ.¨q°"°a¸Ó;ˆØ×(Ñ(×0Ñ0°°B¸¸1Ó=ˆØˆØ˜+¨Ñ/×6Ñ6Ó8Ñ8ˆØ�l UÑ*Ñ*ˆØ�5‰y˜4ÑÐrJ   )rS   rT   rU   re   r˜   r¡   rI   Ú__classcell__©rž   s   @r9   r‘   r‘   X  s   ø„ ñô;ô	
ö
 rJ   r‘   c                 óê  — | j                  «       D �]_  \  }}t        |t        j                  «      �rt	        |j
                  «      }|j                  j                  t        j                  d«      k(  s¼|j                  j                  j                  |j                  «       |j                  j                  j                  |j                  «       |j                  j                  j                  |j                  «       |j                  j                  j                  |j                  «       || j                  |<   t        t!        |j#                  «       «      «      dkD  s�ŒUt%        |«       �Œb y)zš
    Recursively replace all `torch.nn.BatchNorm2d` with `DetaFrozenBatchNorm2d`.

    Args:
        model (torch.nn.Module):
            input model
    Úmetar   N)Únamed_childrenÚ
isinstancer   ÚBatchNorm2dr‘   Únum_featuresr“   Údevicerf   ÚdataÚcopy_r”   r•   r–   Ú_modulesÚlenÚlistÚchildrenÚreplace_batch_norm)ÚmodelÚnamer€   Ú
new_modules       r9   rÀ   rÀ     s  € ð ×,Ñ,Ó.ó '‰ˆˆfÜ�fœbŸn™nÕ-Ü.¨v×/BÑ/BÓCˆJà—=‘=×'Ñ'¬5¯<©<¸Ó+?Ò?Ø×!Ñ!×&Ñ&×,Ñ,¨V¯]©]Ô;Ø—‘×$Ñ$×*Ñ*¨6¯;©;Ô7Ø×'Ñ'×,Ñ,×2Ñ2°6×3FÑ3FÔGØ×&Ñ&×+Ñ+×1Ñ1°&×2DÑ2DÔEà#-ˆE�N‰N˜4Ñ äŒt�F—O‘OÓ%Ó&Ó'¨!Ô+Ü˜vÖ&ñ'rJ   c                   óZ   ‡ — e Zd ZdZˆ fd„Zdej                  dej                  fd„Zˆ xZS )Ú#DetaBackboneWithPositionalEncodingsz‡
    Backbone model with positional embeddings.

    nn.BatchNorm2d layers are replaced by DetaFrozenBatchNorm2d as defined above.
    c                 óº  •— t         ‰| �  «        t        |«      }t        j                  «       5  t        |«       d d d «       || _        | j                  j                  | _        |j                  j                  dk(  rB| j                  j                  «       D ]%  \  }}d|vsŒd|vsŒd|vsŒ|j                  d«       Œ' t        |«      | _        y # 1 sw Y   Œ—xY w)NÚresnetzstages.1zstages.2zstages.3F)r—   r˜   r    rf   Úno_gradrÀ   rÁ   ÚchannelsÚintermediate_channel_sizesÚbackbone_configÚ
model_typeÚnamed_parametersÚrequires_grad_Úbuild_position_encodingÚposition_embedding)rœ   ÚconfigÚbackbonerÂ   Ú	parameterrž   s        €r9   r˜   z,DetaBackboneWithPositionalEncodings.__init__ž  sÁ   ø€ Ü‰ÑÔä  Ó(ˆÜ�]‰]‹_ñ 	)Ü˜xÔ(÷	)àˆŒ
Ø*.¯*©*×*=Ñ*=ˆÔ'ð ×!Ñ!×,Ñ,°Ò8Ø#'§:¡:×#>Ñ#>Ó#@ò 4‘��iØ TÒ)¨jÀÒ.DÈÐ[_ÒI_Ø×,Ñ,¨UÕ3ð4ô #:¸&Ó"AˆÕ÷	)ð 	)ús   ¯CÃCÚpixel_valuesÚ
pixel_maskc                 ó²  — | j                  |«      j                  }g }g }|D ]°  }t        j                  j	                  |d   j                  «       |j                  dd ¬«      j                  t        j                  «      d   }| j                  ||«      j                  |j                  «      }|j                  ||f«       |j                  |«       Œ² ||fS )z¤
        Outputs feature maps of latter stages C_3 through C_5 in ResNet if `config.num_feature_levels > 1`, otherwise
        outputs feature maps of C_5.
        Néþÿÿÿ©Úsizer   )rÁ   Úfeature_mapsr   Ú
functionalÚinterpolateÚfloatÚshapeÚtorf   ÚboolrÐ   ÚdtypeÚappend)	rœ   rÔ   rÕ   ÚfeaturesÚoutÚposÚfeature_mapÚmaskÚposition_embeddingss	            r9   rI   z+DetaBackboneWithPositionalEncodings.forward¯  sÏ   € ð —:‘:˜lÓ+×8Ñ8ˆð ˆØˆØ#ò 	,ˆKä—=‘=×,Ñ,¨Z¸Ñ-=×-CÑ-CÓ-EÈK×L]ÑL]Ð^`Ð^aÐLbÐ,Óc×fÑfÔgl×gqÑgqÓrÐstÑuˆDØ"&×"9Ñ"9¸+ÀtÓ"L×"OÑ"OÐP[×PaÑPaÓ"bÐØ�J‰J˜ TÐ*Ô+Ø�J‰JÐ*Õ+ð	,ð �CˆxˆrJ   )	rS   rT   rU   re   r˜   rf   r
   rI   r±   r²   s   @r9   rÅ   rÅ   —  s)   ø„ ñôBð" E§L¡Lð ¸e¿l¹l÷ rJ   rÅ   c                   ó*   ‡ — e Zd ZdZdˆ fd„	Zd„ Zˆ xZS )ÚDetaSinePositionEmbeddingz¬
    This is a more standard version of the position embedding, very similar to the one used by the Attention is all you
    need paper, generalized to work on images.
    c                 ó¦   •— t         ‰| �  «        || _        || _        || _        |�|du rt        d«      ‚|€dt        j                  z  }|| _        y )NFz+normalize should be True if scale is passedé   )	r—   r˜   Úembedding_dimÚtemperatureÚ	normalizeÚ
ValueErrorÚmathÚpir°   )rœ   rí   rî   rï   r°   rž   s        €r9   r˜   z"DetaSinePositionEmbedding.__init__Ê  sW   ø€ Ü‰ÑÔØ*ˆÔØ&ˆÔØ"ˆŒØÐ ¨eÑ!3ÜÐJÓKÐKØˆ=ØœŸ™‘KˆEØˆ�
rJ   c           
      óx  — |€t        d«      ‚|j                  dt        j                  ¬«      }|j                  dt        j                  ¬«      }| j                  rJd}|dz
  |d d …dd …d d …f   |z   z  | j
                  z  }|dz
  |d d …d d …dd …f   |z   z  | j
                  z  }t        j                  | j                  t        j                  |j                  ¬«      j                  «       }| j                  dt        j                  |dd	¬
«      z  | j                  z  z  }|d d …d d …d d …d f   |z  }|d d …d d …d d …d f   |z  }t        j                  |d d …d d …d d …dd d…f   j                  «       |d d …d d …d d …dd d…f   j                  «       fd¬«      j!                  d«      }t        j                  |d d …d d …d d …dd d…f   j                  «       |d d …d d …d d …dd d…f   j                  «       fd¬«      j!                  d«      }t        j"                  ||fd¬«      j%                  dddd«      }	|	S )NzNo pixel mask providedr!   ©rá   rì   g�íµ ÷Æ°>ç      à?r«   ©rá   r¹   Úfloor©Úrounding_moder   r   ©Údimé   )rð   Úcumsumrf   Úfloat32rï   r°   Úarangerí   Úint64r¹   rÝ   rî   ÚdivÚstackÚsinÚcosÚflattenÚcatÚpermute)
rœ   rÔ   rÕ   Úy_embedÚx_embedrŒ   Údim_tÚpos_xÚpos_yrå   s
             r9   rI   z!DetaSinePositionEmbedding.forwardÕ  s	  € ØÐÜÐ5Ó6Ð6Ø×#Ñ# A¬U¯]©]Ð#Ó;ˆØ×#Ñ# A¬U¯]©]Ð#Ó;ˆØ�>Š>ØˆCØ ‘}¨²°B±Cº°Ñ);¸cÑ)AÑBÀTÇZÁZÑOˆGØ ‘}¨²²A°r±s°Ñ);¸cÑ)AÑBÀTÇZÁZÑOˆGä—‘˜T×/Ñ/´u·{±{È<×K^ÑK^Ô_×eÑeÓgˆØ× Ñ  Q¬¯©°5¸!È7Ô)SÑ%SÐVZ×VhÑVhÑ%hÑiˆàšš1ša ˜Ñ&¨Ñ.ˆØšš1ša ˜Ñ&¨Ñ.ˆÜ—‘˜U¢1¢aª¨A¨D¨q¨D =Ñ1×5Ñ5Ó7¸ºqÂ!ÂQÈÈÈ1È¸}Ñ9M×9QÑ9QÓ9SÐTÐZ[Ô\×dÑdÐefÓgˆÜ—‘˜U¢1¢aª¨A¨D¨q¨D =Ñ1×5Ñ5Ó7¸ºqÂ!ÂQÈÈÈ1È¸}Ñ9M×9QÑ9QÓ9SÐTÐZ[Ô\×dÑdÐefÓgˆÜ�i‰i˜ ˜¨AÔ.×6Ñ6°q¸!¸QÀÓBˆØˆ
rJ   )é@   é'  FN©rS   rT   rU   re   r˜   rI   r±   r²   s   @r9   rê   rê   Ä  s   ø„ ñõ
	örJ   rê   c                   ó,   ‡ — e Zd ZdZdˆ fd„	Zdd„Zˆ xZS )ÚDetaLearnedPositionEmbeddingzN
    This module learns positional embeddings up to a fixed maximum size.
    c                 óŽ   •— t         ‰| �  «        t        j                  d|«      | _        t        j                  d|«      | _        y )Né2   )r—   r˜   r   Ú	EmbeddingÚrow_embeddingsÚcolumn_embeddings)rœ   rí   rž   s     €r9   r˜   z%DetaLearnedPositionEmbedding.__init__ï  s4   ø€ Ü‰ÑÔÜ Ÿl™l¨2¨}Ó=ˆÔÜ!#§¡¨b°-Ó!@ˆÕrJ   c                 ó.  — |j                   dd  \  }}t        j                  ||j                  ¬«      }t        j                  ||j                  ¬«      }| j	                  |«      }| j                  |«      }t        j                  |j                  d«      j                  |dd«      |j                  d«      j                  d|d«      gd¬«      }	|	j                  ddd«      }	|	j                  d«      }	|	j                  |j                   d   ddd«      }	|	S )Nr×   ©r¹   r   r!   r«   rú   rì   )
rÞ   rf   rÿ   r¹   r  r  r  Ú	unsqueezeÚrepeatr  )
rœ   rÔ   rÕ   ÚheightÚwidthÚwidth_valuesÚheight_valuesÚx_embÚy_embrå   s
             r9   rI   z$DetaLearnedPositionEmbedding.forwardô  sò   € Ø$×*Ñ*¨2¨3Ð/‰ˆ�Ü—|‘| E°,×2EÑ2EÔFˆÜŸ™ V°L×4GÑ4GÔHˆØ×&Ñ& |Ó4ˆØ×#Ñ# MÓ2ˆÜ�i‰i˜Ÿ™¨Ó+×2Ñ2°6¸1¸aÓ@À%Ç/Á/ÐRSÓBT×B[ÑB[Ð\]Ð_dÐfgÓBhÐiÐoqÔrˆØ�k‰k˜!˜Q Ó"ˆØ�m‰m˜AÓˆØ�j‰j˜×+Ñ+¨AÑ.°°1°aÓ8ˆØˆ
rJ   )é   r>   r  r²   s   @r9   r  r  ê  s   ø„ ñõA÷

rJ   r  c                 óÄ   — | j                   dz  }| j                  dk(  rt        |d¬«      }|S | j                  dk(  rt        |«      }|S t	        d| j                  › �«      ‚)Nrì   ÚsineT)rï   ÚlearnedzNot supported )Úd_modelÚposition_embedding_typerê   r  rð   )rÑ   Ún_stepsrÐ   s      r9   rÏ   rÏ     sq   € Ø�n‰n Ñ!€GØ×%Ñ%¨Ò/ä6°wÈ$ÔOÐð Ðð 
×	'Ñ	'¨9Ò	4Ü9¸'ÓBÐð Ðô ˜>¨&×*HÑ*HÐ)IÐJÓKÐKrJ   rC   rD   rF   rG   Úreturnc           	      ó†  — | j                   \  }}}}|j                   \  }}}}	}
}| j                  |D ��cg c]&  \  }}|j                  «       |j                  «       z  ‘Œ( c}}d¬«      }d|z  dz
  }g }t        |«      D ]¥  \  }\  }}||   j	                  d«      j                  dd«      j                  ||z  |||«      }|d d …d d …d d …|f   j                  dd«      j	                  dd«      }t        j                  j                  ||ddd¬«      }|j                  |«       Œ§ |j                  dd«      j                  ||z  d||	|
z  «      }t        j                  |d	¬«      j	                  d	«      |z  j                  d
«      j                  |||z  |«      }|j                  dd«      j                  «       S c c}}w )Nr!   rú   rì   r   Úbilinearr›   F)ÚmodeÚpadding_modeÚalign_cornersr×   r«   )rÞ   ÚsplitÚitemÚ	enumerater  Ú	transposer­   r   rÛ   Úgrid_samplerâ   rf   r  ÚsumÚviewÚ
contiguous)rC   rD   rF   rG   Ú
batch_sizeÚ_Ú	num_headsÚ
hidden_dimÚnum_queriesÚ
num_levelsÚ
num_pointsr  r  Ú
value_listÚsampling_gridsÚsampling_value_listÚlevel_idÚvalue_l_Úsampling_grid_l_Úsampling_value_l_rH   s                        r9   Ú multi_scale_deformable_attentionrD    sÛ  € ð ,1¯;©;Ñ(€J��9˜jØ;M×;SÑ;SÑ8€A€{�I˜z¨:°qØ—‘ÐPd×e¹}¸vÀu˜fŸk™k›m¨e¯j©j«lÓ:ÓeÐkl�Óm€JØÐ+Ñ+¨aÑ/€NØÐÜ%.Ð/CÓ%Dò 6Ñ!ˆ‘/�6˜5ð �xÑ ×(Ñ(¨Ó+×5Ñ5°a¸Ó;×CÑCÀJÐQZÑDZÐ\fÐhnÐpuÓvð 	ð *ª!ªQ²°8Ð*;Ñ<×FÑFÀqÈ!ÓL×TÑTÐUVÐXYÓZÐäŸM™M×5Ñ5ØÐ&¨ZÀgÐ]bð 6ó 
Ðð 	×"Ñ"Ð#4Õ5ð!6ð( *×3Ñ3°A°qÓ9×AÑAØ�YÑ  ;°
¸ZÑ0GóÐô 
�‰Ð(¨bÔ	1×	9Ñ	9¸"Ó	=Ð@QÑ	Qß	‰ˆR‹ß	‰ˆj˜) jÑ0°+Ó	>ð ð
 ×Ñ˜A˜qÓ!×,Ñ,Ó.Ð.ùó? fs   µ+F=
c            	       óÒ   ‡ — e Zd ZdZdededefˆ fd„Zd„ Zdej                  de
e	   fd	„Z	 	 	 	 	 	 	 	 dd
ej                  de
ej                     de
ej                     defd„Zˆ xZS )Ú!DetaMultiscaleDeformableAttentionzI
    Multiscale deformable attention as proposed in Deformable DETR.
    rÑ   r8  Ún_pointsc                 óÚ  •— t         ‰| �  «        t        d u}t        «       rt	        «       r|s	 t        «        |j                  |z  dk7  rt        d|j                  › d|› �«      ‚|j                  |z  }||dz
  z  dk(  r|dk7  st        j                  d«       d| _        |j                  | _	        |j                  | _        || _        || _        t%        j&                  |j                  || j                  z  |z  dz  «      | _        t%        j&                  |j                  || j                  z  |z  «      | _        t%        j&                  |j                  |j                  «      | _        t%        j&                  |j                  |j                  «      | _        |j0                  | _        | j3                  «        y # t        $ r#}t        j                  d|› �«       Y d }~�Œ¬d }~ww xY w)	NzGCould not load the custom kernel for multi-scale deformable attention: r   z<embed_dim (d_model) must be divisible by num_heads, but got z and r!   zÀYou'd better set embed_dim (d_model) in DetaMultiscaleDeformableAttention to make the dimension of each attention head a power of 2 which is more efficient in the authors' CUDA implementation.r  rì   )r—   r˜   r)   r   r   r:   Ú	ExceptionÚloggerÚwarningr%  rð   ÚwarningsÚwarnr?   Únum_feature_levelsÚn_levelsÚn_headsrG  r   ÚLinearÚsampling_offsetsrG   Ú
value_projÚoutput_projÚdisable_custom_kernelsÚ_reset_parameters)rœ   rÑ   r8  rG  Úkernel_loadedÚeÚdim_per_headrž   s          €r9   r˜   z*DetaMultiscaleDeformableAttention.__init__:  s¢  ø€ Ü‰ÑÔä5¸TÐAˆÜ"Ô$Ô);Ô)=ÁmðnÜ!Ô#ð �>‰>˜IÑ%¨Ò*ÜØNÈvÏ~É~ÐN^Ð^cÐdmÐcnÐoóð ð —~‘~¨Ñ2ˆà °Ñ!1Ñ2°aÒ7¸\ÈQÒ=NÜ�M‰Mð#ôð ˆÔà—~‘~ˆŒØ×1Ñ1ˆŒØ ˆŒØ ˆŒä "§	¡	¨&¯.©.¸)ÀdÇmÁmÑ:SÐV^Ñ:^ÐabÑ:bÓ cˆÔÜ!#§¡¨6¯>©>¸9ÀtÇ}Á}Ñ;TÐW_Ñ;_Ó!`ˆÔÜŸ)™) F§N¡N°F·N±NÓCˆŒÜŸ9™9 V§^¡^°V·^±^ÓDˆÔà&,×&CÑ&CˆÔ#à×ÑÕ øô= ò nÜ—‘Ð!hÐijÐhkÐl×mÒmûðnús   ¯
F> Æ>	G*ÇG%Ç%G*c                 ó¦  — t         j                  j                  | j                  j                  j
                  d«       t        j                  «       }t        j                  | j                  t        j                  ¬«      j                  |«      dt        j                  z  | j                  z  z  }t        j                  |j                  «       |j!                  «       gd«      }||j#                  «       j%                  dd¬«      d   z  j'                  | j                  ddd	«      j)                  d| j*                  | j,                  d«      }t/        | j,                  «      D ]  }|d d …d d …|d d …fxx   |dz   z  cc<   Œ t        j0                  «       5  t        j2                  |j'                  d«      «      | j                  _        d d d «       t         j                  j                  | j6                  j                  j
                  d«       t         j                  j                  | j6                  j4                  j
                  d«       t         j                  j9                  | j:                  j                  j
                  «       t         j                  j                  | j:                  j4                  j
                  d«       t         j                  j9                  | j<                  j                  j
                  «       t         j                  j                  | j<                  j4                  j
                  d«       y # 1 sw Y   �Œ}xY w)
Nç        rô   ç       @r«   T©Úkeepdimr   r!   rì   )r   ÚinitÚ	constant_rR  r“   rº   rf   Úget_default_dtyperÿ   rP  r   rß   rñ   rò   r  r  r  Úabsr‡   r4  r  rO  rG  r}   rÈ   Ú	Parameterr”   rG   Úxavier_uniform_rS  rT  )rœ   Údefault_dtypeÚthetasÚ	grid_initr‚   s        r9   rV  z3DetaMultiscaleDeformableAttention._reset_parametersa  s@  € Ü
�‰×Ñ˜$×/Ñ/×6Ñ6×;Ñ;¸SÔAÜ×/Ñ/Ó1ˆÜ—‘˜dŸl™l´%·+±+Ô>×AÑAÀ-ÓPÐTWÔZ^×ZaÑZaÑTaÐdh×dpÑdpÑTpÑqˆÜ—K‘K §¡£¨v¯z©z«|Ð <¸bÓAˆ	à˜Ÿ™›×,Ñ,¨R¸Ð,Ó>¸qÑAÑAß‰T�$—,‘,  1 aÓ(ß‰V�A�t—}‘} d§m¡m°QÓ7ð 	ô
 �t—}‘}Ó%ò 	+ˆAØ’aš˜Ašq�jÓ! Q¨¡UÑ*Ô!ð	+ä�]‰]‹_ñ 	JÜ)+¯©°i·n±nÀRÓ6HÓ)IˆD×!Ñ!Ô&÷	Jä
�‰×Ñ˜$×0Ñ0×7Ñ7×<Ñ<¸cÔBÜ
�‰×Ñ˜$×0Ñ0×5Ñ5×:Ñ:¸CÔ@Ü
�‰×Ñ §¡× 6Ñ 6× ;Ñ ;Ô<Ü
�‰×Ñ˜$Ÿ/™/×.Ñ.×3Ñ3°SÔ9Ü
�‰×Ñ × 0Ñ 0× 7Ñ 7× <Ñ <Ô=Ü
�‰×Ñ˜$×*Ñ*×/Ñ/×4Ñ4°cÕ:÷	Jñ 	Jús   Æ4MÍMÚtensorrè   c                 ó   — |€|S ||z   S r>   rW   ©rœ   rh  rè   s      r9   Úwith_pos_embedz0DetaMultiscaleDeformableAttention.with_pos_embedv  ó   € Ø,Ð4ˆvÐV¸&ÐCVÑ:VÐVrJ   rb   Úattention_maskÚoutput_attentionsc
           
      ó~  — |�| j                  ||«      }|j                  \  }
}}|j                  \  }
}}|d d …df   |d d …df   z  j                  «       |k7  rt        d«      ‚| j	                  |«      }|�|j                  |d    t        d«      «      }|j                  |
|| j                  | j                  | j                  z  «      }| j                  |«      j                  |
|| j                  | j                  | j                  d«      }| j                  |«      j                  |
|| j                  | j                  | j                  z  «      }t        j                  |d«      j                  |
|| j                  | j                  | j                  «      }|j                  d   }|dk(  rEt!        j"                  |d   |d   gd«      }|d d …d d …d d d …d d d …f   ||d d d d d …d d d …f   z  z   }n[|d	k(  r;|d d …d d …d d d …d d d…f   || j                  z  |d d …d d …d d d …d dd …f   z  d
z  z   }nt        d|j                  d   › �«      ‚| j$                  rt'        ||||«      }n%	 t(        j+                  |||||| j,                  «      }| j1                  |«      }||fS # t.        $ r t'        ||||«      }Y Œ.w xY w)Nr   r!   z[Make sure to align the spatial shapes with the sequence length of the encoder hidden states).Nrì   r«   ).r!   ©.r   r   rõ   z5Last dim of reference_points must be 2 or 4, but got )rk  rÞ   r3  rð   rS  Úmasked_fillrÝ   r4  rP  r%  rR  rO  rG  rG   ÚFÚsoftmaxrf   r  rU  rD  r<   Úapplyr?   rI  rT  )rœ   rb   rm  ro   Úencoder_attention_maskrè   Úreference_pointsÚspatial_shapesÚlevel_start_indexrn  r6  r:  r7  Úsequence_lengthrC   rR  rG   Únum_coordinatesÚoffset_normalizerrF   rH   s                        r9   rI   z)DetaMultiscaleDeformableAttention.forwardy  sÿ  € ð Ð*Ø ×/Ñ/°Ð?RÓSˆMà%2×%8Ñ%8Ñ"ˆ
�K Ø)>×)DÑ)DÑ&ˆ
�O QØš1˜a˜4Ñ  >²!°Q°$Ñ#7Ñ7×<Ñ<Ó>À/ÒQÜØmóð ð —‘Ð 5Ó6ˆØÐ%à×%Ñ% ~°iÑ'@Ð&@Ä%ÈÃ(ÓKˆEØ—
‘
˜: ¸¿¹ÀdÇlÁlÐVZ×VbÑVbÑFbÓcˆØ×0Ñ0°Ó?×DÑDØ˜ T§\¡\°4·=±=À$Ç-Á-ÐQRó
Ðð !×2Ñ2°=ÓA×FÑFØ˜ T§\¡\°4·=±=À4Ç=Á=Ñ3Pó
Ðô ŸI™IÐ&7¸Ó<×AÑAØ˜ T§\¡\°4·=±=À$Ç-Á-ó
Ðð +×0Ñ0°Ñ4ˆØ˜aÒÜ %§¡¨^¸FÑ-CÀ^ÐTZÑE[Ð,\Ð^`Ó aÐà ¢¢A tªQ°²aÐ!7Ñ8Ø"Ð%6°t¸TÀ4ÊÈDÒRSÐ7SÑ%TÑTñUñ ð  Ò!à ¢¢A tªQ°°b°q°bÐ!8Ñ9Ø" T§]¡]Ñ2Ð5EÂaÊÈDÒRSÐUYÐ[\Ñ[]ÐF]Ñ5^Ñ^ÐadÑdñeñ ô
 ÐTÐUe×UkÑUkÐlnÑUoÐTpÐqÓrÐrà×&Ò&ä5°e¸^ÐM_ÐarÓs‰Fðxä>×DÑDØØ"Ø%Ø&Ø%Ø×$Ñ$ó�ð ×!Ñ! &Ó)ˆàÐ(Ð(Ð(øô ò xä9¸%ÀÐQcÐevÓw’ðxús   É)$J" Ê"J<Ê;J<)NNNNNNNF)rS   rT   rU   re   r"   Úintr˜   rV  rf   r
   r   rk  rà   rI   r±   r²   s   @r9   rF  rF  5  s¨   ø„ ñð%!˜zð %!°cð %!ÀSõ %!òN;ð*W U§\¡\ð WÈÐQWÑHXó Wð 26Ø"Ø#Ø6:ØØØØ"'ñH)à—|‘|ðH)ð ! §¡Ñ.ðH)ð & e§l¡lÑ3ðH)ð  ÷H)rJ   rF  c                   óR  ‡ — e Zd ZdZ	 	 ddedededefˆ fd„Zdej                  ded	efd
„Z
dej                  dee	   fd„Z	 	 	 ddej                  deej                     deej                     dedeej                  eej                     eeej                        f   f
d„Zˆ xZS )ÚDetaMultiheadAttentionz³
    Multi-headed attention from 'Attention Is All You Need' paper.

    Here, we add position embeddings to the queries and keys (as explained in the Deformable DETR paper).
    Ú	embed_dimr8  Údropoutr”   c                 óà  •— t         ‰| �  «        || _        || _        || _        ||z  | _        | j
                  |z  | j                  k7  rt        d| j                  › d|› d�«      ‚| j
                  dz  | _        t        j                  |||¬«      | _
        t        j                  |||¬«      | _        t        j                  |||¬«      | _        t        j                  |||¬«      | _        y )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      à¿)r”   )r—   r˜   r  r8  r€  Úhead_dimrð   Úscalingr   rQ  Úk_projÚv_projÚq_projÚout_proj)rœ   r  r8  r€  r”   rž   s        €r9   r˜   zDetaMultiheadAttention.__init__Ë  sÓ   ø€ ô 	‰ÑÔØ"ˆŒØ"ˆŒØˆŒØ! YÑ.ˆŒØ�=‰=˜9Ñ$¨¯©Ò6ÜØMÈdÏnÉnÐM]ð ^Ø�;˜bð"óð ð —}‘} dÑ*ˆŒä—i‘i 	¨9¸4Ô@ˆŒÜ—i‘i 	¨9¸4Ô@ˆŒÜ—i‘i 	¨9¸4Ô@ˆŒÜŸ	™	 )¨Y¸TÔBˆ�rJ   rh  Úseq_lenr6  c                 óŽ   — |j                  ||| j                  | j                  «      j                  dd«      j	                  «       S )Nr!   rì   )r4  r8  r‚  r1  r5  )rœ   rh  rˆ  r6  s       r9   Ú_shapezDetaMultiheadAttention._shapeã  s7   € Ø�{‰{˜: w°·±ÀÇÁÓN×XÑXÐYZÐ\]Ó^×iÑiÓkÐkrJ   rè   c                 ó   — |€|S ||z   S r>   rW   rj  s      r9   rk  z%DetaMultiheadAttention.with_pos_embedæ  rl  rJ   rb   rm  rn  r(  c                 óö  — |j                  «       \  }}}|�|}| j                  ||«      }| j                  |«      | j                  z  }	| j	                  | j                  |«      d|«      }
| j	                  | j                  «      d|«      }|| j                  z  d| j                  f} | j	                  |	||«      j                  |Ž }	 |
j                  |Ž }
 |j                  |Ž }|
j                  d«      }t        j                  |	|
j                  dd«      «      }|j                  «       || j                  z  ||fk7  r/t        d|| j                  z  ||f› d|j                  «       › �«      ‚|�t        ||j                  «      }|�{|j                  «       |d||fk7  r#t        d|d||f› d|j                  «       › �«      ‚|j                  || j                  ||«      |z   }|j                  || j                  z  ||«      }t         j"                  j%                  |d¬«      }|r?|j                  || j                  ||«      }|j                  || j                  z  ||«      }nd}t         j"                  j'                  || j&                  | j(                  ¬	«      }t        j                  ||«      }|j                  «       || j                  z  || j                  fk7  r7t        d
|| j                  || j                  f› d|j                  «       › �«      ‚|j                  || j                  || j                  «      }|j                  dd«      }|j+                  |||«      }| j-                  |«      }||fS )z#Input shape: Batch x Time x ChannelNr«   r!   rì   z$Attention weights should be of size z	, but is z!Attention mask should be of size rú   ©ÚpÚtrainingz `attn_output` should be of size )rÙ   rk  r†  rƒ  rŠ  r„  r…  r8  r‚  r4  rf   Úbmmr1  rð   r   rá   r   rÛ   rs  r€  r�  r­   r‡  )rœ   rb   rm  rè   rn  r6  Ú
target_lenr  Úhidden_states_originalÚquery_statesÚ
key_statesÚvalue_statesÚ
proj_shapeÚ
source_lenÚattn_weightsÚattn_weights_reshapedÚ
attn_probsÚattn_outputs                     r9   rI   zDetaMultiheadAttention.forwardé  s‚  € ð -:×,>Ñ,>Ó,@Ñ)ˆ
�J 	àÐ*Ø%2Ð"Ø ×/Ñ/°Ð?RÓSˆMð —{‘{ =Ó1°D·L±LÑ@ˆØ—[‘[ §¡¨]Ó!;¸RÀÓLˆ
Ø—{‘{ 4§;¡;Ð/EÓ#FÈÈJÓWˆà  4§>¡>Ñ1°2°t·}±}ÐEˆ
ØM�t—{‘{ <°¸ZÓH×MÑMÈzÐZˆØ$�Z—_‘_ jÐ1ˆ
Ø(�|×(Ñ(¨*Ð5ˆà—_‘_ QÓ'ˆ
ä—y‘y ¨z×/CÑ/CÀAÀqÓ/IÓJˆà×ÑÓ :°·±Ñ#>À
ÈJÐ"WÒWÜØ6¸
ÀTÇ^Á^Ñ8SÐU_ÐakÐ7lÐ6mð nØ ×%Ñ%Ó'Ð(ð*óð ð Ð%ä7¸È×H[ÑH[Ó\ˆNàÐ%Ø×"Ñ"Ó$¨°Q¸
ÀJÐ(OÒOÜ Ø7¸ÀQÈ
ÐT^Ð8_Ð7`ð aØ&×+Ñ+Ó-Ð.ð0óð ð (×,Ñ,¨Z¸¿¹ÈÐU_Ó`ÐcqÑqˆLØ'×,Ñ,¨Z¸$¿.¹.Ñ-HÈ*ÐV`ÓaˆLä—}‘}×,Ñ,¨\¸rÐ,ÓBˆáð
 %1×$5Ñ$5°jÀ$Ç.Á.ÐR\Ð^hÓ$iÐ!Ø0×5Ñ5°jÀ4Ç>Á>Ñ6QÐS]Ð_iÓj‰Là$(Ð!ä—]‘]×*Ñ*¨<¸4¿<¹<ÐRV×R_ÑR_Ð*Ó`ˆ
ä—i‘i 
¨LÓ9ˆà×ÑÓ *¨t¯~©~Ñ"=¸zÈ4Ï=É=Ð!YÒYÜØ2°JÀÇÁÐPZÐ\`×\iÑ\iÐ3jÐ2kð lØ×$Ñ$Ó&Ð'ð)óð ð
 "×&Ñ& z°4·>±>À:ÈtÏ}É}Ó]ˆØ!×+Ñ+¨A¨qÓ1ˆØ!×)Ñ)¨*°jÀ)ÓLˆà—m‘m KÓ0ˆàÐ1Ð1Ð1rJ   )r[  T)NNF)rS   rT   rU   re   r|  rÝ   rà   r˜   rf   r
   rŠ  r   rk  r   rI   r±   r²   s   @r9   r~  r~  Ä  s  ø„ ñð ØñCàðCð ðCð ð	Cð
 õCð0l˜UŸ\™\ð l°Cð lÀSó lðW U§\¡\ð WÈÐQWÑHXó Wð 26Ø6:Ø"'ñM2à—|‘|ðM2ð ! §¡Ñ.ðM2ð & e§l¡lÑ3ð	M2ð
  ðM2ð 
ˆu�|‰|˜X e§l¡lÑ3°X¸eÀEÇLÁLÑ>QÑ5RÐRÑ	S÷M2rJ   r~  c            	       óŠ   ‡ — e Zd Zdefˆ fd„Z	 	 	 	 	 ddej                  dej                  deej                     defd„Z	ˆ xZ
S )	ÚDetaEncoderLayerrÑ   c                 óR  •— t         ‰| �  «        |j                  | _        t	        ||j
                  |j                  ¬«      | _        t        j                  | j                  «      | _
        |j                  | _        t        |j                     | _        |j                  | _        t        j                   | j                  |j"                  «      | _        t        j                   |j"                  | j                  «      | _        t        j                  | j                  «      | _        y )N©r8  rG  )r—   r˜   r%  r  rF  Úencoder_attention_headsÚencoder_n_pointsÚ	self_attnr   Ú	LayerNormÚself_attn_layer_normr€  r   Úactivation_functionÚactivation_fnÚactivation_dropoutrQ  Úencoder_ffn_dimÚfc1Úfc2Úfinal_layer_norm©rœ   rÑ   rž   s     €r9   r˜   zDetaEncoderLayer.__init__:  sÊ   ø€ Ü‰ÑÔØŸ™ˆŒÜ:ØØ×4Ñ4Ø×,Ñ,ô
ˆŒô
 %'§L¡L°·±Ó$@ˆÔ!Ø—~‘~ˆŒÜ# F×$>Ñ$>Ñ?ˆÔØ"(×";Ñ";ˆÔÜ—9‘9˜TŸ^™^¨V×-CÑ-CÓDˆŒÜ—9‘9˜V×3Ñ3°T·^±^ÓDˆŒÜ "§¡¨T¯^©^Ó <ˆÕrJ   rb   rm  rè   rn  c                 óŠ  — |}| j                  |||||||||¬«	      \  }}	t        j                  j                  || j                  | j                  ¬«      }||z   }| j                  |«      }|}| j                  | j                  |«      «      }t        j                  j                  || j                  | j                  ¬«      }| j                  |«      }t        j                  j                  || j                  | j                  ¬«      }||z   }| j                  |«      }| j                  r‹t        j                  |«      j                  «       s#t        j                  |«      j                  «       rEt        j                  |j                   «      j"                  dz
  }
t        j$                  ||
 |
¬«      }|f}|r||	fz  }|S )aº  
        Args:
            hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
                Input to the layer.
            attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
                Attention mask.
            position_embeddings (`torch.FloatTensor`, *optional*):
                Position embeddings, to be added to `hidden_states`.
            reference_points (`torch.FloatTensor`, *optional*):
                Reference points.
            spatial_shapes (`torch.LongTensor`, *optional*):
                Spatial shapes of the backbone feature maps.
            level_start_index (`torch.LongTensor`, *optional*):
                Level start index.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
        ©	rb   rm  ro   ru  rè   rv  rw  rx  rn  r�  éè  r…   )r¢  r   rÛ   r€  r�  r¤  r¦  r©  r§  rª  r«  rf   ÚisinfÚanyÚisnanÚfinforá   r‡   r‰   )rœ   rb   rm  rè   rv  rw  rx  rn  Úresidualr˜  Úclamp_valueÚoutputss               r9   rI   zDetaEncoderLayer.forwardJ  s”  € ð8 !ˆð '+§n¡nØ'Ø)Ø"/Ø#1Ø 3Ø-Ø)Ø/Ø/ð '5ó 
'
Ñ#ˆ�|ô Ÿ™×-Ñ-¨m¸t¿|¹|ÐVZ×VcÑVcÐ-ÓdˆØ  =Ñ0ˆØ×1Ñ1°-Ó@ˆà ˆØ×*Ñ*¨4¯8©8°MÓ+BÓCˆÜŸ™×-Ñ-¨m¸t×?VÑ?VÐae×anÑanÐ-ÓoˆàŸ™ Ó/ˆÜŸ™×-Ñ-¨m¸t¿|¹|ÐVZ×VcÑVcÐ-Ódˆà  =Ñ0ˆØ×-Ñ-¨mÓ<ˆà�=Š=Ü�{‰{˜=Ó)×-Ñ-Ô/´5·;±;¸}Ó3M×3QÑ3QÔ3SÜ#Ÿk™k¨-×*=Ñ*=Ó>×BÑBÀTÑI�Ü %§¡¨MÀ¸|ÐQ\Ô ]�à Ð"ˆáØ˜�Ñ&ˆGàˆrJ   )NNNNF©rS   rT   rU   r"   r˜   rf   r
   r   rà   rI   r±   r²   s   @r9   r�  r�  9  sa   ø„ ð=˜zõ =ð( 7;ØØØØ"'ñCà—|‘|ðCð Ÿ™ðCð & e§l¡lÑ3ð	Cð  ÷CrJ   r�  c                   ó¸   ‡ — e Zd Zdefˆ fd„Z	 	 	 	 	 	 	 d	dej                  deej                     deej                     deej                     dee   f
d„Z	ˆ xZ
S )
ÚDetaDecoderLayerrÑ   c                 óü  •— t         ‰| �  «        |j                  | _        t	        | j                  |j
                  |j                  ¬«      | _        |j                  | _        t        |j                     | _        |j                  | _        t        j                  | j                  «      | _        t!        ||j
                  |j"                  ¬«      | _        t        j                  | j                  «      | _        t        j(                  | j                  |j*                  «      | _        t        j(                  |j*                  | j                  «      | _        t        j                  | j                  «      | _        y )N)r  r8  r€  rŸ  )r—   r˜   r%  r  r~  Údecoder_attention_headsÚattention_dropoutr¢  r€  r   r¥  r¦  r§  r   r£  r¤  rF  Údecoder_n_pointsÚencoder_attnÚencoder_attn_layer_normrQ  Údecoder_ffn_dimr©  rª  r«  r¬  s     €r9   r˜   zDetaDecoderLayer.__init__‘  s	  ø€ Ü‰ÑÔØŸ™ˆŒô 0Ø—n‘nØ×4Ñ4Ø×,Ñ,ô
ˆŒð
 —~‘~ˆŒÜ# F×$>Ñ$>Ñ?ˆÔØ"(×";Ñ";ˆÔä$&§L¡L°·±Ó$@ˆÔ!ä=ØØ×4Ñ4Ø×,Ñ,ô
ˆÔô
 (*§|¡|°D·N±NÓ'CˆÔ$ä—9‘9˜TŸ^™^¨V×-CÑ-CÓDˆŒÜ—9‘9˜V×3Ñ3°T·^±^ÓDˆŒÜ "§¡¨T¯^©^Ó <ˆÕrJ   rb   rè   ro   ru  rn  c	                 ó,  — |}	| j                  |||¬«      \  }}
t        j                  j                  || j                  | j                  ¬«      }|	|z   }| j                  |«      }|}d}| j                  |||||||||¬«	      \  }}t        j                  j                  || j                  | j                  ¬«      }||z   }| j                  |«      }|}	| j                  | j                  |«      «      }t        j                  j                  || j                  | j                  ¬«      }| j                  |«      }t        j                  j                  || j                  | j                  ¬«      }|	|z   }| j                  |«      }|f}|r||
|fz  }|S )a«  
        Args:
            hidden_states (`torch.FloatTensor`):
                Input to the layer of shape `(batch, seq_len, embed_dim)`.
            position_embeddings (`torch.FloatTensor`, *optional*):
                Position embeddings that are added to the queries and keys in the self-attention layer.
            reference_points (`torch.FloatTensor`, *optional*):
                Reference points.
            spatial_shapes (`torch.LongTensor`, *optional*):
                Spatial shapes.
            level_start_index (`torch.LongTensor`, *optional*):
                Level start index.
            encoder_hidden_states (`torch.FloatTensor`):
                cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
            encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
                `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
                values.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
        )rb   rè   rn  r�  Nr®  )r¢  r   rÛ   r€  r�  r¤  r¾  r¿  r¦  r©  r§  rª  r«  )rœ   rb   rè   rv  rw  rx  ro   ru  rn  r´  Úself_attn_weightsÚsecond_residualÚcross_attn_weightsr¶  s                 r9   rI   zDetaDecoderLayer.forward¬  s¬  € ð@ !ˆð ,0¯>©>Ø'Ø 3Ø/ð ,:ó ,
Ñ(ˆÐ(ô Ÿ™×-Ñ-¨m¸t¿|¹|ÐVZ×VcÑVcÐ-ÓdˆØ  =Ñ0ˆØ×1Ñ1°-Ó@ˆà'ˆð "ÐØ,0×,=Ñ,=Ø'Ø1Ø"7Ø#9Ø 3Ø-Ø)Ø/Ø/ð ->ó 
-
Ñ)ˆÐ)ô Ÿ™×-Ñ-¨m¸t¿|¹|ÐVZ×VcÑVcÐ-ÓdˆØ'¨-Ñ7ˆà×4Ñ4°]ÓCˆð !ˆØ×*Ñ*¨4¯8©8°MÓ+BÓCˆÜŸ™×-Ñ-¨m¸t×?VÑ?VÐae×anÑanÐ-ÓoˆØŸ™ Ó/ˆÜŸ™×-Ñ-¨m¸t¿|¹|ÐVZ×VcÑVcÐ-ÓdˆØ  =Ñ0ˆØ×-Ñ-¨mÓ<ˆà Ð"ˆáØÐ)Ð+=Ð>Ñ>ˆGàˆrJ   )NNNNNNFr·  r²   s   @r9   r¹  r¹  �  s„   ø„ ð=˜zõ =ð< 7;ØØØØ8<Ø9=Ø,1ñPà—|‘|ðPð & e§l¡lÑ3ðPð  (¨¯©Ñ5ðPð !)¨¯©Ñ 6ðPð $ D™>÷PrJ   r¹  c                   ó*   — e Zd ZeZdZdZg d¢ZdZd„ Z	y)ÚDetaPreTrainedModelrÁ   rÔ   )rÅ   r�  r¹  Tc                 ó,  — | j                   j                  }t        |t        «      rht        j
                  j                  |j                  j                  «       t        j
                  j                  |j                  j                  «       �n1t        |t        «      r|j                  «        �nt        |t        j                  t        j                  t        j                  f«      rX|j                  j                  j!                  d|¬«       |j"                  �£|j"                  j                  j%                  «        n~t        |t        j&                  «      rd|j                  j                  j!                  d|¬«       |j(                  �1|j                  j                  |j(                     j%                  «        t+        |d«      r“| j                   j,                  s}t        j
                  j/                  |j0                  j                  j                  d¬«       t        j
                  j3                  |j0                  j"                  j                  d«       t+        |d«      r*t        j
                  j!                  |j4                  «       y y )Nr[  )ÚmeanÚstdrv  g      ð?)ÚgainÚlevel_embed)rÑ   Úinit_stdr¶   r  r   r_  Úuniform_r  r“   r  rF  rV  rQ  ÚConv2dr·   rº   Únormal_r”   Úzero_r  Úpadding_idxÚhasattrÚ	two_stagerd  rv  r`  rË  )rœ   r€   rÉ  s      r9   Ú_init_weightsz!DetaPreTrainedModel._init_weights  s®  € Ø�k‰k×"Ñ"ˆä�fÔ:Ô;Ü�G‰G×Ñ˜V×2Ñ2×9Ñ9Ô:Ü�G‰G×Ñ˜V×5Ñ5×<Ñ<Ö=Ü˜Ô AÔBØ×$Ñ$Ö&Ü˜¤§¡¬B¯I©I´r·~±~Ð FÔGð �M‰M×Ñ×&Ñ&¨C°SÐ&Ô9Ø�{‰{Ð&Ø—‘× Ñ ×&Ñ&Õ(Ü˜¤§¡Ô-Ø�M‰M×Ñ×&Ñ&¨C°SÐ&Ô9Ø×!Ñ!Ð-Ø—‘×"Ñ" 6×#5Ñ#5Ñ6×<Ñ<Ô>Ü�6Ð-Ô.°t·{±{×7LÒ7LÜ�G‰G×#Ñ# F×$;Ñ$;×$BÑ$B×$GÑ$GÈcÐ#ÔRÜ�G‰G×Ñ˜f×5Ñ5×:Ñ:×?Ñ?ÀÔEÜ�6˜=Ô)Ü�G‰G�O‰O˜F×.Ñ.Õ/ð *rJ   N)
rS   rT   rU   r"   Úconfig_classÚbase_model_prefixÚmain_input_nameÚ_no_split_modulesÚsupports_gradient_checkpointingrÔ  rW   rJ   r9   rÆ  rÆ  ÿ  s#   „ Ø€LØÐØ$€OÚjÐØ&*Ð#ó0rJ   rÆ  aI  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`DetaConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
ae	  
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Padding will be ignored by default should you provide it.

            Pixel values can be obtained using [`AutoImageProcessor`]. See [`AutoImageProcessor.__call__`] for details.

        pixel_mask (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
            Mask to avoid performing attention on padding pixel values. Mask values selected in `[0, 1]`:

            - 1 for pixels that are real (i.e. **not masked**),
            - 0 for pixels that are padding (i.e. **masked**).

            [What are attention masks?](../glossary#attention-mask)

        decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
            Not used by default. Can be used to mask object queries.
        encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
            Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
            `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
            hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
            can choose to directly pass a flattened representation of an image.
        decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
            Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
            embedded representation.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
c                   óR   ‡ — e Zd ZdZdefˆ fd„Zed„ «       Z	 	 	 	 	 	 	 	 	 dd„Zˆ xZ	S )ÚDetaEncodera  
    Transformer encoder consisting of *config.encoder_layers* deformable attention layers. Each layer is a
    [`DetaEncoderLayer`].

    The encoder updates the flattened multi-scale feature maps through multiple deformable attention layers.

    Args:
        config: DetaConfig
    rÑ   c                 ó  •— t         ‰| �  |«       |j                  | _        t        j                  t        |j                  «      D �cg c]  }t        |«      ‘Œ c}«      | _        d| _	        | j                  «        y c c}w ©NF)r—   r˜   r€  r   r|   r}   Úencoder_layersr�  ÚlayersÚgradient_checkpointingÚ	post_init©rœ   rÑ   r7  rž   s      €r9   r˜   zDetaEncoder.__init__`  sa   ø€ Ü‰Ñ˜Ô à—~‘~ˆŒÜ—m‘mÄuÈV×MbÑMbÓGcÖ$dÀ!Ô%5°fÕ%=Ò$dÓeˆŒØ&+ˆÔ#ð 	�‰Õùò	 %es   ÁA>c                 ó2  — g }t        | «      D ]Ú  \  }\  }}t        t        j                  d|dz
  |t        j                  |¬«      t        j                  d|dz
  |t        j                  |¬«      d¬«      \  }}|j                  d«      d   |dd…d|df   |z  z  }|j                  d«      d   |dd…d|df   |z  z  }t        j                  ||fd«      }	|j                  |	«       ŒÜ t        j                  |d«      }
|
dd…dd…df   |dd…df   z  }
|
S )	a>  
        Get reference points for each feature map. Used in decoder.

        Args:
            spatial_shapes (`torch.LongTensor` of shape `(num_feature_levels, 2)`):
                Spatial shapes of each feature map.
            valid_ratios (`torch.FloatTensor` of shape `(batch_size, num_feature_levels, 2)`):
                Valid ratios of each feature map.
            device (`torch.device`):
                Device on which to create the tensors.
        Returns:
            `torch.FloatTensor` of shape `(batch_size, num_queries, num_feature_levels, 2)`
        rõ   rö   Úij©Úindexingr«   Nr!   r   )	r0  r   rf   Úlinspacerþ   r­   r  râ   r  )rw  Úvalid_ratiosr¹   Úreference_points_listÚlevelr  r  Úref_yÚref_xÚrefrv  s              r9   Úget_reference_pointsz DetaEncoder.get_reference_pointsj  s'  € ð !#ÐÜ&/°Ó&?ò 
	.Ñ"ˆE‘?�F˜EÜ#Ü—‘˜s F¨S¡L°&ÄÇÁÐV\Ô]Ü—‘˜s E¨C¡K°¼e¿m¹mÐTZÔ[Øô‰LˆE�5ð —M‘M "Ó% dÑ+¨|ºA¸tÀUÈAÐ<MÑ/NÐQWÑ/WÑXˆEØ—M‘M "Ó% dÑ+¨|ºA¸tÀUÈAÐ<MÑ/NÐQVÑ/VÑWˆEÜ—+‘+˜u e˜n¨bÓ1ˆCØ!×(Ñ(¨Õ-ð
	.ô !Ÿ9™9Ð%:¸AÓ>ÐØ+ªAªq°$¨JÑ7¸,ÂqÈ$ÀwÑ:OÑOÐØÐrJ   c
           
      óF  — |�|n| j                   j                  }|�|n| j                   j                  }|	�|	n| j                   j                  }	|}
t        j
                  j                  |
| j                  | j                  ¬«      }
| j                  |||j                  ¬«      }|rdnd}|rdnd}t        | j                  «      D ]-  \  }}|r||
fz   } ||
||||||¬«      }|d   }
|sŒ%||d   fz   }Œ/ |r||
fz   }|	st        d„ |
||fD «       «      S t        |
||¬	«      S )
aR  
        Args:
            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
                Flattened feature map (output of the backbone + projection layer) that is passed to the encoder.
            attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on padding pixel features. Mask values selected in `[0, 1]`:
                - 1 for pixel features that are real (i.e. **not masked**),
                - 0 for pixel features that are padding (i.e. **masked**).
                [What are attention masks?](../glossary#attention-mask)
            position_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
                Position embeddings that are added to the queries and keys in each self-attention layer.
            spatial_shapes (`torch.LongTensor` of shape `(num_feature_levels, 2)`):
                Spatial shapes of each feature map.
            level_start_index (`torch.LongTensor` of shape `(num_feature_levels)`):
                Starting index of each feature map.
            valid_ratios (`torch.FloatTensor` of shape `(batch_size, num_feature_levels, 2)`):
                Ratio of valid area in each feature level.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
        Nr�  r  rW   )rè   rv  rw  rx  rn  r   r!   c              3   ó&   K  — | ]	  }|€Œ|–— Œ y ­wr>   rW   ©Ú.0Úvs     r9   ú	<genexpr>z&DetaEncoder.forward.<locals>.<genexpr>Ò  s   è ø€ Òe˜qÐWXÑWdœÑeùó   ‚Š©r_   rb   rc   )rÑ   rn  Úoutput_hidden_statesÚuse_return_dictr   rÛ   r€  r�  rî  r¹   r0  rß  Útupler   )rœ   Úinputs_embedsrm  rè   rw  rx  rè  rn  r÷  Úreturn_dictrb   rv  Úencoder_statesÚall_attentionsr‚   Úencoder_layerÚlayer_outputss                    r9   rI   zDetaEncoder.forward‰  s`  € ðL 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆà%ˆÜŸ™×-Ñ-¨m¸t¿|¹|ÐVZ×VcÑVcÐ-Ódˆà×4Ñ4°^À\ÐZg×ZnÑZnÐ4ÓoÐá3™¸ˆÙ0™°dˆÜ )¨$¯+©+Ó 6ò 	FÑˆAˆ}Ù#Ø!/°=Ð2BÑ!B�Ù)ØØØ$7Ø!1Ø-Ø"3Ø"3ôˆMð *¨!Ñ,ˆMâ Ø!/°=ÀÑ3CÐ2EÑ!E‘ð!	Fñ$  Ø+¨}Ð.>Ñ>ˆNáÜÑe ]°NÀNÐ$SÔeÓeÐeÜØ+¸>ÐVdô
ð 	
rJ   ©	NNNNNNNNN)
rS   rT   rU   re   r"   r˜   rV   rî  rI   r±   r²   s   @r9   rÛ  rÛ  U  sL   ø„ ñð˜zõ ð ñ ó ð ð@ ØØ ØØØØØ!Ø÷L
rJ   rÛ  c                   óF   ‡ — e Zd ZdZdefˆ fd„Z	 	 	 	 	 	 	 	 	 	 	 dd„Zˆ xZS )ÚDetaDecodera  
    Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`DetaDecoderLayer`].

    The decoder updates the query embeddings through multiple self-attention and cross-attention layers.

    Some tweaks for Deformable DETR:

    - `position_embeddings`, `reference_points`, `spatial_shapes` and `valid_ratios` are added to the forward pass.
    - it also returns a stack of intermediate outputs and reference points from all decoding layers.

    Args:
        config: DetaConfig
    rÑ   c                 ó"  •— t         ‰| �  |«       |j                  | _        t        j                  t        |j                  «      D �cg c]  }t        |«      ‘Œ c}«      | _        d| _	        d | _
        d | _        | j                  «        y c c}w rÝ  )r—   r˜   r€  r   r|   r}   Údecoder_layersr¹  rß  rà  Ú
bbox_embedÚclass_embedrá  râ  s      €r9   r˜   zDetaDecoder.__init__ç  sr   ø€ Ü‰Ñ˜Ô à—~‘~ˆŒÜ—m‘mÄuÈV×MbÑMbÓGcÖ$dÀ!Ô%5°fÕ%=Ò$dÓeˆŒØ&+ˆÔ#ð ˆŒØˆÔð 	�‰Õùò %es   ÁBc                 ó2  — |	�|	n| j                   j                  }	|
�|
n| j                   j                  }
|�|n| j                   j                  }|�|}|
rdnd}|	rdnd}|	r|�dnd}d}d}t	        | j
                  «      D �]´  \  }}|j                  d   dk(  r-|dd…dd…df   t        j                  ||gd«      dd…df   z  }n3|j                  d   dk7  rt        d«      ‚|dd…dd…df   |dd…df   z  }|
r|fz  }| j                  r0| j                  r$| j                  |j                  |||||||	«	      }n ||||||||	¬«      }|d   }| j                  �± | j                  |   |«      }|j                  d   dk(  r|t        |«      z   }|j!                  «       }n[|j                  d   dk7  rt        d	|j                  d   › �«      ‚|}|d
dd…f   t        |«      z   |d
dd…f<   |j!                  «       }|j#                  «       }||fz  }||fz  }|	s�ŒŸ||d   fz  }|€�Œ¬||d   fz  }�Œ· t        j$                  |d¬«      }t        j$                  |d¬«      }|
r|fz  }|st'        d„ |||||fD «       «      S t)        |||||¬«      S )aj	  
        Args:
            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
                The query embeddings that are passed into the decoder.
            encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
                Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
                of the decoder.
            encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing cross-attention on padding pixel_values of the encoder. Mask values selected
                in `[0, 1]`:
                - 1 for pixels that are real (i.e. **not masked**),
                - 0 for pixels that are padding (i.e. **masked**).
            position_embeddings (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
                Position embeddings that are added to the queries and keys in each self-attention layer.
            reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)` is `as_two_stage` else `(batch_size, num_queries, 2)` or , *optional*):
                Reference point in range `[0, 1]`, top-left (0,0), bottom-right (1, 1), including padding area.
            spatial_shapes (`torch.FloatTensor` of shape `(num_feature_levels, 2)`):
                Spatial shapes of the feature maps.
            level_start_index (`torch.LongTensor` of shape `(num_feature_levels)`, *optional*):
                Indexes for the start of each feature level. In range `[0, sequence_length]`.
            valid_ratios (`torch.FloatTensor` of shape `(batch_size, num_feature_levels, 2)`, *optional*):
                Ratio of valid area in each feature level.

            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
        NrW   r«   r   rì   z2Reference points' last dimension must be of size 2)rè   ro   rv  rw  rx  ru  rn  r   z;Reference points' last dimension must be of size 2, but is .r!   rú   c              3   ó$   K  — | ]  }|�|–— Œ
 y ­wr>   rW   rñ  s     r9   rô  z&DetaDecoder.forward.<locals>.<genexpr>|  s   è ø€ ò àð �=ô ñùó   ‚)r_   r`   ra   rb   rc   rd   )rÑ   rn  r÷  rø  r0  rß  rÞ   rf   r  rð   rà  r�  Ú_gradient_checkpointing_funcÚ__call__r  r�   ÚsigmoidÚdetachr  rù  r^   )rœ   rú  ro   ru  rè   rv  rw  rx  rè  rn  r÷  rû  rb   Úall_hidden_statesÚall_self_attnsÚall_cross_attentionsÚintermediatera   ÚidxÚdecoder_layerÚreference_points_inputrÿ  ÚtmpÚnew_reference_pointss                           r9   rI   zDetaDecoder.forwardõ  sn  € ð\ 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆàÐ$Ø)ˆMñ #7™B¸DÐÙ0™°dˆÙ&7Ð<QÐ<]™rÐdhÐØˆØ(*Ð%ä"+¨D¯K©KÓ"8ó >	@ÑˆC�Ø×%Ñ% bÑ)¨QÒ.à$¢Qª¨4 ZÑ0´5·9±9¸lÈLÐ=YÐ[]Ó3^Ò_`ÐbfÐ_fÑ3gÑgñ 'ð $×)Ñ)¨"Ñ-°Ò2Ü$Ð%YÓZÐZØ)9º!ºQÀ¸*Ñ)EÈÒUVÐX\ÐU\ÑH]Ñ)]Ð&á#Ø! mÐ%5Ñ5Ð!à×*Ò*¨t¯}ª}Ø $× AÑ AØ!×*Ñ*Ø!Ø'Ø*Ø"Ø%Ø)Ø*Ø%ó
!‘ñ !.Ø!Ø(;Ø*?Ø%;Ø#1Ø&7Ø+AØ&7ô	!�ð *¨!Ñ,ˆMð �‰Ð*Ø*�d—o‘o cÑ*¨=Ó9�Ø#×)Ñ)¨"Ñ-°Ò2Ø+.´ÐAQÓ1RÑ+RÐ(Ø+?×+GÑ+GÓ+IÑ(à'×-Ñ-¨bÑ1°QÒ6Ü(ØYÐZj×ZpÑZpÐqsÑZtÐYuÐvóð ð ,/Ð(Ø47¸¸R¸a¸R¸±LÄ?ÐScÓCdÑ4dÐ(¨¨b¨q¨b¨Ñ1Ø+?×+GÑ+GÓ+IÐ(Ø#7×#>Ñ#>Ó#@Ð à˜]Ð,Ñ,ˆLØ)Ð.>Ð-@Ñ@Ð)ã Ø =°Ñ#3Ð"5Ñ5�à(Ò4Ø(¨]¸1Ñ-=Ð,?Ñ?Ò(ð}>	@ôB —{‘{ <°QÔ7ˆÜ(-¯©Ð4QÐWXÔ(YÐ%ñ  Ø -Ð!1Ñ1ÐáÜñ ð "Ø Ø1Ø%Ø"Ø(ðôó ð ô !Ø+Ø'3Ø*GØ+Ø%Ø1ô
ð 	
rJ   )NNNNNNNNNNN)rS   rT   rU   re   r"   r˜   rI   r±   r²   s   @r9   r  r  Ø  s=   ø„ ñð˜zõ ð  Ø"Ø#Ø ØØØØØØ!Ø÷Z
rJ   r  z›
    The bare DETA Model (consisting of a backbone and encoder-decoder Transformer) outputting raw hidden-states without
    any specific head on top.
    c                   ó¤  ‡ — e Zd Zdefˆ fd„Zd„ Zd„ Zd„ Zd„ Ze	j                  fd„Zd„ Zd	„ Z ee«       eee¬
«      	 	 	 	 	 	 	 	 dde	j&                  dee	j*                     dee	j&                     dee	j&                     dee	j&                     dee	j&                     dee   dee   dee   deee	j&                     ef   fd„«       «       Zˆ xZS )Ú	DetaModelrÑ   c                 ó  •— t         ‰| �  |«       |j                  rt        | dg«       t	        |«      | _        | j
                  j                  }|j                  dkD  �r.t        |«      }g }t        |«      D ]j  }||   }|j                  t        j                  t        j                  ||j                  d¬«      t        j                  d|j                  «      «      «       Œl t        |j                  |z
  «      D ]s  }|j                  t        j                  t        j                  |j                  ddd¬«      t        j                  d|j                  «      «      «       |j                  }Œu t        j                   |«      | _        npt        j                   t        j                  t        j                  |d   |j                  d¬«      t        j                  d|j                  «      «      g«      | _        |j                  s2t        j$                  |j&                  |j                  dz  «      | _        t+        |«      | _        t/        |«      | _        t        j2                  t5        j6                  |j                  |j                  «      «      | _        |j                  �rt        j:                  |j                  |j                  «      | _        t        j>                  |j                  «      | _         t        j:                  |j                  dz  |j                  dz  «      | _!        t        j>                  |j                  dz  «      | _"        t        j:                  |j                  |j                  «      | _#        t        j>                  |j                  «      | _$        n%t        j:                  |j                  d«      | _%        |jL                  | _&        |jN                  | _'        | jQ                  «        y )	NÚtorchvisionr!   )Úkernel_sizeé    rü   rì   )r  ÚstrideÚpaddingr«   ))r—   r˜   rÓ  r   rÅ   rÒ   rÊ   rN  r½   r}   râ   r   Ú
SequentialrÎ  r%  Ú	GroupNormr|   Ú
input_projr  r:  Úquery_position_embeddingsrÛ  Úencoderr  Údecoderrc  rf   r
   rË  rQ  Ú
enc_outputr£  Úenc_output_normÚ	pos_transÚpos_trans_normÚ	pix_transÚpix_trans_normrv  Úassign_first_stageÚtwo_stage_num_proposalsrá  )rœ   rÑ   rÊ   Únum_backbone_outsÚinput_proj_listr7  Úin_channelsrž   s          €r9   r˜   zDetaModel.__init__š  sç  ø€ Ü‰Ñ˜Ô à×ÒÜ˜d ] OÔ4ô <¸FÓCˆŒØ%)§]¡]×%MÑ%MÐ"ð ×$Ñ$ qÓ(Ü #Ð$>Ó ?ÐØ ˆOÜÐ,Ó-ò �Ø8¸Ñ;�Ø×&Ñ&Ü—M‘MÜŸ	™	 +¨v¯~©~È1ÔMÜŸ™ R¨¯©Ó8óõðô ˜6×4Ñ4Ð7HÑHÓIò -�Ø×&Ñ&Ü—M‘MÜŸ	™	 +¨v¯~©~È1ÐUVÐ`aÔbÜŸ™ R¨¯©Ó8óôð %Ÿn™n‘ð-ô !Ÿm™m¨OÓ<ˆD�Oä Ÿm™mä—M‘MÜŸ	™	Ð"<¸RÑ"@À&Ç.Á.Ð^_Ô`ÜŸ™ R¨¯©Ó8óðóˆDŒOð ×ÒÜ-/¯\©\¸&×:LÑ:LÈfÏnÉnÐ_`ÑN`Ó-aˆDÔ*ä" 6Ó*ˆŒÜ" 6Ó*ˆŒäŸ<™<¬¯©°V×5NÑ5NÐPV×P^ÑP^Ó(_Ó`ˆÔà×ÓÜ Ÿi™i¨¯©¸¿¹ÓGˆDŒOÜ#%§<¡<°·±Ó#?ˆDÔ ÜŸY™Y v§~¡~¸Ñ'9¸6¿>¹>ÈAÑ;MÓNˆDŒNÜ"$§,¡,¨v¯~©~ÀÑ/AÓ"BˆDÔÜŸY™Y v§~¡~°v·~±~ÓFˆDŒNÜ"$§,¡,¨v¯~©~Ó">ˆDÕä$&§I¡I¨f¯n©n¸aÓ$@ˆDÔ!à"(×";Ñ";ˆÔØ'-×'EÑ'EˆÔ$à�‰ÕrJ   c                 ó   — | j                   S r>   )r#  ©rœ   s    r9   Úget_encoderzDetaModel.get_encoderÚ  ó   € Ø�|‰|ÐrJ   c                 ó   — | j                   S r>   )r$  r1  s    r9   Úget_decoderzDetaModel.get_decoderÝ  r3  rJ   c                 ó~   — | j                   j                  j                  «       D ]  \  }}|j                  d«       Œ y rÝ  ©rÒ   rÁ   rÍ   rÎ   ©rœ   rÂ   Úparams      r9   Úfreeze_backbonezDetaModel.freeze_backboneà  s6   € ØŸ=™=×.Ñ.×?Ñ?ÓAò 	(‰KˆD�%Ø× Ñ  Õ'ñ	(rJ   c                 ó~   — | j                   j                  j                  «       D ]  \  }}|j                  d«       Œ y )NTr7  r8  s      r9   Úunfreeze_backbonezDetaModel.unfreeze_backboneä  s6   € ØŸ=™=×.Ñ.×?Ñ?ÓAò 	'‰KˆD�%Ø× Ñ  Õ&ñ	'rJ   c                 ó&  — |j                   \  }}}t        j                  |dd…dd…df   d«      }t        j                  |dd…ddd…f   d«      }|j                  |«      |z  }|j                  |«      |z  }	t        j                  |	|gd«      }
|
S )z(Get the valid ratio of all feature maps.Nr   r!   r«   )rÞ   rf   r3  rß   r  )rœ   rç   rá   r7  r  r  Úvalid_heightÚvalid_widthÚvalid_ratio_heightÚvalid_ratio_widthÚvalid_ratios              r9   Úget_valid_ratiozDetaModel.get_valid_ratioè  s�   € ð  Ÿ:™:Ñˆˆ6�5Ü—y‘y ¢aª¨A g¡°Ó2ˆÜ—i‘i ¢Q¨ª1 W¡¨qÓ1ˆØ)Ÿ_™_¨UÓ3°fÑ<ÐØ'ŸN™N¨5Ó1°EÑ9ÐÜ—k‘kÐ#4Ð6HÐ"IÈ2ÓNˆØÐrJ   c           
      ó2  — | j                   j                  dz  }d}dt        j                  z  }t	        j
                  |t        j                  |j                  ¬«      j                  «       }|dt	        j                  |dd¬«      z  |z  z  }|j                  «       |z  }|dd…dd…dd…df   |z  }t	        j                  |dd…dd…dd…ddd…f   j                  «       |dd…dd…dd…ddd…f   j                  «       fd	¬
«      j                  d«      }|S )z,Get the position embedding of the proposals.rì   r  rö   r÷   rø   Nr   r!   r   rú   )rÑ   r%  rñ   rò   rf   rÿ   r   r¹   rÝ   r  r  r  r  r  r  )rœ   Ú	proposalsÚnum_pos_featsrî   r°   r
  rå   s          r9   Úget_proposal_pos_embedz DetaModel.get_proposal_pos_embedó  sú   € ð Ÿ™×+Ñ+¨qÑ0ˆØˆØ”D—G‘G‘ˆä—‘˜]´%·+±+Ài×FVÑFVÔW×]Ñ]Ó_ˆØ ¤E§I¡I¨e°QÀgÔ$NÑ NÐQ^Ñ ^Ñ_ˆà×%Ñ%Ó'¨%Ñ/ˆ	àšš1ša ˜Ñ&¨Ñ.ˆä�k‰k˜3šq¢!¢Q¨¨¨1¨˜}Ñ-×1Ñ1Ó3°SººAºqÀ!À$ÀQÀ$¸Ñ5G×5KÑ5KÓ5MÐNÐTUÔV×^Ñ^Ð_`ÓaˆØˆ
rJ   c                 ó¼  — |j                   d   }g }d}g }t        |«      D �]$  \  }\  }	}
|dd…|||	|
z  z   …f   j                  ||	|
d«      }t        j                  |dd…dd…ddf    d«      }t        j                  |dd…ddd…df    d«      }t        t        j                  d|	dz
  |	t        j                  |j                  ¬«      t        j                  d|
dz
  |
t        j                  |j                  ¬«      d¬«      \  }}t        j                  |j                  d«      |j                  d«      gd«      }t        j                  |j                  d«      |j                  d«      gd«      j                  |ddd«      }|j                  d«      j                  |ddd«      d	z   |z  }t        j                  |«      d
z  d|z  z  }t        j                  ||fd«      j                  |dd«      }|j                  |«       ||	|
z  z  }|j                  |j                  |	|
z  t        j                  ¬«      |z  «       �Œ' t        j                  |d«      }|dkD  |dk  z  j!                  dd¬«      }t        j"                  |d|z
  z  «      }|j%                  |j                  d«      t'        d«      «      }|j%                  | t'        d«      «      }|}|j%                  |j                  d«      t'        d«      «      }|j%                  | t'        d«      «      }| j)                  | j+                  |«      «      }t        j                  |«      }|||fS )a7  Generate the encoder output proposals from encoded enc_output.

        Args:
            enc_output (Tensor[batch_size, sequence_length, hidden_size]): Output of the encoder.
            padding_mask (Tensor[batch_size, sequence_length]): Padding mask for `enc_output`.
            spatial_shapes (Tensor[num_feature_levels, 2]): Spatial shapes of the feature maps.

        Returns:
            `tuple(torch.FloatTensor)`: A tuple of feature map and bbox prediction.
                - object_query (Tensor[batch_size, sequence_length, hidden_size]): Object query features. Later used to
                  directly predict a bounding box. (without the need of a decoder)
                - output_proposals (Tensor[batch_size, sequence_length, 4]): Normalized proposals, after an inverse
                  sigmoid.
        r   Nr!   rö   rä  rå  r«   rì   rõ   gš™™™™™©?r\  r   rô   ç{®Gáz„?g®Gáz®ï?Tr]  Úinf)rÞ   r0  r4  rf   r3  r   rç  rþ   r¹   r  r  ÚexpandÚ	ones_likerâ   Únew_onesÚlongÚallrŠ   rq  rÝ   r&  r%  )rœ   r%  Úpadding_maskrw  r6  rE  Ú_curÚ	level_idsrê  r  r  Úmask_flatten_r>  r?  Úgrid_yÚgrid_xÚgridr°   Úwidth_heigthÚproposalrs   Úoutput_proposals_validÚobject_querys                          r9   Úgen_encoder_output_proposalsz&DetaModel.gen_encoder_output_proposals  s:  € ð  ×%Ñ% aÑ(ˆ
Øˆ	ØˆØˆ	Ü&/°Ó&?ó 	VÑ"ˆE‘?�F˜EØ(ª¨D°D¸6ÀE¹>Ñ4IÐ,JÐ)JÑK×PÑPÐQ[Ð]cÐejÐlmÓnˆMÜ Ÿ9™9 m²A²q¸!¸Q°JÑ&?Ð%?ÀÓCˆLÜŸ)™) ]²1°aº¸A°:Ñ%>Ð$>ÀÓBˆKä%Ü—‘˜q &¨1¡*¨f¼E¿M¹MÐR\×RcÑRcÔdÜ—‘˜q %¨!¡)¨U¼%¿-¹-ÐPZ×PaÑPaÔbØô‰NˆF�Fô
 —9‘9˜f×.Ñ.¨rÓ2°F×4DÑ4DÀRÓ4HÐIÈ2ÓNˆDä—I‘I˜{×4Ñ4°RÓ8¸,×:PÑ:PÐQSÓ:TÐUÐWXÓY×^Ñ^Ð_iÐklÐnoÐqrÓsˆEØ—N‘N 1Ó%×,Ñ,¨Z¸¸RÀÓDÀsÑJÈeÑSˆDÜ Ÿ?™?¨4Ó0°4Ñ7¸3À¹:ÑFˆLÜ—y‘y $¨Ð!5°rÓ:×?Ñ?À
ÈBÐPQÓRˆHØ×Ñ˜XÔ&Ø�F˜U‘NÑ"ˆDØ×Ñ˜TŸ]™]¨6°E©>ÄÇÁ˜]ÓLÈuÑTÖUð%	Vô& !Ÿ9™9 Y°Ó2ÐØ#3°dÑ#:Ð?OÐRVÑ?VÑ"W×!\Ñ!\Ð]_ÐimÐ!\Ó!nÐÜ Ÿ9™9Ð%5¸Ð=MÑ9MÑ%NÓOÐØ+×7Ñ7¸×8NÑ8NÈrÓ8RÔTYÐZ_ÓT`ÓaÐØ+×7Ñ7Ð9OÐ8OÔQVÐW\ÓQ]Ó^Ðð "ˆØ#×/Ñ/°×0FÑ0FÀrÓ0JÌEÐRSËHÓUˆØ#×/Ñ/Ð1GÐ0GÌÈqËÓRˆØ×+Ñ+¨D¯O©O¸LÓ,IÓJˆÜ—I‘I˜iÓ(ˆ	ØÐ-¨yÐ8Ð8rJ   ©Úoutput_typerÕ  rÔ   rÕ   Údecoder_attention_maskÚencoder_outputsrú  Údecoder_inputs_embedsrn  r÷  rû  r(  c
                 óì  — |�|n| j                   j                  }|�|n| j                   j                  }|	�|	n| j                   j                  }	|j                  \  }
}}}|j
                  }|€)t        j                  |
||ft        j                  |¬«      }| j                  ||«      \  }}g }g }t        |«      D ]J  \  }\  }}|j                   | j                  |   |«      «       |j                  |«       |�ŒAt        d«      ‚ | j                   j                  t        |«      kD  �r2t        |«      }t!        || j                   j                  «      D �]  }||k(  r | j                  |   |d   d   «      }n | j                  |   |d   «      }t"        j$                  j'                  |d   j)                  «       |j                  dd ¬«      j+                  t        j,                  «      d   }| j                  j/                  ||«      j+                  |j0                  «      }|j                  |«       |j                  |«       |j                  |«       �Œ d}| j                   j2                  s| j4                  j6                  }|D �cg c]  }|j                  dd ‘Œ }}|D �cg c]#  }|j9                  d«      j;                  d	d«      ‘Œ% }}|D �cg c]  }|j9                  d	«      ‘Œ }}g }t        |«      D ]Z  \  }}|j9                  d«      j;                  d	d«      }|| j<                  |   j?                  d	d	d«      z   }|j                  |«       Œ\ t        j@                  |d	«      }t        j@                  |d	«      }t        j@                  |d	«      }t        jB                  |t        j                  |j
                  ¬«      }t        j@                  |jE                  d
«      |jG                  d	«      jI                  d«      dd f«      }t        jJ                  |D � cg c]  } | jM                  | «      ‘Œ c} d	«      }!|!j)                  «       }!|€| jO                  ||||||!|||	¬«	      }nI|	rGtQ        |tR        «      s7tS        |d   t        |«      d	kD  r|d	   ndt        |«      dkD  r|d   nd¬«      }|d   j                  \  }
}"}d}#d}$d}%| j                   j2                  �r¹| jU                  |d   | |«      \  }&}%}' | jV                  jX                  d   |&«      }# | jV                  jZ                  d   |&«      }(|(|%z   }$| j\                  })|#d   }*| j^                  �rta        |$jc                  «       j)                  «       «      je                  dd	«      }+g },t!        |
«      D �]·  }-|+|-   }.|*|-   }/d}0g }1t!        t        |«      «      D ]@  }2|'|2k(  }3|1j                  t        jf                  |/jc                  «       |3z  |0«      d	   «       ŒB t        j@                  |1«      }1ti        |.|1   |/|1   |'|1   d«      }4|1|4   }5t        |5«      | j\                  k  rAtk        dt        |5«      › d| j\                  › d�«       t        jf                  |*|-   |)«      d	   }5|)t        |«      z  }6|'|5   d   t        jl                  t        |«      |'j
                  ¬«      dd…df   k(  }7|7|7jI                  d	«      |6k  z  }8|8jo                  d«      }8|8jq                  «       |)k  r,|)|8jq                  «       z
  }9|8 js                  «       d|9 }:d|8|:<   |5|8   };|,j                  |;«       �Œº t        jJ                  |,«      },nt        jf                  |#d   |)d	¬«      d	   },t        jt                  |$d	|,jw                  d«      jy                  d	d	d«      «      }<|<j{                  «       }<|<jc                  «       }=|=}>| j}                  | j                  | j�                  |<«      «      «      }?t        j‚                  |?|d¬«      \  }@}At        jJ                  t!        |
«      D �-cg c]  }-|&|-   |,|-      ‘Œ c}-«      j{                  «       }BA| j…                  | j‡                  |B«      «      z   }An€t        j‚                  ||d	¬«      \  }@}A|@jw                  d«      j‰                  |
dd«      }@|Ajw                  d«      j‰                  |
dd«      }A| j‹                  |@«      jc                  «       }=|=}>| jW                  A@|d   ||=|||!|||	¬«      }C|	s"t�        d„ |#|$fD «       «      }D|>fCz   |z   |Dz   }E|ES t�        |>Cj�                  |Cj’                  |Cj”                  |Cj–                  |Cj˜                  |Cjš                  |j�                  |j–                  |j˜                  |#|$|%¬«      S c c}w c c}w c c}w c c} w c c}-w )a  
        Returns:

        Examples:

        ```python
        >>> from transformers import AutoImageProcessor, DetaModel
        >>> from PIL import Image
        >>> import requests

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> image_processor = AutoImageProcessor.from_pretrained("jozhang97/deta-swin-large-o365")
        >>> model = DetaModel.from_pretrained("jozhang97/deta-swin-large-o365", two_stage=False)

        >>> inputs = image_processor(images=image, return_tensors="pt")

        >>> outputs = model(**inputs)

        >>> last_hidden_states = outputs.last_hidden_state
        >>> list(last_hidden_states.shape)
        [1, 900, 256]
        ```Nrö   zNo attention mask was providedr«   r   r×   rØ   rì   r!   )r!   )	rú  rm  rè   rw  rx  rè  rn  r÷  rû  rö  rp  r¯  gÍÌÌÌÌÌì?z[WARNING] nms proposals (z) < z, running naive topkr  Trú   r   )rú  rè   ro   ru  rv  rw  rx  rè  rn  r÷  rû  c              3   ó&   K  — | ]	  }|€Œ|–— Œ y ­wr>   rW   )rò  rC   s     r9   rô  z$DetaModel.forward.<locals>.<genexpr>  s   è ø€ Òv¨%ÐdiÑdu¤Ñvùrõ  )rk   r_   r`   ra   rl   rm   rd   rn   ro   rp   rq   rr   rs   )NrÑ   rn  r÷  rø  rÞ   r¹   rf   rš   rN  rÒ   r0  râ   r!  rð   rN  r½   r}   r   rÛ   rÜ   rÝ   rß   rà   rÐ   rá   rÓ  r"  r“   r  r1  rË  r4  r  Ú	as_tensorÚ	new_zerosÚprodrý   r  rC  r#  r¶   r   r[  r$  r  r  r,  r+  rZ   r  r‰   Útopkr[   Úprintrÿ   r±  r3  ÚnonzeroÚgatherr  r  r  r(  r'  rG  r.  r*  r)  rK  rv  rù  rj   r_   r`   ra   rb   rc   rd   )Frœ   rÔ   rÕ   r^  r_  rú  r`  rn  r÷  rû  r6  Únum_channelsr  r  r¹   rã   Úposition_embeddings_listÚsourcesÚmasksrê  Úsourcerç   Ú_len_sourcesÚpos_lÚquery_embedsrw  Úsource_flattenÚmask_flattenÚlvl_pos_embed_flattenÚ	pos_embedÚlvl_pos_embedrx  Úmrè  r7  rq   rr   rs   Úobject_query_embeddingrR  Ú
delta_bboxrf  Úproposal_logitÚproposal_boxesÚtopk_proposalsÚbÚprop_boxes_bÚprop_logits_bÚpre_nms_topkÚpre_nms_indsÚlvlÚlvl_maskÚpost_nms_indsÚ	keep_indsÚq_per_lÚis_level_orderedÚkeep_inds_maskÚ
num_to_addÚpad_indsÚkeep_inds_topkÚtopk_coords_logitsrv  rk   Úpos_trans_outÚquery_embedÚtargetÚ
topk_featsÚdecoder_outputsÚenc_outputsÚtuple_outputssF                                                                         r9   rI   zDetaModel.forward8  só	  € ðL 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆà2>×2DÑ2DÑ/ˆ
�L &¨%Ø×$Ñ$ˆàÐÜŸ™ j°&¸%Ð%@ÌÏÉÐ\bÔcˆJð
 .2¯]©]¸<ÈÓ-TÑ*ˆÐ*ð ˆØˆÜ%.¨xÓ%8ò 	CÑ!ˆE‘>�F˜DØ�N‰NÐ1˜4Ÿ?™?¨5Ñ1°&Ó9Ô:Ø�L‰L˜ÔØ‰|Ü Ð!AÓBÐBð		Cð �;‰;×)Ñ)¬C°«LÓ8Ü˜w›<ˆLÜ˜|¨T¯[©[×-KÑ-KÓLó 	7�Ø˜LÒ(Ø3˜TŸ_™_¨UÑ3°H¸R±LÀ±OÓD‘Fà3˜TŸ_™_¨UÑ3°G¸B±KÓ@�FÜ—}‘}×0Ñ0°¸DÑ1A×1GÑ1GÓ1IÐPV×P\ÑP\Ð]_Ð]`ÐPaÐ0Ób×eÑeÔfk×fpÑfpÓqÐrsÑt�ØŸ™×8Ñ8¸ÀÓF×IÑIÈ&Ï,É,ÓW�Ø—‘˜vÔ&Ø—‘˜TÔ"Ø(×/Ñ/°Ö6ð	7ð ˆØ�{‰{×$Ò$Ø×9Ñ9×@Ñ@ˆLð <CÖC°˜6Ÿ<™<¨¨Ò+ÐCˆÐCØJQÖRÀ˜&Ÿ.™.¨Ó+×5Ñ5°a¸Õ;ÐRˆÐRØ49Ö:¨D˜Ÿ™ Q�Ð:ˆÐ:à "ÐÜ )Ð*BÓ Cò 	8ÑˆE�9Ø!×)Ñ)¨!Ó,×6Ñ6°q¸!Ó<ˆIØ%¨×(8Ñ(8¸Ñ(?×(DÑ(DÀQÈÈ2Ó(NÑNˆMØ!×(Ñ(¨Õ7ð	8ô
 Ÿ™ >°1Ó5ˆÜ—y‘y ¨qÓ1ˆÜ %§	¡	Ð*?ÀÓ CÐÜŸ™¨¼u¿z¹zÐR`×RgÑRgÔhˆÜ!ŸI™I ~×'?Ñ'?ÀÓ'EÀ~×GZÑGZÐ[\ÓG]×GdÑGdÐefÓGgÐhkÐikÐGlÐ&mÓnÐÜ—{‘{ÀUÖ#KÀ D×$8Ñ$8¸Õ$;Ò#KÈQÓOˆØ#×)Ñ)Ó+ˆð Ð"Ø"Ÿl™lØ,Ø+Ø$9Ø-Ø"3Ø)Ø"3Ø%9Ø'ð +ó 
‰Oñ ¤¨O¼_Ô!MÜ-Ø"1°!Ñ"4Ü47¸Ó4HÈ1Ò4L˜o¨aÒ0ÐRVÜ14°_Ó1EÈÒ1I˜?¨1Ò-ÈtôˆOð '6°aÑ&8×&>Ñ&>Ñ#ˆ
�A�|Ø ÐØ#'Ð ØÐØ�;‰;× Ó ØBF×BcÑBcØ Ñ" \ M°>óCÑ?Ð"Ð$4°ið != §¡× 8Ñ 8¸Ñ <Ð=SÓ TÐà4˜Ÿ™×0Ñ0°Ñ4Ð5KÓLˆJØ'1Ð4DÑ'DÐ$ð ×/Ñ/ˆDØ.¨vÑ6ˆNà×&Ó&Ü!9Ð:R×:ZÑ:ZÓ:\×:bÑ:bÓ:dÓ!e×!kÑ!kÐlmÐopÓ!q�Ø!#�Ü˜zÓ*ó ):�AØ#1°!Ñ#4�LØ$2°1Ñ$5�Mð $(�LØ#%�LÜ$¤S¨Ó%8Ó9ò m˜Ø#,°Ñ#3˜Ø$×+Ñ+¬E¯J©J°}×7LÑ7LÓ7NÐQYÑ7YÐ[gÓ,hÐijÑ,kÕlðmô $)§9¡9¨\Ó#:�Lô %0Ø$ \Ñ2°MÀ,Ñ4OÐQZÐ[gÑQhÐjmó%�Mð !-¨]Ñ ;�Iä˜9“~¨×(DÑ(DÒDÜØ7¼¸I»Ð7GÀtÈD×LhÑLhÐKið j*ð *ôô %*§J¡J¨~¸aÑ/@À$Ó$GÈÑ$J˜	ð #¤c¨.Ó&9Ñ9�Gà! )Ñ,¨TÑ2Ü Ÿ<™<¬¨NÓ(;ÀI×DTÑDTÔUÒVWÐY]ÐV]Ñ^ñ_ð %ð &6Ð9I×9PÑ9PÐQRÓ9SÐW^Ñ9^Ñ%_�NØ%3×%7Ñ%7¸Ó%:�Nð &×)Ñ)Ó+¨dÒ2Ø%)¨N×,>Ñ,>Ó,@Ñ%@˜
Ø%3 O×#<Ñ#<Ó#>¸{À
Ð#K˜Ø37˜ xÑ0à%.¨~Ñ%>�NØ"×)Ñ)¨.Ö9ðS):ôT "'§¡¨^Ó!<‘ä!&§¡Ð,=¸fÑ,EÀtÐQRÔ!SÐTUÑ!V�ä!&§¡Ø(¨!¨^×-EÑ-EÀbÓ-I×-PÑ-PÐQRÐTUÐWXÓ-Yó"Ðð "4×!:Ñ!:Ó!<ÐØ1×9Ñ9Ó;ÐØ$4Ð!Ø ×/Ñ/°·±¸t×?ZÑ?ZÐ[mÓ?nÓ0oÓpˆMÜ"'§+¡+¨m¸\ÈqÔ"QÑˆK˜äŸ™ÜGLÈZÓGXÖYÀ!Ð'¨Ñ*¨>¸!Ñ+<Ó=ÒYóç‰f‹hð ð ˜d×1Ñ1°$·.±.ÀÓ2LÓMÑM‰Fä"'§+¡+¨l¸LÈaÔ"PÑˆK˜Ø%×/Ñ/°Ó2×9Ñ9¸*ÀbÈ"ÓMˆKØ×%Ñ% aÓ(×/Ñ/°
¸BÀÓCˆFØ#×4Ñ4°[ÓA×IÑIÓKÐØ$4Ð!àŸ,™,Ø Ø +Ø"1°!Ñ"4Ø#/Ø-Ø)Ø/Ø%Ø/Ø!5Ø#ð 'ó 
ˆñ ÜÑvÐ4EÐG_Ð3`ÔvÓvˆKØ2Ð4°ÑFÈÑXÐ[fÑfˆMà Ð äØ"7Ø-×?Ñ?Ø'6×'QÑ'QØ*9×*WÑ*WØ"1×"?Ñ"?Ø.×9Ñ9Ø,×=Ñ=Ø&5×&GÑ&GØ"1×"?Ñ"?Ø.×9Ñ9Ø/Ø%=Ø-ô
ð 	
ùòo DùÚRùÚ:ùò $LùòT Zs   ÊgÊ+(g"Ëg'Ð)g,ág1)NNNNNNNN)rS   rT   rU   r"   r˜   r2  r5  r:  r<  rf   rþ   rC  rG  r[  r   ÚDETA_INPUTS_DOCSTRINGr   rj   Ú_CONFIG_FOR_DOCrg   r   Ú
LongTensorrà   r	   r   rI   r±   r²   s   @r9   r  r  ’  sN  ø„ ð>˜zõ >ò@òò(ò'ð +0¯-©-ó 	òò"29ñh +Ð+@ÓAÙ¨?ÈÔYð 26Ø>BØ7;Ø59Ø=AØ,0Ø/3Ø&*ñw
à×'Ñ'ðw
ð ˜U×-Ñ-Ñ.ðw
ð !)¨×):Ñ):Ñ ;ð	w
ð
 " %×"3Ñ"3Ñ4ðw
ð   × 1Ñ 1Ñ2ðw
ð  (¨×(9Ñ(9Ñ:ðw
ð $ D™>ðw
ð ' t™nðw
ð ˜d‘^ðw
ð 
ˆu�U×&Ñ&Ñ'¨Ð8Ñ	9òw
ó Zó Bôw
rJ   r  z™
    DETA Model (consisting of a backbone and encoder-decoder Transformer) with object detection heads on top, for tasks
    such as COCO detection.
    c                   ó¸  ‡ — e Zd ZddgZdZdefˆ fd„Zej                  j                  d„ «       Z
 ee«       eee¬«      	 	 	 	 	 	 	 	 	 ddej                   d	eej$                     d
eej                      deej                      deej                      deej                      deee      dee   dee   dee   deeej                      ef   fd„«       «       Zˆ xZS )ÚDetaForObjectDetectionzbbox_embed\.\d+zclass_embed\.\d+NrÑ   c                 óŽ  •— t         ‰| �  |«       t        |«      | _        t	        j
                  |j                  |j                  «      | _        t        |j                  |j                  dd¬«      | _
        d}t        j                  d|z
  |z  «       }t        j                  |j                  «      |z  | j                  j                  _        t        j"                  j%                  | j                  j&                  d   j(                  j                   d«       t        j"                  j%                  | j                  j&                  d   j                  j                   d«       |j*                  r|j,                  dz   n|j,                  }|j.                  r­t1        | j                  |«      | _        t1        | j                  |«      | _
        t        j"                  j%                  | j                  d   j&                  d   j                  j                   dd  d	«       | j                  | j                  j2                  _
        nßt        j"                  j%                  | j                  j&                  d   j                  j                   dd  d	«       t	        j4                  t7        |«      D �cg c]  }| j                  ‘Œ c}«      | _        t	        j4                  t7        |«      D �cg c]  }| j                  ‘Œ c}«      | _
        d | j                  j2                  _
        |j*                  rz| j                  | j                  j2                  _        | j                  D ]F  }t        j"                  j%                  |j&                  d   j                  j                   dd  d
«       ŒH | j9                  «        y c c}w c c}w )Nr   rü   )Ú	input_dimr9  Ú
output_dimÚ
num_layersrI  r!   r«   r   rì   g       Àr[  )r—   r˜   r  rÁ   r   rQ  r%  Ú
num_labelsr  ÚDetaMLPPredictionHeadr  rñ   rŠ   rf   rš   r”   rº   r_  r`  rß  r“   rÓ  r  Úwith_box_refinerƒ   r$  r|   r}   rá  )rœ   rÑ   Ú
prior_probÚ
bias_valueÚnum_predr7  Ú	box_embedrž   s          €r9   r˜   zDetaForObjectDetection.__init__A  s³  ø€ Ü‰Ñ˜Ô ô ˜vÓ&ˆŒ
ô Ÿ9™9 V§^¡^°V×5FÑ5FÓGˆÔÜ/Ø—n‘n°·±ÈAÐZ[ô
ˆŒð ˆ
Ü—h‘h  J¡°*Ñ<Ó=Ð=ˆ
Ü%*§Z¡Z°×0AÑ0AÓ%BÀZÑ%Oˆ×Ñ×ÑÔ"Ü
�‰×Ñ˜$Ÿ/™/×0Ñ0°Ñ4×;Ñ;×@Ñ@À!ÔDÜ
�‰×Ñ˜$Ÿ/™/×0Ñ0°Ñ4×9Ñ9×>Ñ>ÀÔBð 39×2BÒ2B�F×)Ñ)¨AÒ-È×H]ÑH]ˆØ×!Ò!Ü*¨4×+;Ñ+;¸XÓFˆDÔÜ)¨$¯/©/¸8ÓDˆDŒOÜ�G‰G×Ñ˜dŸo™o¨aÑ0×7Ñ7¸Ñ;×@Ñ@×EÑEÀaÀbÐIÈ4ÔPà,0¯O©OˆD�J‰J×ÑÕ)ä�G‰G×Ñ˜dŸo™o×4Ñ4°RÑ8×=Ñ=×BÑBÀ1À2ÐFÈÔMÜ!Ÿ}™}ÌÈhËÖ-XÀ1¨d×.>Ó.>Ò-XÓYˆDÔÜ Ÿm™mÄeÈHÃoÖ,VÀ¨T¯_«_Ò,VÓWˆDŒOØ,0ˆD�J‰J×ÑÔ)Ø×Òà-1×-=Ñ-=ˆD�J‰J×ÑÔ*Ø!Ÿ_™_ò K�	Ü—‘×!Ñ! )×"2Ñ"2°2Ñ"6×";Ñ";×"@Ñ"@ÀÀÐ"DÀcÕJðKð 	�‰Õùò .YùÚ,Vs   Ê1N=Ë,Oc                 ó    — t        |j                  dd«      d d |j                  dd«      d d «      D ��cg c]
  \  }}||dœ‘Œ }}}|S c c}}w )Nr   r!   r«   )rx   ry   )Úzipr1  )rœ   Úoutputs_classÚoutputs_coordrx   ry   Úaux_losss         r9   Ú_set_aux_lossz$DetaForObjectDetection._set_aux_lossi  si   € ô '*¨-×*AÑ*AÀ!ÀQÓ*GÈÈÐ*LÈm×NeÑNeÐfgÐijÓNkÐloÐmoÐNpÓ&q÷
á"�˜
ð ¨ZÓ8ð
ˆñ 
ð ˆùó	
s   ¶A
r\  rÔ   rÕ   r^  r_  rú  r`  Úlabelsrn  r÷  rû  r(  c                 óŠ
  ‡'‡(— |
�|
n| j                   j                  }
| j                  ||||||||	|
¬«	      }|
r|j                  n|d   }|
r|j                  n|d   }|
r|j
                  n|d   }g }g }t        |j                  d   «      D ]ä  }|dk(  r|}n|dd…|dz
  f   }t        |«      } | j                  |   |dd…|f   «      } | j                  |   |dd…|f   «      }|j                  d   dk(  r||z   }nA|j                  d   dk(  r|d	dd…fxx   |z  cc<   |}nt        d
|j                  d   › �«      ‚|j                  «       }|j                  |«       |j                  |«       Œæ t        j                  |d¬«      }t        j                  |d¬«      }|dd…df   }|dd…df   }d\  }Š'}|��•t!        | j                   j"                  | j                   j$                  | j                   j&                  ¬«      }g d¢}t)        || j                   j*                  | j                   j,                  || j                   j.                  | j                   j0                  | j                   j2                  ¬«      }|j5                  |j6                  «       i }||d<   ||d<   ||d<   | j                   j8                  r| j;                  ||«      }||d<   | j                   j<                  rE|j>                  j                  «       }|j@                  ||jB                  j                  «       dœ|d<    |||«      Š'd| j                   jD                  dœŠ(| j                   jF                  ‰(d<   | j                   j8                  r©i } t        | j                   jH                  dz
  «      D ];  }!| jK                  ‰(jM                  «       D �"�#ci c]  \  }"}#|"d|!› �z   |#“Œ c}#}"«       Œ= | jK                  ‰(jM                  «       D �"�#ci c]  \  }"}#|"dz   |#“Œ c}#}"«       ‰(jK                  | «       tO        ˆ'ˆ(fd„‰'jQ                  «       D «       «      }|
s#|�||f|z   |z   }$n||f|z   }$|�	|‰'f|$z   }%|%S |$}%|%S tS        d*i d|“d‰'“d|“d|“d|“d|jT                  “d|jV                  “d|jX                  “d |jZ                  “d!|j\                  “d"|j^                  “d#|j`                  “d$|j                  “d%|j
                  “d&|j                  “d'|j@                  “d(|j>                  “d)|jB                  “Ž}&|&S c c}#}"w c c}#}"w )+aù  
        labels (`List[Dict]` of len `(batch_size,)`, *optional*):
            Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
            following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch
            respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes
            in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.

        Returns:

        Examples:

        ```python
        >>> from transformers import AutoImageProcessor, DetaForObjectDetection
        >>> from PIL import Image
        >>> import requests

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> image_processor = AutoImageProcessor.from_pretrained("jozhang97/deta-swin-large")
        >>> model = DetaForObjectDetection.from_pretrained("jozhang97/deta-swin-large")

        >>> inputs = image_processor(images=image, return_tensors="pt")
        >>> outputs = model(**inputs)

        >>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
        >>> target_sizes = torch.tensor([image.size[::-1]])
        >>> results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[
        ...     0
        ... ]
        >>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
        ...     box = [round(i, 2) for i in box.tolist()]
        ...     print(
        ...         f"Detected {model.config.id2label[label.item()]} with confidence "
        ...         f"{round(score.item(), 3)} at location {box}"
        ...     )
        Detected cat with confidence 0.802 at location [9.87, 54.36, 316.93, 473.44]
        Detected cat with confidence 0.795 at location [346.62, 24.35, 639.62, 373.2]
        Detected remote with confidence 0.725 at location [40.41, 73.36, 175.77, 117.29]
        Detected remote with confidence 0.638 at location [333.34, 76.81, 370.22, 187.94]
        Detected couch with confidence 0.584 at location [0.03, 0.99, 640.02, 474.93]
        ```N)rÕ   r^  r_  rú  r`  rn  r÷  rû  rì   r   rü   r!   r«   r   .z.reference.shape[-1] should be 4 or 2, but got rú   )NNN)Ú
class_costÚ	bbox_costÚ	giou_cost)rª  ÚboxesÚcardinality)ÚmatcherÚnum_classesÚfocal_alphaÚlossesr:  r+  Úassign_second_stagerx   ry   Úinit_referencerz   )rx   ry   Úanchorsr’  )Úloss_ceÚ	loss_bboxÚ	loss_giour7  Ú_encc              3   ó>   •K  — | ]  }|‰v sŒ‰|   ‰|   z  –— Œ y ­wr>   rW   )rò  Úkrw   Úweight_dicts     €€r9   rô  z1DetaForObjectDetection.forward.<locals>.<genexpr>	  s'   øè ø€ Òc¸ÐRSÐWbÒRb�y ‘| k°!¡nÕ4Ñcùs   ƒ	�rv   rw   r_   rl   rm   rd   rn   ro   rp   r`   ra   rk   rq   rr   rs   rW   )1rÑ   rø  rÁ   r`   rk   ra   r}   rÞ   r�   r  r  rð   r  râ   rf   r  ÚDetaHungarianMatcherr¬  r­  r®  ÚDetaLossr�  r³  r:  r+  rµ  rß   r¹   Úauxiliary_lossr©  rÓ  rr   rq   rs   Úbbox_loss_coefficientÚgiou_loss_coefficientr  ÚupdateÚitemsr3  Úkeysru   r_   rl   rm   rd   rn   ro   rp   ))rœ   rÔ   rÕ   r^  r_  rú  r`  rª  rn  r÷  rû  r¶  rb   r¶  Úinter_referencesÚoutputs_classesÚoutputs_coordsrê  Ú	referencer¦  ry  Úoutputs_coord_logitsr§  rx   ry   rv   rz   r±  r´  Ú	criterionÚoutputs_lossÚenc_outputs_coordÚaux_weight_dictr‚   r½  ró  rH   r“  Údict_outputsrw   r¾  s)                                          @@r9   rI   zDetaForObjectDetection.forwardt  s¡  ù€ ðr &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆð —*‘*ØØ!Ø#9Ø+Ø'Ø"7Ø/Ø!5Ø#ð ó 

ˆñ ?J˜×:Ò:ÈwÐWXÉzˆÙ:E˜×6Ò6È7ÐSTÉ:ˆÙDO˜7×@Ò@ÐU\Ð]^ÑU_Ðð ˆØˆä˜=×.Ñ.¨qÑ1Ó2ò 	1ˆEØ˜ŠzØ*‘	à,ªQ°¸±	¨\Ñ:�	Ü'¨	Ó2ˆIØ3˜D×,Ñ,¨UÑ3°MÂ!ÀUÀ(Ñ4KÓLˆMØ/˜Ÿ™¨Ñ/°ºaÀ¸hÑ0GÓHˆJØ�‰˜rÑ" aÒ'Ø'1°IÑ'=Ñ$Ø—‘ Ñ$¨Ò)Ø˜3   ˜7Ó# yÑ0Ó#Ø'1Ñ$ä Ð#QÐR[×RaÑRaÐbdÑReÐQfÐ!gÓhÐhØ0×8Ñ8Ó:ˆMØ×"Ñ" =Ô1Ø×!Ñ! -Õ0ð#	1ô& Ÿ™ O¸Ô;ˆÜŸ™ N¸Ô:ˆàšq "˜uÑ%ˆØ"¢1 b 5Ñ)ˆ
à-=Ñ*ˆˆiÐ*ØÑä*ØŸ;™;×1Ñ1¸T¿[¹[×=RÑ=RÐ^b×^iÑ^i×^sÑ^sôˆGò 8ˆFÜ ØØ ŸK™K×2Ñ2Ø ŸK™K×3Ñ3ØØ ŸK™K×3Ñ3Ø#'§;¡;×#AÑ#AØ$(§K¡K×$CÑ$CôˆIð �L‰L˜Ÿ™Ô'àˆLØ%+ˆL˜Ñ"Ø)3ˆL˜Ñ&Ø-;ˆLÐ)Ñ*Ø�{‰{×)Ò)Ø$(×$6Ñ$6°}ÀmÓ$TÐ!Ø4E�Ð0Ñ1Ø�{‰{×$Ò$Ø$+×$DÑ$D×$LÑ$LÓ$NÐ!à%×7Ñ7Ø"3Ø&×7Ñ7×?Ñ?ÓAñ/�˜]Ñ+ñ " ,°Ó7ˆIà&'°d·k±k×6WÑ6WÑXˆKØ'+§{¡{×'HÑ'HˆK˜Ñ$Ø�{‰{×)Ò)Ø"$�Ü˜tŸ{™{×9Ñ9¸AÑ=Ó>ò ]�AØ#×*Ñ*À{×GXÑGXÓGZ×+[¹t¸qÀ!¨A°!°A°3°©K¸©NÓ+[Õ\ð]à×&Ñ&À+×BSÑBSÓBU×'V¹$¸!¸Q¨¨F©
°A©Ó'VÔWØ×"Ñ" ?Ô3ÜÔc¸i¿n¹nÓ>NÔcÓcˆDáØ Ð,Ø  *Ð-Ð0AÑAÀGÑK‘à  *Ð-°Ñ7�Ø<@Ð<L˜d IÐ.°Ñ7ˆMà Ð ð SYˆMà Ð ä0ò 
Ùð
áð
ñ ð
ñ "ð	
ñ
 0ð
ð &×7Ò7ð
ð #*×"?Ò"?ð
ð  '×9Ò9ð
ð %×5Ò5ð
ð '.×&GÒ&Gð
ð #*×"?Ò"?ð
ð  '×9Ò9ð
ð (/×'IÒ'Ið
ð +2×*OÒ*Oð
ð #*×"?Ò"?ð
ð  &×7Ò7ð!
ð" &-×%EÒ%Eð#
ð$ %×5Ò5ð%
ˆð* ÐùóG ,\ùÛ'Vs   Ï
T9ÐT?
r   )rS   rT   rU   Ú_tied_weights_keysrØ  r"   r˜   rf   ÚjitÚunusedr©  r   r”  r   ru   r•  rg   r   r–  r   Údictrà   r	   r   rI   r±   r²   s   @r9   r˜  r˜  4  sm  ø„ ð -Ð.AÐBÐàÐð&˜zõ &ðP ‡Y�Y×Ññó ðñ +Ð+@ÓAÙÐ+DÐSbÔcð 26Ø>BØ7;Ø59Ø=AØ'+Ø,0Ø/3Ø&*ñsà×'Ñ'ðsð ˜U×-Ñ-Ñ.ðsð !)¨×):Ñ):Ñ ;ð	sð
 " %×"3Ñ"3Ñ4ðsð   × 1Ñ 1Ñ2ðsð  (¨×(9Ñ(9Ñ:ðsð ˜˜d™Ñ$ðsð $ D™>ðsð ' t™nðsð ˜d‘^ðsð 
ˆu�U×&Ñ&Ñ'Ð)BÐBÑ	Còsó dó BôsrJ   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ì   r«   )r  r  r3  )ÚinputsÚtargetsÚ	num_boxesÚ	numeratorÚdenominatorrv   s         r9   Ú	dice_lossrÛ  ,  sz   € ð �^‰^Ó€FØ�^‰^˜AÓ€FØ�V˜gÑ%×*Ñ*¨1Ó-Ñ-€IØ—*‘*˜R“. 7§;¡;¨r£?Ñ2€KØ�	˜A‘ +°¡/Ñ2Ñ2€DØ�8‰8‹:˜	Ñ!Ð!rJ   ÚalphaÚgammac                 ó  — | j                  «       }t        j                  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 (`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).
        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   )r  r   rÛ   Ú binary_cross_entropy_with_logitsrÈ  r3  )
rÖ  r×  rØ  rÜ  rÝ  ÚprobÚce_lossÚp_trv   Úalpha_ts
             r9   Úsigmoid_focal_lossrç  ?  s¡   € ð$ �>‰>Ó€DÜ�m‰m×<Ñ<¸VÀWÐX^Ð<Ó_€Gà
�‰.˜A ™H¨¨W©Ñ5Ñ
5€CØ�q˜3‘w 5Ñ(Ñ)€Dà�‚zØ˜'‘/ Q¨¡Y°1°w±;Ñ$?Ñ?ˆØ˜‰~ˆà�9‰9�Q‹<×ÑÓ 	Ñ)Ð)rJ   c                   óz   ‡ — e Zd ZdZ	 	 d
ˆ fd„	Zd„ Z ej                  «       d„ «       Zd„ Z	d„ Z
d„ Zd„ Zd	„ Zˆ xZS )rÀ  aä  
    This class computes the losses for `DetaForObjectDetection`. 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 (supervised class and box).

    Args:
        matcher (`DetaHungarianMatcher`):
            Module able to compute a matching between targets and proposals.
        num_classes (`int`):
            Number of object categories, omitting the special no-object category.
        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                 óæ   •— t         ‰| �  «        || _        || _        || _        || _        || _        || _        | j                  rt        «       | _	        | j                  rt        |«      | _        y y r>   )r—   r˜   r±  r²  r³  r´  r+  rµ  ÚDetaStage1AssignerÚstg1_assignerÚDetaStage2AssignerÚstg2_assigner)	rœ   r±  r²  r³  r´  r:  r+  rµ  rž   s	           €r9   r˜   zDetaLoss.__init__o  sm   ø€ ô 	‰ÑÔØˆŒØ&ˆÔØ&ˆÔØˆŒØ"4ˆÔØ#6ˆÔ à×"Ò"Ü!3Ó!5ˆDÔØ×#Ò#Ü!3°KÓ!@ˆDÕð $rJ   c           	      óö  — d|vrt        d«      ‚|d   }| j                  |«      }t        j                  t	        ||«      D ���	cg c]  \  }\  }}	|d   |	   ‘Œ c}	}}«      }
t        j
                  |j                  dd | j                  t        j                  |j                  ¬«      }|
||<   t        j                  |j                  d   |j                  d   |j                  d   dz   g|j                  |j                  |j                  ¬	«      }|j                  d|j                  d
«      d«       |dd…dd…dd
…f   }t        |||| j                   d¬«      |j                  d   z  }d|i}|S c c}	}}w )z 
        Classification loss (Binary focal loss) targets dicts must contain the key "class_labels" containing a tensor
        of dim [nb_target_boxes]
        rx   z#No logits were found in the outputsÚclass_labelsNrì   rö   r   r!   )rá   Úlayoutr¹   r«   )rÜ  rÝ  r¸  )ÚKeyErrorÚ_get_source_permutation_idxrf   r  r¥  ÚfullrÞ   r²  r   r¹   r›   rá   rð  Úscatter_r  rç  r³  )rœ   r¶  r×  ÚindicesrØ  Úsource_logitsr  Útr7  ÚJÚtarget_classes_oÚtarget_classesÚtarget_classes_onehotr¸  r´  s                  r9   Úloss_labelszDetaLoss.loss_labels†  sƒ  € ð
 ˜7Ñ"ÜÐ@ÓAÐAØ Ñ)ˆà×.Ñ.¨wÓ7ˆÜ Ÿ9™9ÌCÐPWÐY`ÓLa×%bÐ%b¹y¸qÁ&À1Àa a¨Ñ&7¸Ó&:Ô%bÓcÐÜŸ™Ø×Ñ  Ð# T×%5Ñ%5¼U¿[¹[ÐQ^×QeÑQeô
ˆð /ˆ�sÑä %§¡Ø× Ñ  Ñ# ]×%8Ñ%8¸Ñ%;¸]×=PÑ=PÐQRÑ=SÐVWÑ=WÐXØ×%Ñ%Ø ×'Ñ'Ø ×'Ñ'ô	!
Ðð 	×&Ñ& q¨.×*BÑ*BÀ2Ó*FÈÔJà 5²aº¸C¸R¸C°iÑ @Ðä˜}Ð.CÀYÐVZ×VfÑVfÐnoÔpØ×!Ñ! !Ñ$ñ%ð 	ð ˜WÐ%ˆàˆùô+ &cs   ÁE4c           	      óz  — |d   }|j                   }t        j                  |D �cg c]  }t        |d   «      ‘Œ c}|¬«      }|j	                  d«      |j
                  d   dz
  k7  j                  d«      }	t        j                  j                  |	j                  «       |j                  «       «      }
d|
i}|S c c}w )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.
        rx   rï  r  r«   r!   Úcardinality_error)r¹   rf   rc  r½   ÚargmaxrÞ   r3  r   rÛ   Úl1_lossrÝ   )rœ   r¶  r×  rõ  rØ  rx   r¹   ró  Útarget_lengthsÚ	card_predÚcard_errr´  s               r9   Úloss_cardinalityzDetaLoss.loss_cardinality§  s¤   € ð ˜Ñ"ˆØ—‘ˆÜŸ™È'Ö)RÀQ¬#¨a°Ñ.?Õ*@Ò)RÐ[aÔbˆà—]‘] 2Ó&¨&¯,©,°rÑ*:¸QÑ*>Ñ>×CÑCÀAÓFˆ	Ü—=‘=×(Ñ(¨¯©Ó):¸N×<PÑ<PÓ<RÓSˆØ% xÐ0ˆØˆùò *Ss   ¥B8c           	      óê  — d|vrt        d«      ‚| j                  |«      }|d   |   }t        j                  t	        ||«      D ���	cg c]  \  }\  }}	|d   |	   ‘Œ c}	}}d¬«      }
t
        j                  j                  ||
d¬«      }i }|j                  «       |z  |d<   d	t        j                  t        t        |«      t        |
«      «      «      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.
        ry   z#No predicted boxes found in outputsr¯  r   rú   rß  rà  r¹  r!   rº  )rñ  rò  rf   r  r¥  r   rÛ   r   r3  ÚdiagÚgeneralized_box_iourZ   )rœ   r¶  r×  rõ  rØ  r  Úsource_boxesr÷  r7  r‚   Útarget_boxesr¹  r´  rº  s                 r9   Ú
loss_boxeszDetaLoss.loss_boxes·  sñ   € ð ˜wÑ&ÜÐ@ÓAÐAØ×.Ñ.¨wÓ7ˆØ˜|Ñ,¨SÑ1ˆÜ—y‘yÄÀWÈgÓAV×!WÐ!W±I°A±v¸¸1 ! G¡*¨Q£-Ô!WÐ]^Ô_ˆä—M‘M×)Ñ)¨,¸ÐPVÐ)ÓWˆ	àˆØ'Ÿm™m›o°	Ñ9ˆˆ{ÑàœŸ
™
ÜÔ 8¸Ó FÔH`ÐamÓHnÓoó
ñ 
ˆ	ð (Ÿm™m›o°	Ñ9ˆˆ{ÑØˆùô "Xs   ÁC.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>   ©rf   r  r0  Ú	full_like)rœ   rõ  r‚   rn  r7  Ú	batch_idxÚ
source_idxs          r9   rò  z$DetaLoss._get_source_permutation_idxÏ  si   € ä—I‘IÔPYÐZaÓPb×cÐc¹n¸aÁÀ&È!œuŸ™¨v°qÕ9ÔcÓdˆ	Ü—Y‘Y¸'×B©;¨F°A¢ÓBÓCˆ
Ø˜*Ð$Ð$ùô dùÛBó   Ÿ#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  )rœ   rõ  r‚   r7  r�  r  Ú
target_idxs          r9   Ú_get_target_permutation_idxz$DetaLoss._get_target_permutation_idxÕ  si   € ä—I‘IÔPYÐZaÓPb×cÐc¹n¸aÁÀ!ÀVœuŸ™¨v°qÕ9ÔcÓdˆ	Ü—Y‘Y¸'×B©;¨A¨v¢ÓBÓCˆ
Ø˜*Ð$Ð$ùô dùÛBr  c                 óŒ   — | j                   | j                  | j                  dœ}||vrt        d|› d�«      ‚ ||   ||||«      S )N)rª  r°  r¯  zLoss z not supported)rü  r  r
  rð   )rœ   rv   r¶  r×  rõ  rØ  Úloss_maps          r9   Úget_losszDetaLoss.get_lossÛ  sW   € à×&Ñ&Ø×0Ñ0Ø—_‘_ñ
ˆð
 �xÑÜ˜u T F¨.Ð9Ó:Ð:Øˆx˜‰~˜g w°¸ÓCÐCrJ   c           
      ó¨  — |j                  «       D ��ci c]  \  }}|dvsŒ||“Œ }}}| j                  r| j                  ||«      }n| j                  ||«      }t	        d„ |D «       «      }t        j                  |gt
        j                  t        t        |j                  «       «      «      j                  ¬«      }d}t        «       r2t        j                  i k7  rt        |«      }t        «       j                   }t        j"                  ||z  d¬«      j%                  «       }i }	| j&                  D ]&  }
|	j)                  | j+                  |
||||«      «       Œ( d|v r”t-        |d   «      D ]ƒ  \  }}| j                  s| j                  ||«      }| j&                  D ]Q  }
| j+                  |
||||«      }|j                  «       D ��ci c]  \  }}|d|› �z   |“Œ }}}|	j)                  |«       ŒS Œ… d|v rÊ|d   }t/        j0                  |«      }|D ]  }t        j2                  |d	   «      |d	<   Œ | j4                  r| j7                  ||«      }n| j                  ||«      }| j&                  D ]N  }
| j+                  |
||||«      }|j                  «       D ��ci c]  \  }}|d
z   |“Œ }}}|	j)                  |«       ŒP |	S c c}}w c c}}w c c}}w )aª  
        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.
        )rz   r’  c              3   ó8   K  — | ]  }t        |d    «      –— Œ y­w)rï  N)r½   )rò  r÷  s     r9   rô  z#DetaLoss.forward.<locals>.<genexpr>ù  s   è ø€ Ò@°1œ˜A˜nÑ-×.Ñ@ùs   ‚rö   r!   rˆ   rz   r7  r’  rï  r»  )rÅ  rµ  rí  r±  r3  rf   rc  rÝ   ÚnextÚiterÚvaluesr¹   r   rX   Ú_shared_staterY   Únum_processesr‰   r/  r´  rÄ  r  r0  r~   r   Ú
zeros_liker+  rë  )rœ   r¶  r×  r½  ró  Úoutputs_without_auxrõ  rØ  Ú
world_sizer´  rv   r‚   rz   Úl_dictr’  Úbin_targetsÚbts                    r9   rI   zDetaLoss.forwardå  s¼  € ð 18·±³×q©¨¨1À1ÐLpÒCp˜q !™tÐqÐÑqð ×#Ò#Ø×(Ñ(Ð)<¸gÓF‰Gà—l‘lÐ#6¸Ó@ˆGô Ñ@¸Ô@Ó@ˆ	Ü—O‘O Y K´u·{±{Ì4ÔPTÐU\×UcÑUcÓUeÓPfÓKg×KnÑKnÔoˆ	àˆ
Ü"Ô$Ü×)Ñ)¨RÒ/Ü" 9Ó-�	Ü)›^×9Ñ9�
Ü—K‘K 	¨JÑ 6¸AÔ>×CÑCÓEˆ	ð ˆØ—K‘Kò 	UˆDØ�M‰M˜$Ÿ-™-¨¨g°wÀÈÓSÕTð	Uð  'Ñ)Ü(1°'Ð:MÑ2NÓ(Oò *Ñ$�Ð$Ø×/Ò/Ø"Ÿl™lÐ+<¸gÓF�GØ ŸK™Kò *�DØ!Ÿ]™]¨4Ð1BÀGÈWÐV_Ó`�FØ9?¿¹»×H±°°A˜a A a S '™k¨1™nÐH�FÑHØ—M‘M &Õ)ñ*ð*ð ˜GÑ#Ø! -Ñ0ˆKÜŸ-™-¨Ó0ˆKØ!ò J�Ü%*×%5Ñ%5°b¸Ñ6HÓ%I��>Ò"ðJà×&Ò&Ø×,Ñ,¨[¸+ÓF‘àŸ,™, {°KÓ@�ØŸ™ò &�ØŸ™ t¨[¸+ÀwÐPYÓZ�Ø4:·L±L³N×C©D¨A¨q˜!˜f™* a™-ÐC�ÑCØ—‘˜fÕ%ð&ð
 ˆùóa rùó> Iùó Ds   ”K¡KÇK
ÊK)FF)rS   rT   rU   re   r˜   rü  rf   rÈ   r  r
  rò  r  r  rI   r±   r²   s   @r9   rÀ  rÀ  ^  sR   ø„ ñð. !Ø!õAò.ðB €U‡]�]ƒ_ñó ðòò0%ò%òDö;rJ   rÀ  c                   ó(   ‡ — e Zd ZdZˆ fd„Zd„ Zˆ xZS )rž  a  
    Very simple multi-layer perceptron (MLP, also called FFN), used to predict the normalized center coordinates,
    height and width of a bounding box w.r.t. an image.

    Copied from https://github.com/facebookresearch/detr/blob/master/models/detr.py

    c                 ó¨   •— t         ‰| �  «        || _        |g|dz
  z  }t        j                  d„ t        |g|z   ||gz   «      D «       «      | _        y )Nr!   c              3   óN   K  — | ]  \  }}t        j                  ||«      –— Œ y ­wr>   )r   rQ  )rò  r�   r½  s      r9   rô  z1DetaMLPPredictionHead.__init__.<locals>.<genexpr>0	  s   è ø€ Ò#g¹¸¸1¤B§I¡I¨a°§OÑ#gùs   ‚#%)r—   r˜   rœ  r   r|   r¥  rß  )rœ   rš  r9  r›  rœ  Úhrž   s         €r9   r˜   zDetaMLPPredictionHead.__init__,	  sS   ø€ Ü‰ÑÔØ$ˆŒØˆL˜J¨™NÑ+ˆÜ—m‘mÑ#gÄÀYÀKÐRSÁOÐUVÐZdÐYeÑUeÓ@fÔ#gÓgˆ�rJ   c                 ó¾   — t        | j                  «      D ]D  \  }}|| j                  dz
  k  r%t        j                  j                   ||«      «      n ||«      }ŒF |S )Nr!   )r0  rß  rœ  r   rÛ   Úrelu)rœ   r‹   r‚   Úlayers       r9   rI   zDetaMLPPredictionHead.forward2	  sT   € Ü! $§+¡+Ó.ò 	V‰HˆAˆuØ01°D·O±OÀaÑ4GÒ0G”—‘×"Ñ"¡5¨£8Ô,ÉUÐSTËX‰Að	VàˆrJ   r  r²   s   @r9   rž  rž  #	  s   ø„ ñôhörJ   rž  c                   ó`   ‡ — e Zd ZdZddededefˆ fd„Z ej                  «       d„ «       Zˆ xZ	S )r¿  aÑ  
    This class computes an assignment between the targets and the predictions of the network.

    For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more
    predictions than targets. In this case, we do a 1-to-1 matching of the best predictions, while the others are
    un-matched (and thus treated as non-objects).

    Args:
        class_cost:
            The relative weight of the classification error in the matching cost.
        bbox_cost:
            The relative weight of the L1 error of the bounding box coordinates in the matching cost.
        giou_cost:
            The relative weight of the giou loss of the bounding box in the matching cost.
    r¬  r­  r®  c                 óž   •— t         ‰| �  «        t        | dg«       || _        || _        || _        |dk(  r|dk(  r|dk(  rt        d«      ‚y y y )NÚscipyr   z#All costs of the Matcher can't be 0)r—   r˜   r   r¬  r­  r®  rð   )rœ   r¬  r­  r®  rž   s       €r9   r˜   zDetaHungarianMatcher.__init__I	  sX   ø€ Ü‰ÑÔÜ˜$  	Ô*à$ˆŒØ"ˆŒØ"ˆŒØ˜Š?˜y¨Aš~°)¸q².ÜÐBÓCÐCð 3A˜~ˆ?rJ   c           	      óŽ  — |d   j                   dd \  }}|d   j                  dd«      j                  «       }|d   j                  dd«      }t        j                  |D �cg c]  }|d   ‘Œ	 c}«      }t        j                  |D �cg c]  }|d   ‘Œ	 c}«      }	d	}
d
}d|
z
  ||z  z  d|z
  dz   j                  «        z  }|
d|z
  |z  z  |dz   j                  «        z  }|dd…|f   |dd…|f   z
  }t        j                  ||	d¬«      }t        t        |«      t        |	«      «       }| j                  |z  | j                  |z  z   | j                  |z  z   }|j                  ||d«      j                  «       }|D �cg c]  }t        |d   «      ‘Œ }}t        |j!                  |d«      «      D ��cg c]  \  }}t#        ||   «      ‘Œ }}}|D ��cg c]O  \  }}t        j$                  |t        j&                  ¬«      t        j$                  |t        j&                  ¬«      f‘ŒQ c}}S c c}w c c}w c c}w c c}}w c c}}w )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.
            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)
        rx   Nrì   r   r!   ry   rï  r¯  ç      Ð?r\  g:Œ0âŽyE>)rŽ  r«   rô   )rÞ   r  r  rf   r  rŠ   Úcdistr  rZ   r­  r¬  r®  r4  r'   r½   r0  r.  r\   rc  r   )rœ   r¶  r×  r6  r:  Úout_probÚout_bboxró  Ú
target_idsÚtarget_bboxrÜ  rÝ  Úneg_cost_classÚpos_cost_classr¬  r­  r®  Úcost_matrixÚsizesr‚   Úcrõ  Újs                          r9   rI   zDetaHungarianMatcher.forwardS	  s3  € ð* #*¨(Ñ"3×"9Ñ"9¸"¸1Ð"=Ñˆ
�Kð ˜8Ñ$×,Ñ,¨Q°Ó2×:Ñ:Ó<ˆØ˜<Ñ(×0Ñ0°°AÓ6ˆô —Y‘Y¸7ÖC°a  .Ó 1ÒCÓDˆ
Ü—i‘i°WÖ =°  7£Ò =Ó>ˆð ˆØˆØ˜e™)¨°%©Ñ8¸aÀ(¹lÈTÑ>Q×=VÑ=VÓ=XÐ<XÑYˆØ 1 x¡<°EÑ"9Ñ:ÀÈ4Á×?TÑ?TÓ?VÐ>VÑWˆØ#¢A z MÑ2°^ÂAÀzÀMÑ5RÑRˆ
ô —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ˆÐ2Ü;DÀ[×EVÑEVÐW\Ð^`ÓEaÓ;b×c±4°1°aÔ(¨¨1©Õ.ÐcˆÑcØkr×sÑcgÐcdÐfg”—‘ ¬%¯+©+Ô6¼¿¹ÈÔQV×Q\ÑQ\Ô8]Ò^ÓsÐsùò-  DùÚ =ùò& 3ùÛcùÛss   Á!H,ÂH1Å?H6Æ4H;ÇAI)r!   r!   r!   )
rS   rT   rU   re   rÝ   r˜   rf   rÈ   rI   r±   r²   s   @r9   r¿  r¿  8	  sD   ø„ ññ D 5ð D¸ð DÈuõ Dð €U‡]�]ƒ_ñ1tó ô1trJ   r¿  r÷  c                 ó  — | j                  «       r>| j                  t        j                  t        j                  fv r| S | j                  «       S | j                  t        j                  t        j                  fv r| S | j                  «       S r>   )	Úis_floating_pointrá   rf   rþ   Úfloat64rÝ   Úint32r   r|  )r÷  s    r9   Ú_upcastr?  ˆ	  s`   € à×ÑÔØ—G‘G¤§¡¬u¯}©}Ð=Ñ=ˆqÐLÀ1Ç7Á7Ã9ÐLà—G‘G¤§¡¬U¯[©[Ð9Ñ9ˆqÐF¸q¿u¹u»wÐFrJ   r¯  c                 óf   — t        | «      } | dd…df   | dd…df   z
  | dd…df   | dd…df   z
  z  S )a´  
    Computes the area of a set of bounding boxes, which are specified by its (x1, y1, x2, y2) coordinates.

    Args:
        boxes (`torch.FloatTensor` of shape `(number_of_boxes, 4)`):
            Boxes for which the area will be computed. They are expected to be in (x1, y1, x2, y2) format with `0 <= x1
            < x2` and `0 <= y1 < y2`.

    Returns:
        `torch.FloatTensor`: a tensor containing the area for each box.
    Nrì   r   rü   r!   )r?  )r¯  s    r9   Úbox_arearA  �	  sB   € ô �E‹N€EØ’!�Q�$‰K˜%¢ 1 ™+Ñ%¨%²°1°©+¸ºaÀ¸d¹Ñ*CÑDÐDrJ   c                 ó^  — t        | «      }t        |«      }t        j                  | d d …d d d…f   |d d …d d…f   «      }t        j                  | d d …d dd …f   |d d …dd …f   «      }||z
  j	                  d¬«      }|d d …d d …df   |d d …d d …df   z  }|d d …d f   |z   |z
  }||z  }	|	|fS )Nrì   r   rˆ   r!   )rA  rf   r‡   r†   r‰   )
Úboxes1Úboxes2Úarea1Úarea2Úleft_topÚright_bottomÚwidth_heightÚinterÚunionÚious
             r9   Úbox_iourM   	  sÊ   € Ü�VÓ€EÜ�VÓ€Eä�y‰y˜¢ 4¨¨!¨ Ñ,¨f²Q¸¸¸°U©mÓ<€HÜ—9‘9˜V¢A t¨Q©R KÑ0°&º¸A¹B¸±-Ó@€Là  8Ñ+×2Ñ2°qÐ2Ó9€LØššA˜q˜Ñ! L²²A°q°Ñ$9Ñ9€Eà’!�T�'‰N˜UÑ" UÑ*€Eà
�%‰-€CØ�ˆ:ÐrJ   c                 ó  — | dd…dd…f   | dd…dd…f   k\  j                  «       st        d| › �«      ‚|dd…dd…f   |dd…dd…f   k\  j                  «       st        d|› �«      ‚t        | |«      \  }}t        j                  | dd…ddd…f   |dd…dd…f   «      }t        j
                  | dd…ddd…f   |dd…dd…f   «      }||z
  j                  d¬«      }|dd…dd…df   |dd…dd…df   z  }|||z
  |z  z
  S )zâ
    Generalized IoU from https://giou.stanford.edu/. The boxes should be in [x0, y0, x1, y1] (corner) format.

    Returns:
        `torch.FloatTensor`: a [N, M] pairwise matrix, where N = len(boxes1) and M = len(boxes2)
    Nrì   z<boxes1 must be in [x0, y0, x1, y1] (corner) format, but got z<boxes2 must be in [x0, y0, x1, y1] (corner) format, but got r   rˆ   r!   )rO  rð   rM  rf   r†   r‡   r‰   )rC  rD  rL  rK  Útop_leftÚbottom_rightrI  Úareas           r9   r  r  °	  s*  € ð ’1�a‘b�5‰M˜V¢A r¨ r E™]Ñ*×/Ñ/Ô1ÜÐWÐX^ÐW_Ð`ÓaÐaØ’1�a‘b�5‰M˜V¢A r¨ r E™]Ñ*×/Ñ/Ô1ÜÐWÐX^ÐW_Ð`ÓaÐaÜ˜ Ó(�J€Cˆä�y‰y˜¢ 4¨¨!¨ Ñ,¨f²Q¸¸¸°U©mÓ<€HÜ—9‘9˜V¢A t¨Q©R KÑ0°&º¸A¹B¸±-Ó@€Là  8Ñ+×2Ñ2°qÐ2Ó9€LØšš1˜a˜Ñ  <²²1°a°Ñ#8Ñ8€Dà�$˜‘, $Ñ&Ñ&Ð&rJ   c                 ó"  — t         j                  j                  «       r`| j                  «       dk(  r.| j	                  d«      j                  «       j                  d«      S | j                  «       j                  d«      S | j                  d¬«      S )z‹
    A 'as_tuple=True' version of torch.nonzero to support torchscript. because of
    https://github.com/pytorch/pytorch/issues/38718
    r   r!   T)Úas_tuple)rf   rÒ  Úis_scriptingrû   r  rh  Úunbind)r‹   s    r9   Únonzero_tuplerV  É	  sk   € ô
 ‡y�y×ÑÔØ�5‰5‹7�aŠ<Ø—;‘;˜q“>×)Ñ)Ó+×2Ñ2°1Ó5Ð5Ø�y‰y‹{×!Ñ! !Ó$Ð$à�y‰y $ˆyÓ'Ð'rJ   c                   ó>   — e Zd ZdZd	dee   dee   defd„Zd„ Z	d„ Z
y)
ÚDetaMatcheraÔ  
    This class assigns to each predicted "element" (e.g., a box) a ground-truth element. Each predicted element will
    have exactly zero or one matches; each ground-truth element may be matched to zero or more predicted elements.

    The matching is determined by the MxN match_quality_matrix, that characterizes how well each (ground-truth,
    prediction)-pair match each other. For example, if the elements are boxes, this matrix may contain box
    intersection-over-union overlap values.

    The matcher returns (a) a vector of length N containing the index of the ground-truth element m in [0, M) that
    matches to prediction n in [0, N). (b) a vector of length N containing the labels for each prediction.
    Ú
thresholdsrª  Úallow_low_quality_matchesc           	      ó¨  — |dd }|d   dk  rt        d«      ‚|j                  dt        d«       «       |j                  t        d«      «       t	        d„ t        |dd |dd «      D «       «      st        d«      ‚t	        d	„ |D «       «      st        d
«      ‚t        |«      t        |«      dz
  k7  rt        d«      ‚|| _        || _        || _	        y)a6  
        Args:
            thresholds (`list[float]`):
                A list of thresholds used to stratify predictions into levels.
            labels (`list[int`):
                A list of values to label predictions belonging at each level. A label can be one of {-1, 0, 1}
                signifying {ignore, negative class, positive class}, respectively.
            allow_low_quality_matches (`bool`, *optional*, defaults to `False`):
                If `True`, produce additional matches for predictions with maximum match quality lower than
                high_threshold. See `set_low_quality_matches_` for more details.

            For example,
                thresholds = [0.3, 0.5] labels = [0, -1, 1] All predictions with iou < 0.3 will be marked with 0 and
                thus will be considered as false positives while training. All predictions with 0.3 <= iou < 0.5 will
                be marked with -1 and thus will be ignored. All predictions with 0.5 <= iou will be marked with 1 and
                thus will be considered as true positives.
        Nr   zThresholds should be positiverJ  c              3   ó,   K  — | ]  \  }}||k  –— Œ y ­wr>   rW   )rò  ÚlowÚhighs      r9   rô  z'DetaMatcher.__init__.<locals>.<genexpr>ý	  s   è ø€ ÒW¡; C¨�3˜$•;ÑWùs   ‚r«   r!   zThresholds should be sorted.c              3   ó$   K  — | ]  }|d v –— Œ
 y­w))r«   r   r!   NrW   )rò  Úls     r9   rô  z'DetaMatcher.__init__.<locals>.<genexpr>ÿ	  s   è ø€ Ò3 q�1˜
”?Ñ3ùr	  z&All labels should be either -1, 0 or 1z<Number of labels should be equal to number of thresholds - 1)
rð   ÚinsertrÝ   râ   rO  r¥  r½   rY  rª  rZ  )rœ   rY  rª  rZ  s       r9   r˜   zDetaMatcher.__init__ä	  sÍ   € ð&  ¡�]ˆ
Ø�a‰=˜1ÒÜÐ<Ó=Ð=Ø×Ñ˜!œe E›l˜]Ô+Ø×Ñœ% ›,Ô'äÑW´#°jÀÀ"°oÀzÐRSÐRTÀ~Ó2VÔWÔWÜÐ;Ó<Ð<ÜÑ3¨FÔ3Ô3ÜÐEÓFÐFÜˆv‹;œ#˜j›/¨AÑ-Ò-ÜÐ[Ó\Ð\Ø$ˆŒØˆŒØ)BˆÕ&rJ   c                 óÒ  — |j                  «       dk(  sJ ‚|j                  «       dk(  ru|j                  |j                  d«      fdt        j
                  ¬«      }|j                  |j                  d«      f| j                  d   t        j                  ¬«      }||fS t	        j                  |dk\  «      sJ ‚|j                  d¬«      \  }}|j                  |j                  «       dt        j                  ¬«      }t        | j                  | j                  dd | j                  dd «      D ]  \  }}}	||k\  ||	k  z  }
|||
<   Œ | j                  r| j                  ||«       ||fS )a†  
        Args:
            match_quality_matrix (Tensor[float]): an MxN tensor, containing the
                pairwise quality between M ground-truth elements and N predicted elements. All elements must be >= 0
                (due to the us of `torch.nonzero` for selecting indices in `set_low_quality_matches_`).

        Returns:
            matches (Tensor[int64]): a vector of length N, where matches[i] is a matched
                ground-truth index in [0, M)
            match_labels (Tensor[int8]): a vector of length N, where pred_labels[i] indicates
                whether a prediction is a true or false positive or ignored
        rì   r   r!   rô   rú   Nr«   )rû   ÚnumelÚnew_fullrÙ   rf   r   rª  Úint8rO  r‡   r¥  rY  rZ  Úset_low_quality_matches_)rœ   Úmatch_quality_matrixÚdefault_matchesÚdefault_match_labelsÚmatched_valsÚmatchesÚmatch_labelsr`  r]  r^  Úlow_highs              r9   r  zDetaMatcher.__call__
  su  € ð $×'Ñ'Ó)¨QÒ.Ð.Ð.Ø×%Ñ%Ó'¨1Ò,Ø2×;Ñ;Ð=Q×=VÑ=VÐWXÓ=YÐ<[Ð]^Ôfk×fqÑfqÐ;ÓrˆOð $8×#@Ñ#@Ø%×*Ñ*¨1Ó-Ð/°·±¸Q±ÄuÇzÁzð $Aó $Ð ð #Ð$8Ð8Ð8ä�y‰yÐ-°Ñ2Ô3Ð3Ð3ð !5× 8Ñ 8¸QÐ 8Ó ?Ñˆ�gà×'Ñ'¨¯©«¸ÄÇÁÐ'ÓLˆä §¡¨T¯_©_¸S¸bÐ-AÀ4Ç?Á?ÐSTÐSUÐCVÓWò 	'‰LˆAˆs�DØ$¨Ñ+°¸tÑ0CÑDˆHØ%&ˆL˜Ò"ð	'ð ×)Ò)Ø×)Ñ)¨,Ð8LÔMà˜Ð$Ð$rJ   c                 óh   — |j                  d¬«      \  }}t        ||dd…df   k(  «      \  }}d||<   y)a¦  
        Produce additional matches for predictions that have only low-quality matches. Specifically, for each
        ground-truth G find the set of predictions that have maximum overlap with it (including ties); for each
        prediction in that set, if it is unmatched, then match it to the ground-truth G.

        This function implements the RPN assignment case (i) in Sec. 3.1.2 of :paper:`Faster R-CNN`.
        r!   rú   N)r‡   rV  )rœ   rl  rg  Úhighest_quality_foreach_gtr7  Úpred_inds_with_highest_qualitys         r9   rf  z$DetaMatcher.set_low_quality_matches_0
  sO   € ð )=×(@Ñ(@ÀQÐ(@Ó(GÑ%Ð" Aô -:Ð:NÐRlÒmnÐptÐmtÑRuÑ:uÓ,vÑ)ˆÐ)ð 89ˆÐ3Ò4rJ   N©F)rS   rT   rU   re   r   rÝ   r|  rà   r˜   r  rf  rW   rJ   r9   rX  rX  ×	  s:   „ ñ
ñ!C 4¨¡;ð !C¸¸S¹	ð !CÐ^bó !CòF'%óR9rJ   rX  rª  Únum_samplesÚpositive_fractionÚbg_labelc                 óÄ  — t        | dk7  | |k7  z  «      d   }t        | |k(  «      d   }t        ||z  «      }t        |j                  «       |«      }||z
  }t        |j                  «       |«      }t	        j
                  |j                  «       |j                  ¬«      d| }t	        j
                  |j                  «       |j                  ¬«      d| }	||   }
||	   }|
|fS )aC  
    Return `num_samples` (or fewer, if not enough found) random samples from `labels` which is a mixture of positives &
    negatives. It will try to return as many positives as possible without exceeding `positive_fraction * num_samples`,
    and then try to fill the remaining slots with negatives.

    Args:
        labels (Tensor): (N, ) label vector with values:
            * -1: ignore
            * bg_label: background ("negative") class
            * otherwise: one or more foreground ("positive") classes
        num_samples (int): The total number of labels with value >= 0 to return.
            Values that are not sampled will be filled with -1 (ignore).
        positive_fraction (float): The number of subsampled labels with values > 0
            is `min(num_positives, int(positive_fraction * num_samples))`. The number of negatives sampled is
            `min(num_negatives, num_samples - num_positives_sampled)`. In order words, if there are not enough
            positives, the sample is filled with negatives. If there are also not enough negatives, then as many
            elements are sampled as is possible.
        bg_label (int): label index of background ("negative") class.

    Returns:
        pos_idx, neg_idx (Tensor):
            1D vector of indices. The total length of both is `num_samples` or fewer.
    r«   r   r  N)rV  r|  r†   rc  rf   Úrandpermr¹   )rª  rr  rs  rt  ÚpositiveÚnegativeÚnum_posÚnum_negÚperm1Úperm2Úpos_idxÚneg_idxs               r9   Úsubsample_labelsr  E
  sØ   € ô0 ˜f¨™l¨v¸Ñ/AÑBÓCÀAÑF€HÜ˜V xÑ/Ó0°Ñ3€Hä�+Ð 1Ñ1Ó2€Gä�(—.‘.Ó" GÓ,€GØ˜GÑ#€Gä�(—.‘.Ó" GÓ,€Gô �N‰N˜8Ÿ>™>Ó+°H·O±OÔDÀXÀgÐN€EÜ�N‰N˜8Ÿ>™>Ó+°H·O±OÔDÀXÀgÐN€Eà�u‰o€GØ�u‰o€GØ�GÐÐrJ   c           	      ó¨  — t        |«      dk(  r| |fS |j                  d¬«      \  }}||   j                  |d¬«      \  }}|d d …d f   j                  d|«      }t	        j
                  t        ||«      D ��	cg c]
  \  }}	|	d | ‘Œ c}	}«      }
t	        j
                  t        ||«      D ��cg c]
  \  }}|d | ‘Œ c}}«      }|
|fS c c}	}w c c}}w )Nr   T)Úreturn_countsr!   rú   )r½   Úuniquerf  r  rf   r  r¥  )Úpr_indsÚgt_indsrL  r½  Úgt_inds2ÚcountsÚscoresÚpr_inds2r9  ÚprÚpr_inds3ÚgtÚgt_inds3s                r9   Úsample_topk_per_gtr�  p
  sÑ   € Ü
ˆ7ƒ|�qÒØ˜ÐÐà—~‘~°D�~Ó9Ñ€HˆfØ˜8‘}×)Ñ)¨!°Ð)Ó3Ñ€FˆHØš˜4˜Ñ ×'Ñ'¨¨1Ó-€Hô �y‰y¬c°&¸(Ó.C×D¡U Q¨˜"˜R˜aš&ÓDÓE€HÜ�y‰y¬c°&¸(Ó.C×D¡U Q¨˜"˜R˜aš&ÓDÓE€HØ�XÐÐùó EùÛDs   Á8C
Â-C
c                   ó~   ‡ — e Zd Zdˆ fd„	Zdej
                  dej
                  dej
                  fd„Zd	d„Zd„ Zˆ xZ	S )
rì  c                 ó†   •— t         ‰| �  «        d| _        d| _        || _        t        dgddgd¬«      | _        || _        y )Nr/  i�  g333333ã?r   r!   T©rY  rª  rZ  )r—   r˜   rs  rt  Úbatch_size_per_imagerX  Úproposal_matcherr½  )rœ   r:  Úmax_krž   s      €r9   r˜   zDetaStage2Assigner.__init__€
  sD   ø€ Ü‰ÑÔØ!%ˆÔØˆŒØ$/ˆÔ!Ü +¸°uÀaÈÀVÐgkÔ lˆÔØˆ�rJ   Úmatched_idxsÚmatched_labelsÚ
gt_classesc                 óN  — |j                  «       dkD  }|r ||   }| j                  ||dk(  <   d||dk(  <   n"t        j                  |«      | j                  z   }t	        || j
                  | j                  | j                  «      \  }}t        j                  ||gd¬«      }|||   fS )aA  
        Based on the matching between N proposals and M groundtruth, sample the proposals and set their classification
        labels.

        Args:
            matched_idxs (Tensor): a vector of length N, each is the best-matched
                gt index in [0, M) for each proposal.
            matched_labels (Tensor): a vector of length N, the matcher's label
                (one of cfg.MODEL.ROI_HEADS.IOU_LABELS) for each proposal.
            gt_classes (Tensor): a vector of length M.

        Returns:
            Tensor: a vector of indices of sampled proposals. Each is in [0, N). Tensor: a vector of the same length,
            the classification label for
                each sampled proposal. Each sample is labeled as either a category in [0, num_classes) or the
                background (num_classes).
        r   r«   rú   )rc  rt  rf   r  r  r‘  rs  r  )rœ   r”  r•  r–  Úhas_gtÚsampled_fg_idxsÚsampled_bg_idxsÚsampled_idxss           r9   Ú_sample_proposalsz$DetaStage2Assigner._sample_proposalsˆ
  s®   € ð$ ×!Ñ!Ó# aÑ'ˆáØ# LÑ1ˆJà.2¯m©mˆJ�~¨Ñ*Ñ+à/1ˆJ�~¨Ñ+Ò,ä×)Ñ)¨,Ó7¸$¿-¹-ÑGˆJä+;Ø˜×1Ñ1°4×3IÑ3IÈ4Ï=É=ó,
Ñ(ˆ˜ô —y‘y /°?Ð!CÈÔKˆØ˜Z¨Ñ5Ð5Ð5rJ   c                 óÈ  — t        |«      }g }g }t        |«      D ]¾  }t        t        ||   d   «      t        |d   |   j	                  «       «      «      \  }}	| j                  |«      \  }
}| j                  |
|||   d   «      \  }}||| j                  k7     }|
|   }| j                  |||«      \  }}|j                  ||f«       |j                  |«       ŒÀ |r||fS |S )Nr¯  r¶  rï  )
r½   r}   rM  rZ   r  r’  rœ  rt  Úpostprocess_indicesrâ   )rœ   r¶  r×  Úreturn_cost_matrixÚbsrõ  Úiousr}  rL  r7  r”  r•  r›  Úsampled_gt_classesÚpos_pr_indsÚpos_gt_indss                   r9   rI   zDetaStage2Assigner.forward¬
  s  € ô �‹\ˆØˆØˆÜ�r“ò 	ˆAÜÜ(¨°©°GÑ)<Ó=Ü(¨Ð1AÑ)BÀ1Ñ)E×)LÑ)LÓ)NÓOó‰FˆC�ð ,0×+@Ñ+@Øó,Ñ(ˆL˜.ð ×&Ñ&Ø˜n¨g°a©j¸Ñ.HóñØØ"ð 'Ð'9¸T¿]¹]Ñ'JÑKˆKØ& {Ñ3ˆKØ'+×'?Ñ'?ÀÈ[ÐZ]Ó'^Ñ$ˆK˜Ø�N‰N˜K¨Ð5Ô6Ø�K‰K˜Õð%	ñ& Ø˜D�=Ð ØˆrJ   c                 ó2   — t        |||| j                  «      S r>   ©r�  r½  ©rœ   rƒ  r„  rL  s       r9   rž  z&DetaStage2Assigner.postprocess_indicesÉ
  ó   € Ü! '¨7°C¸¿¹Ó@Ð@rJ   )r   rq  )
rS   rT   rU   r˜   rf   r
   rœ  rI   rž  r±   r²   s   @r9   rì  rì  
  s=   ø„ õð"6¨e¯l©lð "6ÈEÏLÉLð "6Ðfk×frÑfró "6óHö:ArJ   rì  c                   ó2   ‡ — e Zd Zdˆ fd„	Zd„ Zd„ Zd„ Zˆ xZS )rê  c                 ó–   •— t         ‰| �  «        d| _        d| _        || _        || _        || _        t        ||gg d¢d¬«      | _        y )Nrõ   r!  )r   r«   r!   Tr�  )	r—   r˜   rs  r‘  r½  Út_lowÚt_highrX  Úanchor_matcher)rœ   r«  r¬  r“  rž   s       €r9   r˜   zDetaStage1Assigner.__init__Ï
  sL   ø€ Ü‰ÑÔØ!$ˆÔØ$'ˆÔ!ØˆŒØˆŒ
ØˆŒÜ)Ø˜v�ªzÐUYô
ˆÕrJ   c                 ó¾   — t        || j                  | j                  d«      \  }}|j                  d«       |j	                  d|d«       |j	                  d|d«       |S )a-  
        Randomly sample a subset of positive and negative examples, and overwrite the label vector to the ignore value
        (-1) for all elements that are not included in the sample.

        Args:
            labels (Tensor): a vector of -1, 0, 1. Will be modified in-place and returned.
        r   r«   r!   )r  r‘  rs  Úfill_rô  )rœ   Úlabelr}  r~  s       r9   Ú_subsample_labelsz$DetaStage1Assigner._subsample_labelsÚ
  sV   € ô ,¨E°4×3LÑ3LÈd×NdÑNdÐfgÓhÑˆ�à�‰�BŒØ�‰�q˜' 1Ô%Ø�‰�q˜' 1Ô%ØˆrJ   c           	      ó   — t        |«      }g }t        |«      D �]q  }|d   |   }t        ||   d   «      dk(  rp|j                  t        j                  g t        j
                  |j                  ¬«      t        j                  g t        j
                  |j                  ¬«      f«       Œ�t        t        ||   d   «      t        |«      «      \  }}| j                  |«      \  }	}
| j                  |
«      }
t        j                  t        |«      |
j                  ¬«      }||
dk(     }|	|   }| j                  |||«      \  }}|j                  |j                  «      |j                  |j                  «      }}|j                  ||f«       �Œt |S )Nr·  r¯  r   rö   r  r!   )r½   r}   râ   rf   rh  rN  r¹   rM  rZ   r­  r±  rÿ   rž  rß   )rœ   r¶  r×  r   rõ  r}  r·  rL  r7  r”  r•  Úall_pr_indsr£  r¤  s                 r9   rI   zDetaStage1Assigner.forwardé
  sl  € Ü�‹\ˆØˆÜ�r“ó 	7ˆAØ˜iÑ(¨Ñ+ˆGÜ�7˜1‘:˜gÑ&Ó'¨1Ò,Ø—‘äŸ™ R¬u¯z©zÀ'Ç.Á.ÔQÜŸ™ R¬u¯z©zÀ'Ç.Á.ÔQðôð ÜÜ(¨°©°GÑ)<Ó=Ü(¨Ó1ó‰FˆC�ð ,0×+>Ñ+>Øó,Ñ(ˆL˜.ð "×3Ñ3°NÓCˆNäŸ,™,¤s¨7£|¸N×<QÑ<QÔRˆKØ% n¸Ñ&9Ñ:ˆKØ& {Ñ3ˆKØ'+×'?Ñ'?ÀÈ[ÐZ]Ó'^Ñ$ˆK˜Ø'2§~¡~°g·n±nÓ'EÀ{Ç~Á~ÐV]×VdÑVdÓGe˜ˆKØ�N‰N˜K¨Ð5Ö6ð1	7ð2 ˆrJ   c                 ó2   — t        |||| j                  «      S r>   r¦  r§  s       r9   rž  z&DetaStage1Assigner.postprocess_indices  r¨  rJ   )g333333Ó?gffffffæ?r   )rS   rT   rU   r˜   r±  rI   rž  r±   r²   s   @r9   rê  rê  Î
  s   ø„ õ	
òòö<ArJ   rê  )r¬   )r/  rì   )pre   r~   rñ   r2   rL  Údataclassesr   Úpathlibr   Útypingr   r   r   r   r	   rf   Útorch.nn.functionalr   rÛ   rr  r
   Útorch.autogradr   Útorch.autograd.functionr   Úactivationsr   Ú
file_utilsr   r   r   r   r   r   r   Úmodeling_attn_mask_utilsr   Úmodeling_outputsr   Úmodeling_utilsr   Úpytorch_utilsr   Úutilsr   r   r   r   r   Úutils.backbone_utilsr    Úconfiguration_detar"   Ú
get_loggerrS   rJ  r)   r:   r<   Ú
acceleraterX   Úaccelerate.utilsrY   Útransformers.image_transformsrZ   Útorchvision.ops.boxesr[   Úscipy.optimizer\   r•  Ú_CHECKPOINT_FOR_DOCr^   rj   ru   rƒ   r�   ÚModuler‘   rÀ   rÅ   rê   r  rÏ   rD  rF  r~  r�  r¹  rÆ  ÚDETA_START_DOCSTRINGr”  rÛ  r  r  r˜  rÛ  rÝ   rç  rÀ  rž  r¿  r?  rA  rM  r  rV  rX  r|  r  r�  rì  rê  rW   rJ   r9   ú<module>rÍ     s‰  ðñ ã Û Û 	Û Ý !Ý ß 5Õ 5ã ß Ð ß Ý #Ý 7å "÷÷ ñ õ DÝ 0Ý .Ý &ß wÕ wÝ 2Ý *ð 
ˆ×	Ñ	˜HÓ	%€à $Ð òô<-Q¨Hô -Qñ` ÔÝ'Ý'áÔÝFáÔÝ1áÔÝ4à	ˆ×	Ñ	˜HÓ	%€à€Ø6Ð ð ô!@˜ó !@ó ð!@ðH ô99�kó 99ó ð99ðx ôO9 ó O9ó ðO9òdDóô$ ˜BŸI™Iô $ òN'ô0*¨"¯)©)ô *ôZ# §	¡	ô #ôL 2§9¡9ô ò.
ð$/Øð$/Ø)/ð$/ØEKð$/Ø`fð$/àó$/ôNL)¨¯	©	ô L)ô^r2˜RŸY™Yô r2ôjT�r—y‘yô Tônl�r—y‘yô lô^0˜/ô 0ð@Ð ð #Ð ôL@
Ð%ô @
ôFw
Ð%ô w
ñt ðð óôX
Ð#ó X
óðX
ñv ðð óônÐ0ó nóðnòb"ñ&*¸%ð *Èuó *ô>Bˆr�y‰yô BôJ˜BŸI™Iô ô*Mt˜2Ÿ9™9ô Mtð`Gˆvð G˜&ó GðE�Fð E˜vó Eò ò 'ò2
(÷j9ñ j9ð\(˜UŸ\™\ð (¸ð (ÐPUð (Ðadó (òVôKA˜Ÿ™ô KAô^:A˜Ÿ™õ :ArJ   