Ë
    S^(h'Y ã                   óL  — d Z ddl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ZmZ ddlmZ ddlmZ dd	lmZmZmZ dd
lmZ ddlmZmZmZmZmZmZmZ ddlm Z  ddl!m"Z"  e«       rddl#m$Z$  ejJ                  e&«      Z'dZ(dZ)e G d„ de«      «       Z*e G d„ de«      «       Z+e G d„ de«      «       Z,e G d„ de«      «       Z- G d„ dej\                  «      Z/d„ Z0 G d„ dej\                  «      Z1 G d„ d ej\                  «      Z2 G d!„ d"ej\                  «      Z3 G d#„ d$ej\                  «      Z4d%„ Z5 G d&„ d'ej\                  «      Z6 G d(„ d)ej\                  «      Z7 G d*„ d+ej\                  «      Z8 G d,„ d-e«      Z9d.Z:d/Z; G d0„ d1e9«      Z< G d2„ d3e9«      Z= ed4e:«       G d5„ d6e9«      «       Z> G d7„ d8ej\                  «      Z? ed9e:«       G d:„ d;e9«      «       Z@ ed<e:«       G d=„ d>e9«      «       ZAd?eBfd@„ZC G dA„ dBej\                  «      ZD G dC„ dDej\                  «      ZEg dE¢ZFy)FzPyTorch DETR model.é    N)Ú	dataclass)ÚDictÚListÚOptionalÚTupleÚUnion)ÚTensorÚnné   )ÚACT2FN)Ú_prepare_4d_attention_mask)ÚBaseModelOutputÚ"BaseModelOutputWithCrossAttentionsÚSeq2SeqModelOutput)ÚPreTrainedModel)ÚModelOutputÚadd_start_docstringsÚ%add_start_docstrings_to_model_forwardÚis_timm_availableÚloggingÚreplace_return_docstringsÚrequires_backends)Úload_backboneé   )Ú
DetrConfig)Úcreate_modelr   zfacebook/detr-resnet-50c                   ó:   — e Zd ZU dZdZeej                     ed<   y)ÚDetrDecoderOutputaº  
    Base class for outputs of the DETR decoder. This class adds one attribute to BaseModelOutputWithCrossAttentions,
    namely an optional stack of intermediate decoder activations, i.e. the output of each decoder layer, each of them
    gone through a layernorm. This is useful when training the model with auxiliary decoding losses.

    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.
        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.
        intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):
            Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
            layernorm.
    NÚintermediate_hidden_states©	Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   ÚtorchÚFloatTensorÚ__annotations__© ó    úd/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/detr/modeling_detr.pyr   r   3   s    … ñð2 ?CÐ ¨×):Ñ):Ñ ;ÔBr)   r   c                   ó:   — e Zd ZU dZdZeej                     ed<   y)ÚDetrModelOutputa)  
    Base class for outputs of the DETR encoder-decoder model. This class adds one attribute to Seq2SeqModelOutput,
    namely an optional stack of intermediate decoder activations, i.e. the output of each decoder layer, each of them
    gone through a layernorm. This is useful when training the model with auxiliary decoding losses.

    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 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, sequence_length, 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, sequence_length,
            sequence_length)`. 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_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.
        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_heads, sequence_length,
            sequence_length)`. 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 `(config.decoder_layers, batch_size, sequence_length, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):
            Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
            layernorm.
    Nr   r    r(   r)   r*   r,   r,   Q   s!   … ñ!ðF ?CÐ ¨×):Ñ):Ñ ;ÔBr)   r,   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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<   y)ÚDetrObjectDetectionOutputa  
    Output type of [`DetrForObjectDetection`].

    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 [`~DetrImageProcessor.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, sequence_length, 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, sequence_length, 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, sequence_length,
            sequence_length)`. 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_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.
        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_heads, sequence_length,
            sequence_length)`. Attentions weights of the encoder, after the attention softmax, used to compute the
            weighted average in the self-attention heads.
    NÚlossÚ	loss_dictÚlogitsÚ
pred_boxesÚauxiliary_outputsÚlast_hidden_stateÚdecoder_hidden_statesÚdecoder_attentionsÚcross_attentionsÚencoder_last_hidden_stateÚencoder_hidden_statesÚencoder_attentions)r!   r"   r#   r$   r/   r   r%   r&   r'   r0   r   r1   r2   r3   r   r4   r5   r   r6   r7   r8   r9   r:   r(   r)   r*   r.   r.   y   s  … ñ-ð^ )-€Dˆ(�5×$Ñ$Ñ
%Ó,Ø $€Iˆx˜‰~Ó$Ø*.€FˆH�U×&Ñ&Ñ'Ó.Ø.2€J�˜×*Ñ*Ñ+Ó2Ø.2Ð�x  T¡
Ñ+Ó2Ø59Ð�x × 1Ñ 1Ñ2Ó9Ø@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Ñ:ÔAr)   r.   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j                     ed<   dZeee
      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<   y)ÚDetrSegmentationOutputaP  
    Output type of [`DetrForSegmentation`].

    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 [`~DetrImageProcessor.post_process_object_detection`] to retrieve the
            unnormalized bounding boxes.
        pred_masks (`torch.FloatTensor` of shape `(batch_size, num_queries, height/4, width/4)`):
            Segmentation masks logits for all queries. See also
            [`~DetrImageProcessor.post_process_semantic_segmentation`] or
            [`~DetrImageProcessor.post_process_instance_segmentation`]
            [`~DetrImageProcessor.post_process_panoptic_segmentation`] to evaluate semantic, instance and panoptic
            segmentation masks respectively.
        auxiliary_outputs (`list[Dict]`, *optional*):
            Optional, only returned when auxiliary 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, sequence_length, 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, sequence_length, 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, sequence_length,
            sequence_length)`. 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_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.
        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_heads, sequence_length,
            sequence_length)`. Attentions weights of the encoder, after the attention softmax, used to compute the
            weighted average in the self-attention heads.
    Nr/   r0   r1   r2   Ú
pred_masksr3   r4   r5   r6   r7   r8   r9   r:   )r!   r"   r#   r$   r/   r   r%   r&   r'   r0   r   r1   r2   r=   r3   r   r4   r5   r   r6   r7   r8   r9   r:   r(   r)   r*   r<   r<   ¸   s3  … ñ3ðj )-€Dˆ(�5×$Ñ$Ñ
%Ó,Ø $€Iˆx˜‰~Ó$Ø*.€FˆH�U×&Ñ&Ñ'Ó.Ø.2€J�˜×*Ñ*Ñ+Ó2Ø.2€J�˜×*Ñ*Ñ+Ó2Ø.2Ð�x  T¡
Ñ+Ó2Ø59Ð�x × 1Ñ 1Ñ2Ó9Ø@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Ñ:ÔAr)   r<   c                   ó2   ‡ — e Zd ZdZˆ fd„Zˆ fd„Zd„ Zˆ xZS )ÚDetrFrozenBatchNorm2dzú
    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_bufferr%   ÚonesÚzeros)ÚselfÚnÚ	__class__s     €r*   rF   zDetrFrozenBatchNorm2d.__init__  sn   ø€ Ü‰ÑÔØ×Ñ˜X¤u§z¡z°!£}Ô5Ø×Ñ˜V¤U§[¡[°£^Ô4Ø×Ñ˜^¬U¯[©[¸«^Ô<Ø×Ñ˜]¬E¯J©J°q«MÕ:r)   c           	      óH   •— |dz   }||v r||= t         ‰	| �  |||||||«       y )NÚnum_batches_tracked)rE   Ú_load_from_state_dict)
rJ   Ú
state_dictÚprefixÚlocal_metadataÚstrictÚmissing_keysÚunexpected_keysÚ
error_msgsÚnum_batches_tracked_keyrL   s
            €r*   rO   z+DetrFrozenBatchNorm2d._load_from_state_dict  s?   ø€ ð #)Ð+@Ñ"@ÐØ" jÑ0ØÐ2Ð3ä‰Ñ%Ø˜ °¸ÀoÐWaõ	
r)   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   éÿÿÿÿgñhãˆµøä>)rA   ÚreshaperB   rD   rC   Úrsqrt)rJ   ÚxrA   rB   rD   rC   ÚepsilonÚscales           r*   ÚforwardzDetrFrozenBatchNorm2d.forward  s«   € ð —‘×$Ñ$ Q¨¨A¨qÓ1ˆØ�y‰y× Ñ   B¨¨1Ó-ˆØ×&Ñ&×.Ñ.¨q°"°a¸Ó;ˆØ×(Ñ(×0Ñ0°°B¸¸1Ó=ˆØˆØ˜+¨Ñ/×6Ñ6Ó8Ñ8ˆØ�l UÑ*Ñ*ˆØ�5‰y˜4ÑÐr)   )r!   r"   r#   r$   rF   rO   r_   Ú__classcell__©rL   s   @r*   r?   r?      s   ø„ ñô;ô	
ö
 r)   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 `DetrFrozenBatchNorm2d`.

    Args:
        model (torch.nn.Module):
            input model
    Úmetar   N)Únamed_childrenÚ
isinstancer
   ÚBatchNorm2dr?   Únum_featuresrA   Údevicer%   ÚdataÚcopy_rB   rC   rD   Ú_modulesÚlenÚlistÚchildrenÚreplace_batch_norm)ÚmodelÚnameÚmoduleÚ
new_modules       r*   ro   ro   '  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Ö&ñ'r)   c                   óZ   ‡ — e Zd ZdZˆ fd„Zdej                  dej                  fd„Zˆ xZS )ÚDetrConvEncoderzµ
    Convolutional backbone, using either the AutoBackbone API or one from the timm library.

    nn.BatchNorm2d layers are replaced by DetrFrozenBatchNorm2d as defined above.

    c                 ó,  •— t         ‰	| �  «        || _        |j                  r£t	        | dg«       t        |di «      }|€i n|j                  «       }|j                  dd«      }|j                  d|j                  «      }|j                  r|j                  dd«      |d<   t        |j                  f|j                  d||d	œ|¤Ž}nt        |«      }t        j                   «       5  t#        |«       d d d «       || _        |j                  r$| j$                  j&                  j)                  «       n| j$                  j(                  | _        d }|j                  �|j                  }n.|j,                  �|j,                  j.                  }nt1        d
«      ‚d|v rp| j$                  j3                  «       D ]R  \  }}|j                  r!d|vsŒd|vsŒd|vsŒ!|j5                  d«       Œ3d|vsŒ8d|vsŒ=d|vsŒB|j5                  d«       ŒT y y # 1 sw Y   �ŒxY w)NÚtimmÚbackbone_kwargsÚout_indices)r   é   r   é   Úin_chansÚoutput_strideé   T)Ú
pretrainedÚfeatures_onlyry   r|   zGEither `backbone` or `backbone_config` should be provided in the configÚresnetÚlayer2Úlayer3Úlayer4Fzstage.1zstage.2zstage.3)rE   rF   ÚconfigÚuse_timm_backboner   ÚgetattrÚcopyÚpopÚnum_channelsÚdilationÚgetr   ÚbackboneÚuse_pretrained_backboner   r%   Úno_gradro   rp   Úfeature_infoÚchannelsÚintermediate_channel_sizesÚbackbone_configÚ
model_typeÚ
ValueErrorÚnamed_parametersÚrequires_grad_)
rJ   r…   Úkwargsry   rŠ   r�   Úbackbone_model_typerq   Ú	parameterrL   s
            €r*   rF   zDetrConvEncoder.__init__G  sù  ø€ Ü‰ÑÔàˆŒð ×#Ò#ô ˜d V HÔ-Ü˜VÐ%6¸Ó;ˆFØ!˜>‘R¨v¯{©{«}ˆFØ Ÿ*™* ]°LÓAˆKØ!Ÿ:™: j°&×2EÑ2EÓFˆLØ�ŠØ*0¯*©*°_ÀbÓ*I��Ñ'Ü#Ø—‘ðà!×9Ñ9Ø"Ø'Ø%ñð ñ‰Hô % VÓ,ˆHô �]‰]‹_ñ 	)Ü˜xÔ(÷	)àˆŒ
à28×2JÒ2JˆD�J‰J×#Ñ#×,Ñ,Ô.ÐPT×PZÑPZ×PcÑPcð 	Ô'ð #ÐØ�?‰?Ð&Ø"(§/¡/ÑØ×#Ñ#Ð/Ø"(×"8Ñ"8×"CÑ"CÑäÐfÓgÐgàÐ*Ñ*Ø#'§:¡:×#>Ñ#>Ó#@ò 8‘��iØ×+Ò+Ø tÒ+°ÀÒ0DÈÐY]ÒI]Ø!×0Ñ0°Õ7à ¨Ò,°À$Ò1FÈ9Ð\`ÒK`Ø!×0Ñ0°Õ7ñ8ð +÷	)ñ 	)ús   Ã%H	È	HÚpixel_valuesÚ
pixel_maskc                 ó€  — | j                   j                  r| j                  |«      n| j                  |«      j                  }g }|D ]t  }t        j
                  j                  |d    j                  «       |j                  dd  ¬«      j                  t        j                  «      d   }|j                  ||f«       Œv |S )Néþÿÿÿ)Úsizer   )r…   r†   rp   Úfeature_mapsr
   Ú
functionalÚinterpolateÚfloatÚshapeÚtor%   ÚboolÚappend)rJ   r›   rœ   ÚfeaturesÚoutÚfeature_mapÚmasks          r*   r_   zDetrConvEncoder.forward{  s«   € à/3¯{©{×/LÒ/L�4—:‘:˜lÔ+ÐRV×R\ÑR\Ð]iÓRj×RwÑRwˆàˆØ#ò 	,ˆKä—=‘=×,Ñ,¨Z¸Ñ-=×-CÑ-CÓ-EÈK×L]ÑL]Ð^`Ð^aÐLbÐ,Óc×fÑfÔgl×gqÑgqÓrÐstÑuˆDØ�J‰J˜ TÐ*Õ+ð	,ð ˆ
r)   )	r!   r"   r#   r$   rF   r%   r	   r_   r`   ra   s   @r*   ru   ru   ?  s)   ø„ ñô28ðh	 E§L¡Lð 	¸e¿l¹l÷ 	r)   ru   c                   ó(   ‡ — e Zd ZdZˆ fd„Zd„ Zˆ xZS )ÚDetrConvModelzp
    This module adds 2D position embeddings to all intermediate feature maps of the convolutional encoder.
    c                 ó>   •— t         ‰| �  «        || _        || _        y ©N)rE   rF   Úconv_encoderÚposition_embedding)rJ   r°   r±   rL   s      €r*   rF   zDetrConvModel.__init__Œ  s   ø€ Ü‰ÑÔØ(ˆÔØ"4ˆÕr)   c                 óº   — | j                  ||«      }g }|D ]?  \  }}|j                  | j                  ||«      j                  |j                  «      «       ŒA ||fS r¯   )r°   r§   r±   r¥   Údtype)rJ   r›   rœ   r©   Úposrª   r«   s          r*   r_   zDetrConvModel.forward‘  sd   € à×Ñ ¨jÓ9ˆØˆØ!$ò 	YÑˆK˜à�J‰J�t×.Ñ.¨{¸DÓA×DÑDÀ[×EVÑEVÓWÕXð	Yð �Cˆxˆr)   ©r!   r"   r#   r$   rF   r_   r`   ra   s   @r*   r­   r­   ‡  s   ø„ ñô5ö
r)   r­   c                   ó*   ‡ — e Zd ZdZdˆ fd„	Zd„ Zˆ xZS )ÚDetrSinePositionEmbeddingz¬
    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 passedrz   )	rE   rF   Úembedding_dimÚtemperatureÚ	normalizer•   ÚmathÚpir^   )rJ   r¹   rº   r»   r^   rL   s        €r*   rF   z"DetrSinePositionEmbedding.__init__¢  sW   ø€ Ü‰ÑÔØ*ˆÔØ&ˆÔØ"ˆŒØÐ ¨eÑ!3ÜÐJÓKÐKØˆ=ØœŸ™‘KˆEØˆ�
r)   c           
      óh  — |€t        d«      ‚|j                  dt        j                  ¬«      }|j                  dt        j                  ¬«      }| j                  rB||d d …dd …d d …f   dz   z  | j
                  z  }||d d …d d …dd …f   d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³   rz   rY   g�íµ ÷Æ°>)r³   rh   Úfloor)Úrounding_moder   r{   ©Údimr   )r•   Úcumsumr%   Úfloat32r»   r^   Úaranger¹   Úint64rh   r£   rº   ÚdivÚstackÚsinÚcosÚflattenÚcatÚpermute)	rJ   r›   rœ   Úy_embedÚx_embedÚdim_tÚpos_xÚpos_yr´   s	            r*   r_   z!DetrSinePositionEmbedding.forward­  sü  € ØÐÜÐ5Ó6Ð6Ø×#Ñ# A¬U¯]©]Ð#Ó;ˆØ×#Ñ# A¬U¯]©]Ð#Ó;ˆØ�>Š>Ø ª¨B©C²¨Ñ!3°dÑ!:Ñ;¸d¿j¹jÑHˆGØ ªªA¨r©s¨Ñ!3°dÑ!:Ñ;¸d¿j¹jÑHˆ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ˆØˆ
r)   )é@   i'  FNrµ   ra   s   @r*   r·   r·   œ  s   ø„ ñõ
	ör)   r·   c                   ó,   ‡ — e Zd ZdZdˆ fd„	Zdd„Zˆ xZS )ÚDetrLearnedPositionEmbeddingzN
    This module learns positional embeddings up to a fixed maximum size.
    c                 óŽ   •— t         ‰| �  «        t        j                  d|«      | _        t        j                  d|«      | _        y )Né2   )rE   rF   r
   Ú	EmbeddingÚrow_embeddingsÚcolumn_embeddings)rJ   r¹   rL   s     €r*   rF   z%DetrLearnedPositionEmbedding.__init__Æ  s4   ø€ Ü‰ÑÔÜ Ÿl™l¨2¨}Ó=ˆÔÜ!#§¡¨b°-Ó!@ˆÕr)   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ž   ©rh   r   r   rY   rÁ   rz   )
r¤   r%   rÅ   rh   rÚ   rÙ   rÌ   Ú	unsqueezeÚrepeatrÍ   )
rJ   r›   rœ   ÚheightÚwidthÚwidth_valuesÚheight_valuesÚx_embÚy_embr´   s
             r*   r_   z$DetrLearnedPositionEmbedding.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ˆØˆ
r)   )é   r¯   rµ   ra   s   @r*   rÕ   rÕ   Á  s   ø„ ñõA÷

r)   rÕ   c                 óÄ   — | j                   dz  }| j                  dk(  rt        |d¬«      }|S | j                  dk(  rt        |«      }|S t	        d| j                  › �«      ‚)Nrz   ÚsineT)r»   ÚlearnedzNot supported )Úd_modelÚposition_embedding_typer·   rÕ   r•   )r…   Ún_stepsr±   s      r*   Úbuild_position_encodingrì   Ø  sq   € Ø�n‰n Ñ!€GØ×%Ñ%¨Ò/ä6°wÈ$ÔOÐð Ðð 
×	'Ñ	'¨9Ò	4Ü9¸'ÓBÐð Ðô ˜>¨&×*HÑ*HÐ)IÐJÓKÐKr)   c                   ó’  ‡ — 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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 )ÚDetrAttentionz¨
    Multi-headed attention from 'Attention Is All You Need' paper.

    Here, we add position embeddings to the queries and keys (as explained in the DETR paper).
    Ú	embed_dimÚ	num_headsÚdropoutrB   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).ç      à¿©rB   )rE   rF   rï   rð   rñ   Úhead_dimr•   Úscalingr
   ÚLinearÚk_projÚv_projÚq_projÚout_proj)rJ   rï   rð   rñ   rB   rL   s        €r*   rF   zDetrAttention.__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ˆ�r)   ÚtensorÚseq_lenÚ
batch_sizec                 óŽ   — |j                  ||| j                  | j                  «      j                  dd«      j	                  «       S )Nr   rz   )Úviewrð   rõ   Ú	transposeÚ
contiguous)rJ   rü   rý   rþ   s       r*   Ú_shapezDetrAttention._shape  s7   € Ø�{‰{˜: w°·±ÀÇÁÓN×XÑXÐYZÐ\]Ó^×iÑiÓkÐkr)   Úobject_queriesc                 ó   — |€|S ||z   S r¯   r(   )rJ   rü   r  s      r*   Úwith_pos_embedzDetrAttention.with_pos_embed  s   € Ø'Ð/ˆvÐL°V¸nÑ5LÐLr)   Úhidden_statesÚattention_maskÚkey_value_statesÚspatial_position_embeddingsÚoutput_attentionsÚreturnc                 óˆ  — |du}|j                  «       \  }}	}
|�|}| j                  ||«      }|�|}| j                  ||«      }| j                  |«      | j                  z  }|rE| j	                  | j                  |«      d|«      }| j	                  | j                  «      d|«      }nD| 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                  «       › �«      ‚|�{|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 ChannelNrY   r   rz   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Ÿ   r  rú   rö   r  rø   rù   rð   rõ   r   r%   Úbmmr  r•   r
   r¡   Úsoftmaxrñ   r  rZ   rû   )rJ   r  r  r  r	  r
  r  Úis_cross_attentionrþ   Ú
target_lenrï   Úhidden_states_originalÚkey_value_states_originalÚquery_statesÚ
key_statesÚvalue_statesÚ
proj_shapeÚ
source_lenÚattn_weightsÚattn_weights_reshapedÚ
attn_probsÚattn_outputs                         r*   r_   zDetrAttention.forward
  sØ  € ð .°TÐ9ÐØ,9×,>Ñ,>Ó,@Ñ)ˆ
�J 	ð Ð%Ø%2Ð"Ø ×/Ñ/°¸~ÓNˆMð 'Ð2Ø(8Ð%Ø#×2Ñ2Ð3CÐE`ÓaÐð —{‘{ =Ó1°D·L±LÑ@ˆáàŸ™ T§[¡[Ð1AÓ%BÀBÈ
ÓSˆJØŸ;™; t§{¡{Ð3LÓ'MÈrÐS]Ó^‰Lð Ÿ™ T§[¡[°Ó%?ÀÀZÓPˆJØŸ;™; t§{¡{Ð3IÓ'JÈBÐPZÓ[ˆLà  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Ø ×%Ñ%Ó'Ð(ð*óð ð
 Ð%Ø×"Ñ"Ó$¨°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Ð1r)   )ç        T)NNNNF)r!   r"   r#   r$   Úintr£   r¦   rF   r%   r	   r  r   r  r   r_   r`   ra   s   @r*   rî   rî   å  s2  ø„ ñð ØñCàðCð ðCð ð	Cð
 õCð0l˜UŸ\™\ð l°Cð lÀSó lðM U§\¡\ð MÀ8ÈFÑCSó Mð 26Ø15Ø37Ø>BØ"'ñY2à—|‘|ðY2ð ! §¡Ñ.ðY2ð ! §¡Ñ.ð	Y2ð
 # 5§<¡<Ñ0ðY2ð &.¨e¯l©lÑ%;ðY2ð  ðY2ð 
ˆu�|‰|˜X e§l¡lÑ3°X¸eÀEÇLÁLÑ>QÑ5RÐRÑ	S÷Y2r)   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 )	ÚDetrEncoderLayerr…   c                 óf  •— t         ‰| �  «        |j                  | _        t	        | j                  |j
                  |j                  ¬«      | _        t        j                  | j                  «      | _
        |j                  | _        t        |j                     | _        |j                  | _        t        j                   | j                  |j"                  «      | _        t        j                   |j"                  | j                  «      | _        t        j                  | j                  «      | _        y )N©rï   rð   rñ   )rE   rF   ré   rï   rî   Úencoder_attention_headsÚattention_dropoutÚ	self_attnr
   Ú	LayerNormÚself_attn_layer_normrñ   r   Úactivation_functionÚactivation_fnÚactivation_dropoutr÷   Úencoder_ffn_dimÚfc1Úfc2Úfinal_layer_norm©rJ   r…   rL   s     €r*   rF   zDetrEncoderLayer.__init__g  sÎ   ø€ Ü‰ÑÔØŸ™ˆŒÜ&Ø—n‘nØ×4Ñ4Ø×,Ñ,ô
ˆŒô
 %'§L¡L°·±Ó$@ˆÔ!Ø—~‘~ˆŒÜ# F×$>Ñ$>Ñ?ˆÔØ"(×";Ñ";ˆÔÜ—9‘9˜TŸ^™^¨V×-CÑ-CÓDˆŒÜ—9‘9˜V×3Ñ3°T·^±^ÓDˆŒÜ "§¡¨T¯^©^Ó <ˆÕr)   r  r  r  r  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`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
                values.
            object_queries (`torch.FloatTensor`, *optional*):
                Object queries (also called content embeddings), to be added to the hidden states.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
        )r  r  r  r  r  iè  )ÚminÚmax)r(  r
   r¡   rñ   r  r*  r,  r/  r-  r0  r1  r%   ÚisinfÚanyÚisnanÚfinfor³   r5  Úclamp)	rJ   r  r  r  r  Úresidualr  Úclamp_valueÚoutputss	            r*   r_   zDetrEncoderLayer.forwardw  sƒ  € ð& !ˆØ&*§n¡nØ'Ø)Ø)Ø/ð	 '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àˆr)   ©NF©r!   r"   r#   r   rF   r%   r	   r   r¦   r_   r`   ra   s   @r*   r#  r#  f  sS   ø„ ð=˜zõ =ð( 26Ø"'ñ3à—|‘|ð3ð Ÿ™ð3ð ! §¡Ñ.ð	3ð
  ÷3r)   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j                     deej                     d	ee   fd
„Z	ˆ xZ
S )ÚDetrDecoderLayerr…   c                 ó  •— t         ‰| �  «        |j                  | _        t	        | j                  |j
                  |j                  ¬«      | _        |j                  | _        t        |j                     | _        |j                  | _        t        j                  | j                  «      | _        t	        | j                  |j
                  |j                  ¬«      | _        t        j                  | j                  «      | _        t        j$                  | j                  |j&                  «      | _        t        j$                  |j&                  | j                  «      | _        t        j                  | j                  «      | _        y )Nr%  )rñ   )rE   rF   ré   rï   rî   Údecoder_attention_headsr'  r(  rñ   r   r+  r,  r-  r
   r)  r*  Úencoder_attnÚencoder_attn_layer_normr÷   Údecoder_ffn_dimr/  r0  r1  r2  s     €r*   rF   zDetrDecoderLayer.__init__®  s  ø€ Ü‰ÑÔØŸ™ˆŒä&Ø—n‘nØ×4Ñ4Ø×,Ñ,ô
ˆŒð
 —~‘~ˆŒÜ# F×$>Ñ$>Ñ?ˆÔØ"(×";Ñ";ˆÔä$&§L¡L°·±Ó$@ˆÔ!Ü)Ø�N‰NØ×*Ñ*Ø×,Ñ,ô
ˆÔô
 (*§|¡|°D·N±NÓ'CˆÔ$Ü—9‘9˜TŸ^™^¨V×-CÑ-CÓDˆŒÜ—9‘9˜V×3Ñ3°T·^±^ÓDˆŒÜ "§¡¨T¯^©^Ó <ˆÕr)   r  r  r  Úquery_position_embeddingsr9   Úencoder_attention_maskr  c                 ó,  — |}| j                  ||||¬«      \  }}	t        j                  j                  || j                  | j                  ¬«      }||z   }| j                  |«      }d}
|�h|}| 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)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
                values.
            object_queries (`torch.FloatTensor`, *optional*):
                object_queries that are added to the hidden states
            in the cross-attention layer.
            query_position_embeddings (`torch.FloatTensor`, *optional*):
                position embeddings that are added to the queries and keys
            in the self-attention layer.
            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.
        )r  r  r  r  r  N)r  r  r	  r  r
  r  )r(  r
   r¡   rñ   r  r*  rD  rE  r,  r/  r-  r0  r1  )rJ   r  r  r  rG  r9   rH  r  r;  Úself_attn_weightsÚcross_attn_weightsr=  s               r*   r_   zDetrDecoderLayer.forwardÆ  s¬  € ð> !ˆð ,0¯>©>Ø'Ø4Ø)Ø/ð	 ,:ó ,
Ñ(ˆÐ(ô Ÿ™×-Ñ-¨m¸t¿|¹|ÐVZ×VcÑVcÐ-ÓdˆØ  =Ñ0ˆØ×1Ñ1°-Ó@ˆð "ÐØ Ð,Ø$ˆHà04×0AÑ0AØ+Ø8Ø!6Ø5Ø,:Ø"3ð 1Bó 1Ñ-ˆMÐ-ô ŸM™M×1Ñ1°-À4Ç<Á<ÐZ^×ZgÑZgÐ1ÓhˆMØ$ }Ñ4ˆMØ ×8Ñ8¸ÓGˆMð !ˆØ×*Ñ*¨4¯8©8°MÓ+BÓCˆÜŸ™×-Ñ-¨m¸t×?VÑ?VÐae×anÑanÐ-ÓoˆØŸ™ Ó/ˆÜŸ™×-Ñ-¨m¸t¿|¹|ÐVZ×VcÑVcÐ-ÓdˆØ  =Ñ0ˆØ×-Ñ-¨mÓ<ˆà Ð"ˆáØÐ)Ð+=Ð>Ñ>ˆGàˆr)   )NNNNNFr?  ra   s   @r*   rA  rA  ­  s©   ø„ ð=˜zõ =ð6 26Ø15Ø<@Ø8<Ø9=Ø,1ñMà—|‘|ðMð ! §¡Ñ.ðMð ! §¡Ñ.ð	Mð
 $,¨E¯L©LÑ#9ðMð  (¨¯©Ñ5ðMð !)¨¯©Ñ 6ðMð $ D™>÷Mr)   rA  c                   ó&   — e Zd ZeZdZdZg d¢Zd„ Zy)ÚDetrPreTrainedModelrp   r›   )ru   r#  rA  c                 ó.  — | j                   j                  }| j                   j                  }t        |t        «      rÑt
        j                  j                  |j                  j                  «       t
        j                  j                  |j                  j                  «       t
        j                  j                  |j                  j                  |¬«       t
        j                  j                  |j                  j                  |¬«       nvt        |t        «      rft
        j                  j                  |j                  j                  «       t
        j                  j                  |j                   j                  «       t        |t
        j"                  t
        j$                  t
        j&                  f«      rY|j                  j(                  j+                  d|¬«       |j                  �%|j                  j(                  j-                  «        y y t        |t
        j.                  «      rf|j                  j(                  j+                  d|¬«       |j0                  �2|j                  j(                  |j0                     j-                  «        y y y )N)Úgainr   )ÚmeanÚstd)r…   Úinit_stdÚinit_xavier_stdre   ÚDetrMHAttentionMapr
   ÚinitÚzeros_Úk_linearrB   Úq_linearÚxavier_uniform_rA   rÕ   Úuniform_rÙ   rÚ   r÷   ÚConv2drf   ri   Únormal_Úzero_rØ   Úpadding_idx)rJ   rr   rQ  Ú
xavier_stds       r*   Ú_init_weightsz!DetrPreTrainedModel._init_weights  s«  € Ø�k‰k×"Ñ"ˆØ—[‘[×0Ñ0ˆ
ä�fÔ0Ô1Ü�G‰G�N‰N˜6Ÿ?™?×/Ñ/Ô0Ü�G‰G�N‰N˜6Ÿ?™?×/Ñ/Ô0Ü�G‰G×#Ñ# F§O¡O×$:Ñ$:ÀÐ#ÔLÜ�G‰G×#Ñ# F§O¡O×$:Ñ$:ÀÐ#ÕLÜ˜Ô <Ô=Ü�G‰G×Ñ˜V×2Ñ2×9Ñ9Ô:Ü�G‰G×Ñ˜V×5Ñ5×<Ñ<Ô=Ü�fœrŸy™y¬"¯)©)´R·^±^ÐDÔEð �M‰M×Ñ×&Ñ&¨C°SÐ&Ô9Ø�{‰{Ð&Ø—‘× Ñ ×&Ñ&Õ(ð 'ä˜¤§¡Ô-Ø�M‰M×Ñ×&Ñ&¨C°SÐ&Ô9Ø×!Ñ!Ð-Ø—‘×"Ñ" 6×#5Ñ#5Ñ6×<Ñ<Õ>ð .ð .r)   N)	r!   r"   r#   r   Úconfig_classÚbase_model_prefixÚmain_input_nameÚ_no_split_modulesr`  r(   r)   r*   rM  rM    s   „ Ø€LØÐØ$€OÚVÐó?r)   rM  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 ([`DetrConfig`]):
            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.
a`	  
    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 [`DetrImageProcessor.__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 [`~utils.ModelOutput`] instead of a plain tuple.
c                   ó<   ‡ — e Zd ZdZdefˆ fd„Z	 	 	 	 	 	 dd„Zˆ xZS )ÚDetrEncoderaU  
    Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
    [`DetrEncoderLayer`].

    The encoder updates the flattened feature map through multiple self-attention layers.

    Small tweak for DETR:

    - object_queries are added to the forward pass.

    Args:
        config: DetrConfig
    r…   c                 ó  •— t         ‰| �  |«       |j                  | _        |j                  | _        t        j                  t        |j                  «      D �cg c]  }t        |«      ‘Œ c}«      | _
        | j                  «        y c c}w r¯   )rE   rF   rñ   Úencoder_layerdropÚ	layerdropr
   Ú
ModuleListÚrangeÚencoder_layersr#  ÚlayersÚ	post_init©rJ   r…   Ú_rL   s      €r*   rF   zDetrEncoder.__init__y  sf   ø€ Ü‰Ñ˜Ô à—~‘~ˆŒØ×1Ñ1ˆŒä—m‘mÄuÈV×MbÑMbÓGcÖ$dÀ!Ô%5°fÕ%=Ò$dÓeˆŒð
 	�‰Õùò %es   ÁBc                 ó¦  — |�|n| j                   j                  }|�|n| j                   j                  }|�|n| j                   j                  }|}t        j
                  j                  || j                  | j                  ¬«      }|�t        ||j                  «      }|rdnd}|rdnd}	t        | j                  «      D ]c  \  }
}|r||fz   }d}| j                  r&t        j                  g «      }|| j                  k  rd}|rd}n |||||¬«      }|d   }|sŒ[|	|d	   fz   }	Œe |r||fz   }|st        d
„ |||	fD «       «      S t!        |||	¬«      S )a•  
        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)

            object_queries (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
                Object queries that are added to the queries in each self-attention layer.

            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 [`~utils.ModelOutput`] instead of a plain tuple.
        Nr  r(   FT©NN)r  r  r   r   c              3   ó&   K  — | ]	  }|€Œ|–— Œ y ­wr¯   r(   ©Ú.0Úvs     r*   ú	<genexpr>z&DetrEncoder.forward.<locals>.<genexpr>Ö  s   è ø€ Òe˜qÐWXÑWdœÑeùs   ‚Š©r4   r  Ú
attentions)r…   r  Úoutput_hidden_statesÚuse_return_dictr
   r¡   rñ   r  r   r³   Ú	enumeraterm  r%   Úrandri  Útupler   )rJ   Úinputs_embedsr  r  r  rz  Úreturn_dictr  Úencoder_statesÚall_attentionsÚiÚencoder_layerÚto_dropÚdropout_probabilityÚlayer_outputss                  r*   r_   zDetrEncoder.forward†  s‡  € ðD 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆà%ˆÜŸ™×-Ñ-¨m¸t¿|¹|ÐVZ×VcÑVcÐ-Ódˆð Ð%ä7¸È×H[ÑH[Ó\ˆNá3™¸ˆÙ0™°dˆÜ )¨$¯+©+Ó 6ò 	FÑˆAˆ}Ù#Ø!/°=Ð2BÑ!B�àˆGØ�}Š}Ü&+§j¡j°£nÐ#Ø&¨¯©Ò7Ø"�GáØ ,‘ñ !.Ø!Ø"Ø#1Ø&7ô	!�ð !.¨aÑ 0�â Ø!/°=ÀÑ3CÐ2EÑ!E‘ð1	Fñ4  Ø+¨}Ð.>Ñ>ˆNáÜÑe ]°NÀNÐ$SÔeÓeÐeÜØ+¸>ÐVdô
ð 	
r)   )NNNNNN©r!   r"   r#   r$   r   rF   r_   r`   ra   s   @r*   rf  rf  j  s.   ø„ ñð˜zõ ð ØØØØ!Ø÷S
r)   rf  c                   óB   ‡ — e Zd ZdZdefˆ fd„Z	 	 	 	 	 	 	 	 	 dd„Zˆ xZS )ÚDetrDecoderaç  
    Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`DetrDecoderLayer`].

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

    Some small tweaks for DETR:

    - object_queries and query_position_embeddings are added to the forward pass.
    - if self.config.auxiliary_loss is set to True, also returns a stack of activations from all decoding layers.

    Args:
        config: DetrConfig
    r…   c                 óp  •— t         ‰| �  |«       |j                  | _        |j                  | _        t        j                  t        |j                  «      D �cg c]  }t        |«      ‘Œ c}«      | _
        t        j                  |j                  «      | _        d| _        | j                  «        y c c}w r>  )rE   rF   rñ   Údecoder_layerdropri  r
   rj  rk  Údecoder_layersrA  rm  r)  ré   Ú	layernormÚgradient_checkpointingrn  ro  s      €r*   rF   zDetrDecoder.__init__ë  s€   ø€ Ü‰Ñ˜Ô Ø—~‘~ˆŒØ×1Ñ1ˆŒä—m‘mÄuÈV×MbÑMbÓGcÖ$dÀ!Ô%5°fÕ%=Ò$dÓeˆŒäŸ™ f§n¡nÓ5ˆŒà&+ˆÔ#à�‰Õùò %es   ÁB3c
           
      óX  — |�|n| j                   j                  }|�|n| j                   j                  }|	�|	n| j                   j                  }	|�|}
|j	                  «       dd }d}|� |�|t        ||j                  d   ¬«      z   }|�|�t        ||j                  d   ¬«      }| j                   j                  rdnd}|rdnd}|rdnd}|r|�dnd}t        | j                  «      D ]Ð  \  }}|r|
fz  }| j                  r%t        j                  g «      }|| j                  k  rŒ?| j                  r-| j                  r!| j                  |j                   
|||d«      }n |
||||||¬«      }|d   }
| j                   j                  r| j#                  |
«      }
||
fz  }|sŒ¼||d   fz  }|€ŒÈ||d   fz  }ŒÒ | j#                  
«      }
|r||
fz  }| j                   j                  rt        j$                  |«      }|	st'        d	„ |
||||fD «       «      S t)        |
||||¬
«      S )aá  
        Args:
            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
                The query embeddings that are passed into the decoder.

            attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on certain queries. Mask values selected in `[0, 1]`:

                - 1 for queries that are **not masked**,
                - 0 for queries that are **masked**.

                [What are attention masks?](../glossary#attention-mask)
            encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_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, encoder_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**).

            object_queries (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
                Object queries that are added to the queries and keys in each cross-attention layer.
            query_position_embeddings (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
                , *optional*): Position embeddings that are added to the values and keys in each self-attention layer.

            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 [`~utils.ModelOutput`] instead of a plain tuple.
        NrY   )Útgt_lenr(   )r  r  rG  r9   rH  r  r   r   rz   c              3   ó$   K  — | ]  }|�|–— Œ
 y ­wr¯   r(   rt  s     r*   rw  z&DetrDecoder.forward.<locals>.<genexpr>~  s   è ø€ ò àØ�=ô ñùs   ‚)r4   r  ry  r7   r   )r…   r  rz  r{  rŸ   r   r³   Úauxiliary_lossr|  rm  r  r%   r}  ri  r�  Ú_gradient_checkpointing_funcÚ__call__rŽ  rÈ   r~  r   )rJ   r  r  r9   rH  r  rG  r  rz  r€  r  Úinput_shapeÚcombined_attention_maskÚintermediateÚall_hidden_statesÚall_self_attnsÚall_cross_attentionsÚidxÚdecoder_layerr†  r‡  s                        r*   r_   zDetrDecoder.forwardø  s©  € ð` 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆàÐ$Ø)ˆMØ'×,Ñ,Ó.¨s°Ð3ˆKà"&ÐàÐ%Ð*AÐ*Mà&=Ô@ZØ × 3Ñ 3¸[È¹_ôAñ 'Ð#ð
 !Ð,Ð1GÐ1Sä%?Ø&¨×(;Ñ(;À[ÐQSÁ_ô&Ð"ð
 "Ÿ[™[×7Ò7‘r¸Tˆñ #7™B¸DÐÙ0™°dˆÙ&7Ð<QÐ<]™rÐdhÐä"+¨D¯K©KÓ"8ò '	@ÑˆC�á#Ø! mÐ%5Ñ5Ð!Ø�}Š}Ü&+§j¡j°£nÐ#Ø&¨¯©Ò7Øà×*Ò*¨t¯}ª}Ø $× AÑ AØ!×*Ñ*Ø!Ø+Ø)Ø*Øó!‘ñ !.Ø!Ø#:Ø#1Ø.GØ*?Ø+AØ&7ô!�ð *¨!Ñ,ˆMà�{‰{×)Ò)Ø $§¡¨}Ó =�Ø Ð 0Ñ0�â Ø =°Ñ#3Ð"5Ñ5�à(Ñ4Ø(¨]¸1Ñ-=Ð,?Ñ?Ñ(ðO'	@ðT Ÿ™ }Ó5ˆñ  Ø -Ð!1Ñ1Ðð �;‰;×%Ò%Ü Ÿ;™; |Ó4ˆLáÜñ à'Ð):¸NÐL`ÐbnÐoôó ð ô
 !Ø+Ø+Ø%Ø1Ø'3ô
ð 	
r)   ©	NNNNNNNNNrˆ  ra   s   @r*   rŠ  rŠ  Ü  s7   ø„ ñð˜zõ ð ØØ"Ø#ØØ"&ØØ!Ø÷Q
r)   rŠ  z›
    The bare DETR Model (consisting of a backbone and encoder-decoder Transformer) outputting raw hidden-states without
    any specific head on top.
    c                   óz  ‡ — e Zd Zdefˆ fd„Zd„ Z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 )Ú	DetrModelr…   c                 ó˜  •— t         ‰| �  |«       t        |«      }t        |«      }t	        ||«      | _        t        j                  |j                  d   |j                  d¬«      | _
        t        j                  |j                  |j                  «      | _        t        |«      | _        t!        |«      | _        | j%                  «        y )NrY   r   )Úkernel_size)rE   rF   ru   rì   r­   r�   r
   r[  r’   ré   Úinput_projectionrØ   Únum_queriesrG  rf  ÚencoderrŠ  Údecoderrn  )rJ   r…   r�   r  rL   s       €r*   rF   zDetrModel.__init__”  sŸ   ø€ Ü‰Ñ˜Ô ô # 6Ó*ˆÜ0°Ó8ˆÜ% h°Ó?ˆŒô !#§	¡	¨(×*MÑ*MÈbÑ*QÐSY×SaÑSaÐopÔ qˆÔä)+¯©°f×6HÑ6HÈ&Ï.É.Ó)YˆÔ&ä" 6Ó*ˆŒÜ" 6Ó*ˆŒð 	�‰Õr)   c                 ó   — | j                   S r¯   )r¥  ©rJ   s    r*   Úget_encoderzDetrModel.get_encoder§  ó   € Ø�|‰|Ðr)   c                 ó   — | j                   S r¯   )r¦  r¨  s    r*   Úget_decoderzDetrModel.get_decoderª  rª  r)   c                 ó’   — | j                   j                  j                  j                  «       D ]  \  }}|j	                  d«       Œ y r>  ©r�   r°   rp   r–   r—   ©rJ   rq   Úparams      r*   Úfreeze_backbonezDetrModel.freeze_backbone­  s<   € ØŸ=™=×5Ñ5×;Ñ;×LÑLÓNò 	(‰KˆD�%Ø× Ñ  Õ'ñ	(r)   c                 ó’   — | j                   j                  j                  j                  «       D ]  \  }}|j	                  d«       Œ y )NTr®  r¯  s      r*   Úunfreeze_backbonezDetrModel.unfreeze_backbone±  s<   € ØŸ=™=×5Ñ5×;Ñ;×LÑLÓNò 	'‰KˆD�%Ø× Ñ  Õ&ñ	'r)   ©Úoutput_typera  r›   rœ   Údecoder_attention_maskÚencoder_outputsr  Údecoder_inputs_embedsr  rz  r€  r  c
                 ó   — |�|n| j                   j                  }|�|n| j                   j                  }|	�|	n| j                   j                  }	|j                  \  }
}}}|j
                  }|€t        j                  |
||f|¬«      }| j                  ||«      \  }}|d   \  }}|€t        d«      ‚| j                  |«      }|j                  d«      j                  ddd«      }|d   j                  d«      j                  ddd«      }|j                  d«      }|€| j                  ||||||	¬«      }nI|	rGt        |t        «      s7t        |d   t!        |«      dkD  r|d   ndt!        |«      dkD  r|d   nd¬	«      }| j"                  j$                  j'                  d«      j)                  |
dd«      }t        j*                  |«      }| j-                  |d|||d   ||||	¬
«	      }|	s||z   S t/        |j0                  |j2                  |j4                  |j6                  |j0                  |j2                  |j4                  |j8                  ¬«      S )aÒ  
        Returns:

        Examples:

        ```python
        >>> from transformers import AutoImageProcessor, DetrModel
        >>> 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("facebook/detr-resnet-50")
        >>> model = DetrModel.from_pretrained("facebook/detr-resnet-50")

        >>> # prepare image for the model
        >>> inputs = image_processor(images=image, return_tensors="pt")

        >>> # forward pass
        >>> outputs = model(**inputs)

        >>> # the last hidden states are the final query embeddings of the Transformer decoder
        >>> # these are of shape (batch_size, num_queries, hidden_size)
        >>> last_hidden_states = outputs.last_hidden_state
        >>> list(last_hidden_states.shape)
        [1, 100, 256]
        ```NrÜ   rY   z/Backbone does not return downsampled pixel maskrz   r   r   ©r  r  r  r  rz  r€  rx  ©	r  r  r  rG  r9   rH  r  rz  r€  )r4   r5   r6   r7   r8   r9   r:   r   )r…   r  rz  r{  r¤   rh   r%   rH   r�   r•   r£  rË   rÍ   r¥  re   r   rl   rG  rA   rÝ   rÞ   Ú
zeros_liker¦  r,   r4   r  ry  r7   r   )rJ   r›   rœ   r¶  r·  r  r¸  r  rz  r€  rþ   rŠ   rß   rà   rh   r¨   Úobject_queries_listrª   r«   Úprojected_feature_mapÚflattened_featuresr  Úflattened_maskrG  ÚqueriesÚdecoder_outputss                             r*   r_   zDetrModel.forwardµ  s…  € ðT 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆà2>×2DÑ2DÑ/ˆ
�L &¨%Ø×$Ñ$ˆàÐÜŸ™ j°&¸%Ð%@È&ÔQˆJð
 )-¯©°lÀJÓ(OÑ%ˆÐ%ð % R™LÑˆ�Tàˆ<ÜÐNÓOÐOð !%× 5Ñ 5°kÓ BÐð 3×:Ñ:¸1Ó=×EÑEÀaÈÈAÓNÐØ,¨RÑ0×8Ñ8¸Ó;×CÑCÀAÀqÈ!ÓLˆàŸ™ a›ˆð
 Ð"Ø"Ÿl™lØ0Ø-Ø-Ø"3Ø%9Ø'ð +ó ‰Oñ ¤¨O¼_Ô!MÜ-Ø"1°!Ñ"4Ü47¸Ó4HÈ1Ò4L˜o¨aÒ0ÐRVÜ14°_Ó1EÈÒ1I˜?¨1Ò-ÈtôˆOð %)×$BÑ$B×$IÑ$I×$SÑ$SÐTUÓ$V×$]Ñ$]Ð^hÐjkÐmnÓ$oÐ!Ü×"Ñ"Ð#<Ó=ˆð Ÿ,™,Ø!ØØ)Ø&?Ø"1°!Ñ"4Ø#1Ø/Ø!5Ø#ð 'ó 

ˆñ Ø" _Ñ4Ð4äØ-×?Ñ?Ø"1×"?Ñ"?Ø.×9Ñ9Ø,×=Ñ=Ø&5×&GÑ&GØ"1×"?Ñ"?Ø.×9Ñ9Ø'6×'QÑ'Qô	
ð 		
r)   )NNNNNNNN)r!   r"   r#   r   rF   r©  r¬  r±  r³  r   ÚDETR_INPUTS_DOCSTRINGr   r,   Ú_CONFIG_FOR_DOCr%   r&   r   Ú
LongTensorr¦   r   r   r_   r`   ra   s   @r*   r   r   Œ  s4  ø„ ð˜zõ ò&òò(ò'ñ +Ð+@ÓAÙ¨?ÈÔYð 26Ø>BØ7;Ø59Ø=AØ,0Ø/3Ø&*ñz
à×'Ñ'ðz
ð ˜U×-Ñ-Ñ.ðz
ð !)¨×):Ñ):Ñ ;ð	z
ð
 " %×"3Ñ"3Ñ4ðz
ð   × 1Ñ 1Ñ2ðz
ð  (¨×(9Ñ(9Ñ:ðz
ð $ D™>ðz
ð ' t™nðz
ð ˜d‘^ðz
ð 
ˆu�U×&Ñ&Ñ'¨Ð8Ñ	9òz
ó Zó Bôz
r)   r   c                   ó(   ‡ — e Zd ZdZˆ fd„Zd„ Zˆ xZS )ÚDetrMLPPredictionHeada  
    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
   r÷   )ru  rK   Úks      r*   rw  z1DetrMLPPredictionHead.__init__.<locals>.<genexpr>B  s   è ø€ Ò#g¹¸¸1¤B§I¡I¨a°§OÑ#gùs   ‚#%)rE   rF   Ú
num_layersr
   rj  Úziprm  )rJ   Ú	input_dimÚ
hidden_dimÚ
output_dimrË  ÚhrL   s         €r*   rF   zDetrMLPPredictionHead.__init__>  sS   ø€ Ü‰ÑÔØ$ˆŒØˆL˜J¨™NÑ+ˆÜ—m‘mÑ#gÄÀYÀKÐRSÁOÐUVÐZdÐYeÑUeÓ@fÔ#gÓgˆ�r)   c                 ó¾   — t        | j                  «      D ]D  \  }}|| j                  dz
  k  r%t        j                  j                   ||«      «      n ||«      }ŒF |S )Nr   )r|  rm  rË  r
   r¡   Úrelu)rJ   r\   rƒ  Úlayers       r*   r_   zDetrMLPPredictionHead.forwardD  sT   € Ü! $§+¡+Ó.ò 	V‰HˆAˆuØ01°D·O±OÀaÑ4GÒ0G”—‘×"Ñ"¡5¨£8Ô,ÉUÐSTËX‰Að	Vàˆr)   rµ   ra   s   @r*   rÇ  rÇ  5  s   ø„ ñôhör)   rÇ  z™
    DETR Model (consisting of a backbone and encoder-decoder Transformer) with object detection heads on top, for tasks
    such as COCO detection.
    c                   ót  ‡ — e Zd Zdefˆ f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 )ÚDetrForObjectDetectionr…   c                 ó  •— t         ‰| �  |«       t        |«      | _        t	        j
                  |j                  |j                  dz   «      | _        t        |j                  |j                  dd¬«      | _
        | j                  «        y )Nr   r{   r   )rÍ  rÎ  rÏ  rË  )rE   rF   r   rp   r
   r÷   ré   Ú
num_labelsÚclass_labels_classifierrÇ  Úbbox_predictorrn  r2  s     €r*   rF   zDetrForObjectDetection.__init__R  sr   ø€ Ü‰Ñ˜Ô ô ˜vÓ&ˆŒ
ô (*§y¡yØ�N‰N˜F×-Ñ-°Ñ1ó(
ˆÔ$ô 4Ø—n‘n°·±ÈAÐZ[ô
ˆÔð
 	�‰Õr)   r´  r›   rœ   r¶  r·  r  r¸  Úlabelsr  rz  r€  r  c                 óú  — |
�|
n| j                   j                  }
| j                  ||||||||	|
¬«	      }|d   }| j                  |«      }| j	                  |«      j                  «       }d\  }}}|��d\  }}| j                   j                  rC|
r|j                  n|d   }| j                  |«      }| j	                  |«      j                  «       }| j                  ||| j                  || j                   ||«      \  }}}|
s|�||f|z   |z   }n||f|z   }|�||f|z   S |S t        ||||||j                  |j                  |j                  |j                  |j                  |j                   |j"                  ¬«      S )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, DetrForObjectDetection
        >>> import torch
        >>> 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("facebook/detr-resnet-50")
        >>> model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")

        >>> 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.9, 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 remote with confidence 0.998 at location [40.16, 70.81, 175.55, 117.98]
        Detected remote with confidence 0.996 at location [333.24, 72.55, 368.33, 187.66]
        Detected couch with confidence 0.995 at location [-0.02, 1.15, 639.73, 473.76]
        Detected cat with confidence 0.999 at location [13.24, 52.05, 314.02, 470.93]
        Detected cat with confidence 0.999 at location [345.4, 23.85, 640.37, 368.72]
        ```)rœ   r¶  r·  r  r¸  r  rz  r€  r   ©NNNrr  r{   )r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   )r…   r{  rp   rØ  rÙ  Úsigmoidr“  r   Úloss_functionrh   r.   r4   r5   r6   r7   r8   r9   r:   )rJ   r›   rœ   r¶  r·  r  r¸  rÚ  r  rz  r€  r=  Úsequence_outputr1   r2   r/   r0   r3   Úoutputs_classÚoutputs_coordr˜  Úoutputs                         r*   r_   zDetrForObjectDetection.forwardc  s¾  € ðv &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆð —*‘*ØØ!Ø#9Ø+Ø'Ø"7Ø/Ø!5Ø#ð ó 

ˆð " !™*ˆð ×-Ñ-¨oÓ>ˆØ×(Ñ(¨Ó9×AÑAÓCˆ
à-=Ñ*ˆˆiÐ*ØÐØ+5Ñ(ˆM˜=Ø�{‰{×)Ò)ÙEP˜w×AÒAÐV]Ð^_ÑV`�Ø $× <Ñ <¸\Ó J�Ø $× 3Ñ 3°LÓ A× IÑ IÓ K�Ø15×1CÑ1CØ˜ §¡¨Z¸¿¹ÀmÐUbó2Ñ.ˆD�)Ð.ñ Ø Ð,Ø  *Ð-Ð0AÑAÀGÑK‘à  *Ð-°Ñ7�Ø37Ð3C�T˜9Ð%¨Ñ.ÐOÈÐOä(ØØØØ!Ø/Ø%×7Ñ7Ø")×"?Ñ"?Ø&×9Ñ9Ø$×5Ñ5Ø&-×&GÑ&GØ")×"?Ñ"?Ø&×9Ñ9ô
ð 	
r)   rž  )r!   r"   r#   r   rF   r   rÃ  r   r.   rÄ  r%   r&   r   rÅ  r   Údictr¦   r   r   r_   r`   ra   s   @r*   rÕ  rÕ  J  s:  ø„ ð˜zõ ñ" +Ð+@ÓAÙÐ+DÐSbÔcð 26Ø>BØ7;Ø59Ø=AØ'+Ø,0Ø/3Ø&*ñm
à×'Ñ'ðm
ð ˜U×-Ñ-Ñ.ðm
ð !)¨×):Ñ):Ñ ;ð	m
ð
 " %×"3Ñ"3Ñ4ðm
ð   × 1Ñ 1Ñ2ðm
ð  (¨×(9Ñ(9Ñ:ðm
ð ˜˜d™Ñ$ðm
ð $ D™>ðm
ð ' t™nðm
ð ˜d‘^ðm
ð 
ˆu�U×&Ñ&Ñ'Ð)BÐBÑ	Còm
ó dó Bôm
r)   rÕ  z–
    DETR Model (consisting of a backbone and encoder-decoder Transformer) with a segmentation head on top, for tasks
    such as COCO panoptic.

    c                   ót  ‡ — e Zd Zdefˆ f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 )ÚDetrForSegmentationr…   c                 óv  •— t         ‰| �  |«       t        |«      | _        |j                  |j
                  }}| j                  j                  j                  j                  j                  }t        ||z   |d d d…   dd  |«      | _        t        |||d|j                  ¬«      | _        | j                  «        y )NrY   éýÿÿÿr   )rñ   rQ  )rE   rF   rÕ  Údetrré   r&  rp   r�   r°   r’   ÚDetrMaskHeadSmallConvÚ	mask_headrT  rS  Úbbox_attentionrn  )rJ   r…   Úhidden_sizeÚnumber_of_headsr’   rL   s        €r*   rF   zDetrForSegmentation.__init__Þ  s©   ø€ Ü‰Ñ˜Ô ô +¨6Ó2ˆŒ	ð (.§~¡~°v×7UÑ7U�_ˆØ%)§Y¡Y§_¡_×%=Ñ%=×%JÑ%J×%eÑ%eÐ"ä.Ø˜/Ñ)Ð+EÁdÈÀdÑ+KÈBÈCÐ+PÐR]ó
ˆŒô 1Ø˜ o¸sÈ×H^ÑH^ô
ˆÔð 	�‰Õr)   r´  r›   rœ   r¶  r·  r  r¸  rÚ  r  rz  r€  r  c                 óÆ  — |
�|
n| j                   j                  }
|j                  \  }}}}|j                  }|€t	        j
                  |||f|¬«      }| j                  j                  j                  ||¬«      \  }}|d   \  }}|j                  \  }}}}| j                  j                  j                  |«      }|j                  d«      j                  ddd«      }|d   j                  d«      j                  ddd«      }|j                  d«      }|€,| j                  j                  j                  |||||	|
¬«      }nI|
rGt        |t        «      s7t        |d   t        |«      dkD  r|d   ndt        |«      dkD  r|d   nd¬	«      }| j                  j                  j                   j"                  j%                  d«      j'                  |dd«      }t	        j(                  |«      }| j                  j                  j+                  |d|||d   |||	|
¬
«	      }|d   }| j                  j-                  |«      }| j                  j/                  |«      j1                  «       }|d   j                  ddd«      j3                  || j                   j4                  ||«      }|j3                  |||«      }| j7                  ||| ¬«      }| j9                  |||d   d   |d   d   |d   d   g«      } | j3                  || j                  j                   j:                  | j                  d   | j                  d   «      }!d\  }"}#}$|�˜d\  }%}&| j                   j<                  rW|
r|j>                  n|d   }'| j                  j-                  |'«      }%| j                  j/                  |'«      j1                  «       }&| jA                  |||||!| j                   |%|&«      \  }"}#}$|
s'|$�|||!f|$z   |z   |z   }(n|||!f|z   |z   }(|"�|"|#f|(z   S |(S tC        |"|#|||!|$|jD                  |jF                  |jH                  |jJ                  |jD                  |jF                  |jH                  ¬«      S )aÂ  
        labels (`List[Dict]` of len `(batch_size,)`, *optional*):
            Labels for computing the bipartite matching loss, DICE/F-1 loss and Focal loss. List of dicts, each
            dictionary containing at least the following 3 keys: 'class_labels', 'boxes' and 'masks' (the class labels,
            bounding boxes and segmentation masks 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,)`, the boxes a
            `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)` and the masks a
            `torch.FloatTensor` of shape `(number of bounding boxes in the image, height, width)`.

        Returns:

        Examples:

        ```python
        >>> import io
        >>> import requests
        >>> from PIL import Image
        >>> import torch
        >>> import numpy

        >>> from transformers import AutoImageProcessor, DetrForSegmentation
        >>> from transformers.image_transforms import rgb_to_id

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

        >>> image_processor = AutoImageProcessor.from_pretrained("facebook/detr-resnet-50-panoptic")
        >>> model = DetrForSegmentation.from_pretrained("facebook/detr-resnet-50-panoptic")

        >>> # prepare image for the model
        >>> inputs = image_processor(images=image, return_tensors="pt")

        >>> # forward pass
        >>> outputs = model(**inputs)

        >>> # Use the `post_process_panoptic_segmentation` method of the `image_processor` to retrieve post-processed panoptic segmentation maps
        >>> # Segmentation results are returned as a list of dictionaries
        >>> result = image_processor.post_process_panoptic_segmentation(outputs, target_sizes=[(300, 500)])

        >>> # A tensor of shape (height, width) where each value denotes a segment id, filled with -1 if no segment is found
        >>> panoptic_seg = result[0]["segmentation"]
        >>> # Get prediction score and segment_id to class_id mapping of each segment
        >>> panoptic_segments_info = result[0]["segments_info"]
        ```NrÜ   )rœ   rY   rz   r   r   rº  rx  r»  )r«   rž   rÜ  rr  )r/   r0   r1   r2   r=   r3   r4   r5   r6   r7   r8   r9   r:   )&r…   r{  r¤   rh   r%   rH   rè  rp   r�   r£  rË   rÍ   r¥  re   r   rl   rG  rA   rÝ   rÞ   r¼  r¦  rØ  rÙ  rÝ  r   ré   rë  rê  r¤  r“  r   rÞ  r<   r4   r  ry  r7   ))rJ   r›   rœ   r¶  r·  r  r¸  rÚ  r  rz  r€  rþ   rŠ   rß   rà   rh   r¨   r½  rª   r«   r¾  r¿  r  rÀ  rG  rÁ  rÂ  rß  r1   r2   ÚmemoryÚ	bbox_maskÚ	seg_masksr=   r/   r0   r3   rà  rá  r˜  râ  s)                                            r*   r_   zDetrForSegmentation.forwardò  s�  € ðx &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆà2>×2DÑ2DÑ/ˆ
�L &¨%Ø×$Ñ$ˆàÐÜŸ™ Z°¸Ð$?ÈÔOˆJð )-¯	©	¯©×(@Ñ(@ÀÐZdÐ(@Ó(eÑ%ˆÐ%ð % R™LÑˆ�TØ2=×2CÑ2CÑ/ˆ
�L &¨%Ø $§	¡	§¡× @Ñ @ÀÓ MÐð 3×:Ñ:¸1Ó=×EÑEÀaÈÈAÓNÐØ,¨RÑ0×8Ñ8¸Ó;×CÑCÀAÀqÈ!ÓLˆàŸ™ a›ˆð
 Ð"Ø"Ÿi™iŸo™o×5Ñ5Ø0Ø-Ø-Ø"3Ø%9Ø'ð 6ó ‰Oñ ¤¨O¼_Ô!MÜ-Ø"1°!Ñ"4Ü47¸Ó4HÈ1Ò4L˜o¨aÒ0ÐRVÜ14°_Ó1EÈÒ1I˜?¨1Ò-ÈtôˆOð %)§I¡I§O¡O×$MÑ$M×$TÑ$T×$^Ñ$^Ð_`Ó$a×$hÑ$hØ˜˜1ó%
Ð!ô ×"Ñ"Ð#<Ó=ˆð Ÿ)™)Ÿ/™/×1Ñ1Ø!ØØ)Ø&?Ø"1°!Ñ"4Ø#1Ø/Ø!5Ø#ð 2ó 

ˆð *¨!Ñ,ˆð —‘×2Ñ2°?ÓCˆØ—Y‘Y×-Ñ-¨oÓ>×FÑFÓHˆ
à  Ñ#×+Ñ+¨A¨q°!Ó4×9Ñ9¸*ÀdÇkÁk×FYÑFYÐ[aÐchÓiˆØ×"Ñ" :¨v°uÓ=ˆð
 ×'Ñ'¨¸ÀtÀeÐ'ÓLˆ	à—N‘NÐ#8¸)ÀhÈqÁkÐRSÁnÐV^Ð_`ÑVaÐbcÑVdÐfnÐopÑfqÐrsÑftÐEuÓvˆ	à—^‘^ J°·	±	×0@Ñ0@×0LÑ0LÈiÏoÉoÐ^`ÑNaÐcl×crÑcrÐsuÑcvÓwˆ
à-=Ñ*ˆˆiÐ*ØÐØ+5Ñ(ˆM˜=Ø�{‰{×)Ò)ÙMX˜×IÒIÐ^mÐnpÑ^q�Ø $§	¡	× AÑ AÀ,Ó O�Ø $§	¡	× 8Ñ 8¸Ó F× NÑ NÓ P�Ø15×1CÑ1CØ˜ ¨
°JÀÇÁÈ]Ð\ió2Ñ.ˆD�)Ð.ñ Ø Ð,Ø  *¨jÐ9Ð<MÑMÐP_Ñ_ÐbqÑq‘à  *¨jÐ9¸OÑKÈoÑ]�Ø37Ð3C�T˜9Ð%¨Ñ.ÐOÈÐOä%ØØØØ!Ø!Ø/Ø-×?Ñ?Ø"1×"?Ñ"?Ø.×9Ñ9Ø,×=Ñ=Ø&5×&GÑ&GØ"1×"?Ñ"?Ø.×9Ñ9ô
ð 	
r)   rž  )r!   r"   r#   r   rF   r   rÃ  r   r<   rÄ  r%   r&   r   rÅ  r   rã  r¦   r   r   r_   r`   ra   s   @r*   rå  rå  Õ  s:  ø„ ð˜zõ ñ( +Ð+@ÓAÙÐ+AÐP_Ô`ð 26Ø>BØ7;Ø59Ø=AØ'+Ø,0Ø/3Ø&*ñj
à×'Ñ'ðj
ð ˜U×-Ñ-Ñ.ðj
ð !)¨×):Ñ):Ñ ;ð	j
ð
 " %×"3Ñ"3Ñ4ðj
ð   × 1Ñ 1Ñ2ðj
ð  (¨×(9Ñ(9Ñ:ðj
ð ˜˜d™Ñ$ðj
ð $ D™>ðj
ð ' t™nðj
ð ˜d‘^ðj
ð 
ˆu�U×&Ñ&Ñ'Ð)?Ð?Ñ	@òj
ó aó Bôj
r)   rå  Úlengthc                 ó|   — | j                  d«      j                  dt        |«      ddd«      j                  dd«      S )Nr   r   )rÝ   rÞ   r!  rË   )rü   rò  s     r*   Ú_expandrô  ¡  s7   € Ø×Ñ˜AÓ×%Ñ% a¬¨V«°a¸¸AÓ>×FÑFÀqÈ!ÓLÐLr)   c                   ó<   ‡ — e Zd ZdZˆ fd„Zdededee   fd„Zˆ xZS )ré  z^
    Simple convolutional head, using group norm. Upsampling is done using a FPN approach
    c                 ó€  •— t         ‰| �  «        |dz  dk7  rt        d«      ‚||dz  |dz  |dz  |dz  |dz  g}t        j                  ||dd	¬
«      | _        t        j                  d|«      | _        t        j                  ||d	   dd	¬
«      | _        t        j                  t        d|d	   «      |d	   «      | _
        t        j                  |d	   |d   dd	¬
«      | _        t        j                  t        d|d   «      |d   «      | _        t        j                  |d   |d   dd	¬
«      | _        t        j                  t        d|d   «      |d   «      | _        t        j                  |d   |d   dd	¬
«      | _        t        j                  t        d|d   «      |d   «      | _        t        j                  |d   d	dd	¬
«      | _        || _        t        j                  |d   |d	   d	«      | _        t        j                  |d	   |d   d	«      | _        t        j                  |d   |d   d	«      | _        | j-                  «       D ]r  }t/        |t        j                  «      sŒt        j0                  j3                  |j4                  d	¬«       t        j0                  j7                  |j8                  d«       Œt y )Né   r   zsThe hidden_size + number of attention heads must be divisible by 8 as the number of groups in GroupNorm is set to 8rz   r{   r~   rÓ   r   r   )Úpadding)Úa)rE   rF   r•   r
   r[  Úlay1Ú	GroupNormÚgn1Úlay2r4  Úgn2Úlay3Úgn3Úlay4Úgn4Úlay5Úgn5Úout_layrÂ   Úadapter1Úadapter2Úadapter3Úmodulesre   rU  Úkaiming_uniform_rA   Ú	constant_rB   )rJ   rÂ   Úfpn_dimsÚcontext_dimÚ
inter_dimsÚmrL   s         €r*   rF   zDetrMaskHeadSmallConv.__init__«  sG  ø€ Ü‰ÑÔà�‰7�aŠ<Üð)óð ð
 ˜;¨!Ñ+¨[¸AÑ-=¸{ÈaÑ?OÐQ\Ð`bÑQbÐdoÐsuÑduÐvˆ
ä—I‘I˜c 3¨°1Ô5ˆŒ	Ü—<‘<  3Ó'ˆŒÜ—I‘I˜c :¨a¡=°!¸QÔ?ˆŒ	Ü—<‘<¤ A z°!¡}Ó 5°zÀ!±}ÓEˆŒÜ—I‘I˜j¨™m¨Z¸©]¸AÀqÔIˆŒ	Ü—<‘<¤ A z°!¡}Ó 5°zÀ!±}ÓEˆŒÜ—I‘I˜j¨™m¨Z¸©]¸AÀqÔIˆŒ	Ü—<‘<¤ A z°!¡}Ó 5°zÀ!±}ÓEˆŒÜ—I‘I˜j¨™m¨Z¸©]¸AÀqÔIˆŒ	Ü—<‘<¤ A z°!¡}Ó 5°zÀ!±}ÓEˆŒÜ—y‘y ¨A¡°°1¸aÔ@ˆŒàˆŒäŸ	™	 (¨1¡+¨z¸!©}¸aÓ@ˆŒÜŸ	™	 (¨1¡+¨z¸!©}¸aÓ@ˆŒÜŸ	™	 (¨1¡+¨z¸!©}¸aÓ@ˆŒà—‘“ò 	-ˆAÜ˜!œRŸY™YÕ'Ü—‘×(Ñ(¨¯©°QÐ(Ô7Ü—‘×!Ñ! !§&¡&¨!Õ,ñ	-r)   r\   rð  Úfpnsc                 ó´  — t        j                  t        ||j                  d   «      |j	                  dd«      gd«      }| j                  |«      }| j                  |«      }t        j                  j                  |«      }| j                  |«      }| j                  |«      }t        j                  j                  |«      }| j                  |d   «      }|j                  d«      |j                  d«      k7  r-t        ||j                  d«      |j                  d«      z  «      }|t        j                  j                  ||j                  dd  d¬«      z   }| j                  |«      }| j!                  |«      }t        j                  j                  |«      }| j#                  |d   «      }|j                  d«      |j                  d«      k7  r-t        ||j                  d«      |j                  d«      z  «      }|t        j                  j                  ||j                  dd  d¬«      z   }| j%                  |«      }| j'                  |«      }t        j                  j                  |«      }| j)                  |d   «      }|j                  d«      |j                  d«      k7  r-t        ||j                  d«      |j                  d«      z  «      }|t        j                  j                  ||j                  dd  d¬«      z   }| j+                  |«      }| j-                  |«      }t        j                  j                  |«      }| j/                  |«      }|S )Nr   r   rž   Únearest)rŸ   Úmoderz   )r%   rÌ   rô  r¤   rË   rú  rü  r
   r¡   rÒ  rý  rþ  r  rŸ   r¢   rÿ  r   r  r  r  r  r  r  r  )rJ   r\   rð  r  Úcur_fpns        r*   r_   zDetrMaskHeadSmallConv.forwardÍ  s”  € ô �I‰I”w˜q )§/¡/°!Ñ"4Ó5°y×7HÑ7HÈÈAÓ7NÐOÐQRÓSˆà�I‰I�a‹LˆØ�H‰H�Q‹KˆÜ�M‰M×Ñ˜qÓ!ˆØ�I‰I�a‹LˆØ�H‰H�Q‹KˆÜ�M‰M×Ñ˜qÓ!ˆà—-‘-  Q¡Ó(ˆØ�<‰<˜‹?˜aŸf™f Q›iÒ'Ü˜g q§v¡v¨a£y°G·L±LÀ³OÑ'CÓDˆGØ”b—m‘m×/Ñ/°¸¿¹ÀbÀcÐ8JÐQZÐ/Ó[Ñ[ˆØ�I‰I�a‹LˆØ�H‰H�Q‹KˆÜ�M‰M×Ñ˜qÓ!ˆà—-‘-  Q¡Ó(ˆØ�<‰<˜‹?˜aŸf™f Q›iÒ'Ü˜g q§v¡v¨a£y°G·L±LÀ³OÑ'CÓDˆGØ”b—m‘m×/Ñ/°¸¿¹ÀbÀcÐ8JÐQZÐ/Ó[Ñ[ˆØ�I‰I�a‹LˆØ�H‰H�Q‹KˆÜ�M‰M×Ñ˜qÓ!ˆà—-‘-  Q¡Ó(ˆØ�<‰<˜‹?˜aŸf™f Q›iÒ'Ü˜g q§v¡v¨a£y°G·L±LÀ³OÑ'CÓDˆGØ”b—m‘m×/Ñ/°¸¿¹ÀbÀcÐ8JÐQZÐ/Ó[Ñ[ˆØ�I‰I�a‹LˆØ�H‰H�Q‹KˆÜ�M‰M×Ñ˜qÓ!ˆà�L‰L˜‹OˆØˆr)   )	r!   r"   r#   r$   rF   r	   r   r_   r`   ra   s   @r*   ré  ré  ¦  s,   ø„ ñô -ðD&˜ð &¨Fð &¸$¸v¹,÷ &r)   ré  c                   ó8   ‡ — e Zd ZdZdˆ fd„	Zddee   fd„Zˆ xZS )rT  zdThis is a 2D attention module, which only returns the attention softmax (no multiplication by value)c                 ó&  •— t         ‰| �  «        || _        || _        t	        j
                  |«      | _        t	        j                  |||¬«      | _        t	        j                  |||¬«      | _	        t        || j                  z  «      dz  | _        y )Nrô   ró   )rE   rF   rð   rÎ  r
   ÚDropoutrñ   r÷   rX  rW  r£   Únormalize_fact)rJ   Ú	query_dimrÎ  rð   rñ   rB   rQ  rL   s          €r*   rF   zDetrMHAttentionMap.__init__ù  so   ø€ Ü‰ÑÔØ"ˆŒØ$ˆŒÜ—z‘z 'Ó*ˆŒäŸ	™	 )¨Z¸dÔCˆŒÜŸ	™	 )¨Z¸dÔCˆŒä# J°·±Ñ$?Ó@ÀDÑHˆÕr)   r«   c                 ó  — | j                  |«      }t        j                  j                  || j                  j
                  j                  d«      j                  d«      | j                  j                  «      }|j                  |j                  d   |j                  d   | j                  | j                  | j                  z  «      }|j                  |j                  d   | j                  | j                  | j                  z  |j                  d   |j                  d   «      }t        j                  d|| j                  z  |«      }|�W|j                  |j                  d«      j                  d«      t        j                   |j"                  «      j$                  «      }t        j                  j'                  |j)                  d«      d¬«      j                  |j+                  «       «      }| j-                  |«      }|S )NrY   r   r   rž   zbqnc,bnchw->bqnhwrz   rÁ   )rX  r
   r¡   Úconv2drW  rA   rÝ   rB   r   r¤   rð   rÎ  r%   Úeinsumr  Úmasked_fillr9  r³   r4  r  rË   rŸ   rñ   )rJ   ÚqrÊ  r«   Úqueries_per_headÚkeys_per_headÚweightss          r*   r_   zDetrMHAttentionMap.forward  s€  € Ø�M‰M˜!ÓˆÜ�M‰M× Ñ   D§M¡M×$8Ñ$8×$BÑ$BÀ2Ó$F×$PÑ$PÐQSÓ$TÐVZ×VcÑVc×VhÑVhÓiˆØŸ6™6 !§'¡'¨!¡*¨a¯g©g°a©j¸$¿.¹.È$Ï/É/Ð]a×]kÑ]kÑJkÓlÐØŸ™˜qŸw™w q™z¨4¯>©>¸4¿?¹?ÈdÏnÉnÑ;\Ð^_×^eÑ^eÐfhÑ^iÐkl×krÑkrÐsuÑkvÓwˆÜ—,‘,Ð2Ð4DÀt×GZÑGZÑ4ZÐ\iÓjˆàÐØ×)Ñ)¨$¯.©.¸Ó*;×*EÑ*EÀaÓ*HÌ%Ï+É+ÐV]×VcÑVcÓJd×JhÑJhÓiˆGÜ—-‘-×'Ñ'¨¯©¸Ó(:ÀÐ'ÓC×HÑHÈÏÉËÓXˆØ—,‘,˜wÓ'ˆØˆr)   )r   TNr¯   )	r!   r"   r#   r$   rF   r   r	   r_   r`   ra   s   @r*   rT  rT  ö  s   ø„ Ùnõ	Iñ (¨6Ñ"2÷ r)   rT  )rÕ  rå  r   rM  )Gr$   r¼   Údataclassesr   Útypingr   r   r   r   r   r%   r	   r
   Úactivationsr   Úmodeling_attn_mask_utilsr   Úmodeling_outputsr   r   r   Úmodeling_utilsr   Úutilsr   r   r   r   r   r   r   Úutils.backbone_utilsr   Úconfiguration_detrr   rw   r   Ú
get_loggerr!   ÚloggerrÄ  Ú_CHECKPOINT_FOR_DOCr   r,   r.   r<   ÚModuler?   ro   ru   r­   r·   rÕ   rì   rî   r#  rA  rM  ÚDETR_START_DOCSTRINGrÃ  rf  rŠ  r   rÇ  rÕ  rå  r!  rô  ré  rT  Ú__all__r(   r)   r*   ú<module>r1     s–  ðñ ã Ý !ß 5Õ 5ã ß å !Ý Bß gÑ gÝ -÷÷ ñ õ 2Ý *ñ ÔÝ!ð 
ˆ×	Ñ	˜HÓ	%€à€Ø/Ð ð ôCÐ:ó Có ðCð: ô$CÐ(ó $Có ð$CðN ô;B ó ;Bó ð;Bð| ôBB˜[ó BBó ðBBôN$ ˜BŸI™Iô $ òN'ô0E�b—i‘iô EôP�B—I‘Iô ô*" §	¡	ô "ôJ 2§9¡9ô ò.
ô~2�B—I‘Iô ~2ôBD�r—y‘yô DôNf�r—y‘yô fôR?˜/ô ?ð<Ð ð #Ð ôLo
Ð%ô o
ôdm
Ð%ô m
ñ` ðð óô^
Ð#ó ^
óð^
ôD˜BŸI™Iô ñ* ðð óôA
Ð0ó A
óðA
ñH ðð
 óôA
Ð-ó A
óðA
ðHM˜Có Mô
M˜BŸI™Iô Mô`˜Ÿ™ô ò8�r)   