
    0idt              	          d Z ddlZddlZddlZddlmZ ddlmZ ddl	m
Z
 ddlmZ ddlmZ dd	lmZmZ dd
lmZ ddlmZmZ ddlmZ  ej2                  e      Z G d dej8                        Zej<                  j>                  d        Z d Z! G d dej8                        Z"d0dejF                  de$de%dejF                  fdZ& G d dej8                        Z' G d dej8                        Z( G d dej8                        Z) G d d ej8                        Z*d! Z+d" Z, G d# d$e      Z- G d% d&ej8                        Z.e G d' d(e             Z/e G d) d*e/             Z0 ed+,       G d- d.ee/             Z1g d/Z2y)1zPyTorch ViTDet backbone.    N)nn   )initialization)ACT2FN)BackboneMixin)GradientCheckpointingLayer)BackboneOutputBaseModelOutput)PreTrainedModel)auto_docstringlogging   )VitDetConfigc                   `     e Zd ZdZ fdZd Zdej                  dej                  fdZ xZ	S )VitDetEmbeddingsz
    This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
    `hidden_states` (patch embeddings) to be consumed by a Transformer.
    c                 p   t         |           |j                  |j                  }}|j                  |j
                  }}t        |t        j                  j                        r|n||f}t        |t        j                  j                        r|n||f}|d   |d   z  |d   |d   z  z  }|| _
        || _        || _        || _        |j                  r?|dz   }t        j                  t        j                   d||j
                              | _        nd | _        t        j$                  ||||      | _        y )Nr   r   )kernel_sizestride)super__init__pretrain_image_size
patch_sizenum_channelshidden_size
isinstancecollectionsabcIterable
image_sizenum_patches use_absolute_position_embeddingsr   	Parametertorchzerosposition_embeddingsConv2d
projection)	selfconfigr   r   r   r   r    num_positions	__class__s	           f/mnt/e/genesis-system/.venv/lib/python3.12/site-packages/transformers/models/vitdet/modeling_vitdet.pyr   zVitDetEmbeddings.__init__)   s   !'!;!;V=N=NJ
$*$7$79K9Kk#-j+//:R:R#SZZdfpYq
#-j+//:R:R#SZZdfpYq
!!}
15*Q-:VW=:XY$$(&22'!OM')||EKK=RXRdRd4e'fD$'+D$))L+:^hi    c                    |r|ddddf   }|j                   d   }t        t        j                  |            }||z  |k7  rt	        d      t
        j                  j                         s
||k7  s||k7  r]t        j                  j                  |j                  d||d      j                  dddd      ||fdd	
      }|j                  dddd      S |j                  d||d      S )a  
        Calculate absolute positional embeddings. If needed, resize embeddings and remove cls_token dimension for the
        original embeddings.

        Args:
            abs_pos_embeddings (`torch.Tensor`):
                Absolute positional embeddings with (1, num_position, num_channels).
            has_cls_token (`bool`):
                If true, has 1 embedding in abs_pos_embeddings for cls token.
            height (`int`):
                Height of input image tokens.
            width (`int`):
                Width of input image tokens.

        Returns:
            Absolute positional embeddings after processing with shape (1, height, width, num_channels)
        Nr   z5Absolute position embeddings must be a square number.r   r      bicubicF)sizemodealign_corners)shapeintmathsqrt
ValueErrorr#   jit
is_tracingr   
functionalinterpolatereshapepermute)r(   abs_pos_embeddingshas_cls_tokenheightwidthnum_positionr2   new_abs_pos_embeddingss           r,   get_absolute_positionsz'VitDetEmbeddings.get_absolute_positions?   s    $ !3AqrE!:)//2499\*+$;,&TUU99!dfn%']]%>%>"**1dD"=EEaAqQe_#	 &? &" *11!Q1==%--aCCr-   pixel_valuesreturnc                 z   |j                   d   }|| j                  k7  rt        d| j                   d| d      | j                  |      }| j                  c|j                  dddd      }|| j                  | j                  d|j                   d   |j                   d         z   }|j                  dddd      }|S )	Nr   zoMake sure that the channel dimension of the pixel values match with the one set in the configuration. Expected z	 but got .r   r0   r   T)r5   r   r9   r'   r%   r?   rF   )r(   rG   r   
embeddingss       r,   forwardzVitDetEmbeddings.forwarde   s    #))!,4,,,!../yaI  __\2
##/#++Aq!Q7J#d&A&A(($
0@0@0CZEUEUVWEX' J $++Aq!Q7Jr-   )
__name__
__module____qualname____doc__r   rF   r#   TensorrL   __classcell__r+   s   @r,   r   r   #   s0    
j,$DLELL U\\ r-   r   c                 T   t        dt        | |      z  dz
        }|j                  d   |k7  rtt        j                  j                  |j                  d|j                  d   d      j                  ddd      |d      }|j                  d|      j                  dd      }n|}t        j                  |       dddf   t        || z  d      z  }t        j                  |      dddf   t        | |z  d      z  }||z
  |dz
  t        | |z  d      z  z   }||j                            S )	a  
    Get relative positional embeddings according to the relative positions of query and key sizes.

    Args:
        q_size (`int`):
            Size of query q.
        k_size (`int`):
            Size of key k.
        rel_pos (`torch.Tensor`):
            Relative position embeddings (num_embeddings, num_channels).

    Returns:
        Extracted positional embeddings according to relative positions.
    r0   r   r   r/   linear)r2   r3   Ng      ?)r6   maxr5   r   r<   r=   r>   r?   r#   arangelong)q_sizek_sizerel_posmax_rel_distrel_pos_resizedq_coordsk_coordsrelative_coordss           r,   get_rel_posra   {   s%     q3vv..23L}}Q<'--33OOAw}}Q/4<<Q1E 4 

 *11"lCKKAqQ! ||F#AtG,s6F?C/HHH||F#D!G,s6F?C/HHH(*vzS&RU=V.VVO?//122r-   c                    |\  }}|\  }}	t        |||      }
t        ||	|      }|j                  \  }}}|j                  ||||      }t        j                  d||
      }
t        j                  d||      }| j                  |||||	      |
dddddddddf   z   |dddddddddf   z   j                  |||z  ||	z        } | S )a  
    Calculate decomposed Relative Positional Embeddings as introduced in
    [MViT2](https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py).

    Args:
        attn (`torch.Tensor`):
            Attention map.
        queries (`torch.Tensor`):
            Query q in the attention layer with shape (batch_size, queries_height * queries_width, num_channels).
        rel_pos_h (`torch.Tensor`):
            Relative position embeddings (Lh, num_channels) for height axis.
        rel_pos_w (`torch.Tensor`):
            Relative position embeddings (Lw, num_channels) for width axis.
        q_size (`tuple[int]`):
            Spatial sequence size of query q with (queries_height, queries_width).
        k_size (`tuple[int]`):
            Spatial sequence size of key k with (keys_height, keys_width).

    Returns:
        attn (Tensor): attention map with added relative positional embeddings.
    zbhwc,hkc->bhwkzbhwc,wkc->bhwkN)ra   r5   r>   r#   einsumview)attnqueries	rel_pos_h	rel_pos_wrY   rZ   queries_heightqueries_widthkeys_height
keys_widthrelative_heightrelative_width
batch_size_dimr_qrelative_weights                    r,   !add_decomposed_relative_positionsrt      s    , %+!NM$K!.+yIO 
IFN J3
//*nmS
ICll#3S/JOll#3S.IO 			*nm[*U
!Q1d*
+	,
!Q4*
+	, d:~5{Z7OP	 	 Kr-   c                   ,     e Zd ZdZd fd	ZddZ xZS )VitDetAttentionz=Multi-head Attention block with relative position embeddings.c                     t         |           |j                  }|j                  }|| _        ||z  }|dz  | _        t        j                  ||dz  |j                        | _	        t        j                  ||      | _
        |j                  | _        | j                  rot        j                  t        j                  d|d   z  dz
  |            | _        t        j                  t        j                  d|d   z  dz
  |            | _        yy)z
        Args:
            config (`VitDetConfig`):
                Model configuration.
            input_size (`tuple[int]`, *optional*):
                Input resolution, only required in case relative position embeddings are added.
        g      r   biasr0   r   r   N)r   r   r   num_attention_heads	num_headsscaler   Linearqkv_biasqkvproj use_relative_position_embeddingsr"   r#   r$   rg   rh   )r(   r)   
input_sizerq   r{   head_dimr+   s         r,   r   zVitDetAttention.__init__   s     	  ..	")#t^
99S#'@IIc3'	060W0W-00\\%++a*Q-6G!6KX*VWDN\\%++a*Q-6G!6KX*VWDN 1r-   c           	      0   |j                   \  }}}}| j                  |      j                  |||z  d| j                  d      j	                  ddddd      }|j                  d|| j                  z  ||z  d      j                  d      \  }}	}
|| j                  z  |	j                  dd      z  }| j                  r(t        ||| j                  | j                  ||f||f      }|j                  d      }||
z  }|j                  || j                  ||d      }|j	                  ddddd      }|j                  |||d      }| j                  |      }|r>|j                  || j                  |j                   d   |j                   d         }||f}|S |f}|S )	Nr   r/   r0   r   r      )rq   )r5   r   r>   r{   r?   unbindr|   	transposer   rt   rg   rh   softmaxrd   r   )r(   hidden_stateoutput_attentionsro   rB   rC   rp   r   rf   keysvaluesattention_scoresattention_probsoutputss                 r,   rL   zVitDetAttention.forward   s   '3'9'9$
FE1hh|$,,Z%DNN\^_gghiklnoqrtuv #AzDNN/JFUZN\^ _ f fgh iv#djj0DNN2r4JJ00@ '4>>4>>FTY?]cej\k  +22r2:&/#((T^^VUTVW#++Aq!Q:#++JrJyy.-55DNNO,A,A",EG\G\]_G`O $_5G  $oGr-   NFrM   rN   rO   rP   r   rL   rR   rS   s   @r,   rv   rv      s    GX4r-   rv   input	drop_probtrainingrH   c                    |dk(  s|s| S d|z
  }| j                   d   fd| j                  dz
  z  z   }|t        j                  || j                  | j
                        z   }|j                          | j                  |      |z  }|S )zc
    Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).

            r   r   )r   )dtypedevice)r5   ndimr#   randr   r   floor_div)r   r   r   	keep_probr5   random_tensoroutputs          r,   	drop_pathr     s    
 CxII[[^

Q 77E

5ELL YYMYYy!M1FMr-   c                   x     e Zd ZdZd	dedz  ddf fdZdej                  dej                  fdZde	fdZ
 xZS )
VitDetDropPathzXDrop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).Nr   rH   c                 0    t         |           || _        y r   )r   r   r   )r(   r   r+   s     r,   r   zVitDetDropPath.__init__  s    "r-   hidden_statesc                 D    t        || j                  | j                        S r   )r   r   r   )r(   r   s     r,   rL   zVitDetDropPath.forward  s    FFr-   c                      d| j                    S )Nzp=)r   r(   s    r,   
extra_reprzVitDetDropPath.extra_repr"  s    DNN#$$r-   r   )rM   rN   rO   rP   floatr   r#   rQ   rL   strr   rR   rS   s   @r,   r   r     sG    b#%$, #$ #GU\\ Gell G%C %r-   r   c                   *     e Zd ZdZd fd	Zd Z xZS )VitDetLayerNormaL  
    A LayerNorm variant, popularized by Transformers, that performs point-wise mean and variance normalization over the
    channel dimension for inputs that have shape (batch_size, channels, height, width).
    https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119
    c                     t         |           t        j                  t	        j
                  |            | _        t        j                  t	        j                  |            | _        || _	        |f| _
        y r   )r   r   r   r"   r#   onesweightr$   ry   epsnormalized_shape)r(   r   r   r+   s      r,   r   zVitDetLayerNorm.__init__-  sT    ll5::.>#?@LL-=!>?	!1 3r-   c                    |j                  dd      }||z
  j                  d      j                  dd      }||z
  t        j                  || j                  z         z  }| j
                  d d d d f   |z  | j                  d d d d f   z   }|S )Nr   T)keepdimr0   )meanpowr#   r8   r   r   ry   )r(   xuss       r,   rL   zVitDetLayerNorm.forward4  s    FF1dF#UKKN40UejjTXX..KK4&*TYYq$}-EEr-   )gư>r   rS   s   @r,   r   r   &  s    4r-   r   c                   (     e Zd ZdZ fdZd Z xZS )VitDetResBottleneckBlockz
    The standard bottleneck residual block without the last activation layer. It contains 3 conv layers with kernels
    1x1, 3x3, 1x1.
    c                    t         |           t        j                  ||dd      | _        t        |      | _        t        |j                     | _	        t        j                  ||ddd      | _
        t        |      | _        t        |j                     | _        t        j                  ||dd      | _        t        |      | _        y)ar  
        Args:
            config (`VitDetConfig`):
                Model configuration.
            in_channels (`int`):
                Number of input channels.
            out_channels (`int`):
                Number of output channels.
            bottleneck_channels (`int`):
                Number of output channels for the 3x3 "bottleneck" conv layers.
        r   Frx   r   )paddingry   N)r   r   r   r&   conv1r   norm1r   
hidden_actact1conv2norm2act2conv3norm3)r(   r)   in_channelsout_channelsbottleneck_channelsr+   s        r,   r   z!VitDetResBottleneckBlock.__init__B  s     	YY{,?O
$%89
6,,-	YY24GTU\ab
$%89
6,,-	YY2L!%P
$\2
r-   c                 N    |}| j                         D ]
  } ||      } ||z   }|S r   )children)r(   r   outlayers       r,   rL   z VitDetResBottleneckBlock.forwardZ  s5    ]]_ 	E*C	 #g
r-   r   rS   s   @r,   r   r   <  s    
30r-   r   c                   d     e Zd Zdededdf fdZdej                  dej                  fdZ xZS )	VitDetMlpin_featureshidden_featuresrH   Nc                    t         |           t        j                  ||      | _        t
        |j                     | _        t        j                  ||      | _        t        j                  |j                        | _        y r   )r   r   r   r}   fc1r   r   actfc2Dropoutdropout_probdrop)r(   r)   r   r   r+   s       r,   r   zVitDetMlp.__init__d  sZ    99[/:&++,99_k:JJv223	r-   r   c                     | j                  |      }| j                  |      }| j                  |      }| j                  |      }| j                  |      }|S r   )r   r   r   r   )r(   r   s     r,   rL   zVitDetMlp.forwardk  sH    HHQKHHQKIIaLHHQKIIaLr-   )	rM   rN   rO   r6   r   r#   rQ   rL   rR   rS   s   @r,   r   r   c  s8    4C 4# 4$ 4 %,, r-   r   c           	      `   | j                   \  }}}}|||z  z
  |z  }|||z  z
  |z  }t        j                  j                  | ddd|d|f      } ||z   ||z   }	}| j	                  |||z  ||	|z  ||      } | j                  dddddd      j                         j	                  d|||      }
|
||	ffS )a  
    Partition into non-overlapping windows with padding if needed.

    Args:
        hidden_state (`torch.Tensor`):
            Input tokens with [batch_size, height, width, num_channels].
        window_size (`int`):
            Window size.

    Returns:
        `tuple(torch.FloatTensor)` comprising various elements:
        - windows: windows after partition with [batch_size * num_windows, window_size, window_size, num_channels].
        - (padded_height, padded_width): padded height and width before partition
    r   r   r   r0   r      r/   )r5   r   r<   padrd   r?   
contiguous)r   window_sizero   rB   rC   r   
pad_height	pad_widthpadded_heightpadded_widthwindowss              r,   window_partitionr   u  s     /;.@.@+J| 44CJu{22kAI ==$$\Aq!Y:3VWL"(:"5uy7H<M$$M[0+|{?Z\giuL ""1aAq!4??AFFr;XceqrG]L111r-   c                 6   |\  }}|\  }}| j                   d   ||z  |z  |z  z  }| j                  |||z  ||z  ||d      }	|	j                  dddddd      j                         }	|	j                  |||d      }	|	ddd|d|ddf   j                         }	|	S )	aB  
    Window unpartition into original sequences and removing padding.

    Args:
        windows (`torch.Tensor`):
            Input tokens with [batch_size * num_windows, window_size, window_size, num_channels].
        window_size (`int`):
            Window size.
        pad_height_width (`tuple[int]`):
            Padded height and width (padded_height, padded_width).
        height_width (`tuple[int]`):
            Original height and width before padding.

    Returns:
        hidden_state: unpartitioned sequences with [batch_size, height, width, num_channels].
    r   r/   r   r   r0   r   r   N)r5   rd   r?   r   )
r   r   pad_height_widthheight_widthr   r   rB   rC   ro   r   s
             r,   window_unpartitionr     s    " #3M< MFEq!ml&Bk&QU`&`aJ<<M[0,+2M{\gikL  ''1aAq9DDFL$$ZbQL  7F7FUFA 56AACLr-   c                        e Zd ZdZ	 ddededededdf
 fdZ	 dd	e	j                  d
edee	j                  e	j                  f   ee	j                     z  fdZ xZS )VitDetLayerzCThis corresponds to the Block class in the original implementation.r)   drop_path_rater   use_residual_blockrH   Nc                    t         	|           |j                  }|j                  }t	        |t
        t        f      r|n||f}|j                  }t	        |t
        t        f      r|n||f}|d   |d   z  |d   |d   z  f}t        j                  ||j                        | _        t        ||dk(  r|n||f      | _        |dkD  rt        |      nt        j                         | _        t        j                  ||j                        | _        t%        ||t'        ||j(                  z              | _        || _        || _        | j.                  rt1        ||||dz        | _        y y )	Nr   r   )r   )r   r   )r)   r   r   r0   )r)   r   r   r   )r   r   r   r   r   listtupler   r   	LayerNormlayer_norm_epsr   rv   	attentionr   Identityr   r   r   r6   	mlp_ratiomlpr   r   r   residual)
r(   r)   r   r   r   rq   r   r   r   r+   s
            r,   r   zVitDetLayer.__init__  sX    	  &&
#-j4-#HZz[eNf
&&
#-j4-#HZz[eNf
 mz!}4jmzRS}6TU
\\#6+@+@A
([A-=zKQ\C]
 <JC;O7UWU`U`Ub\\#6+@+@A
FSQTW]WgWgQgMhi&"4""4 $'1H	DM #r-   r   r   c                 f   |j                  dddd      }|}| j                  |      }| j                  dkD  r7|j                  d   |j                  d   }}t	        || j                        \  }}| j                  ||      }|d   }|dd  }| j                  dkD  rt        || j                  f      }|| j                  |      z   }|| j                  | j                  | j                  |                  z   }|j                  dddd      }| j                  r| j                  |      }|f|z   }|S )Nr   r0   r   r   )r   )r?   r   r   r5   r   r   r   r   r   r   r   r   )	r(   r   r   shortcutrB   rC   r   self_attention_outputsr   s	            r,   rL   zVitDetLayer.forward  sM   
 &--aAq9 

=1 a)//2M4G4G4JEF.>}dN^N^._+M+!%/ "0 "
 /q1(, a.}d>N>NP`cikpbqrM !4>>-#@@%txx

=@Y7Z([[%--aAq9"" MM-8M "W,r-   )r   r   Fr   )rM   rN   rO   rP   r   r   r6   boolr   r#   rQ   r   rL   rR   rS   s   @r,   r   r     s    M qv!"!49!LO!im!	!L #('||'  ' 
u||U\\)	*U5<<-@	@	'r-   r   c                   f     e Zd Zdeddf fdZ	 	 	 d
dej                  dedededee	z  f
d	Z
 xZS )VitDetEncoderr)   rH   Nc           
         t         |           || _        |j                  }t	        j
                  d|j                  |d      D cg c]  }|j                          }}g }t        |      D ]I  }|j                  t        |||   ||j                  v r|j                  nd||j                  v              K t        j                  |      | _        d| _        y c c}w )Nr   cpu)r   )r   r   r   F)r   r   r)   num_hidden_layersr#   linspacer   itemrangeappendr   window_block_indicesr   residual_block_indicesr   
ModuleListr   gradient_checkpointing)r(   r)   depthr   r   layersir+   s          r,   r   zVitDetEncoder.__init__  s    (( -2NN1f>S>SUZch,ijq!&&(jju 	AMM#1!#4676;V;V6V 2 2\]'(F,I,I'I		 ]]6*
&+# ks   Cr   r   output_hidden_statesreturn_dictc                     |rdnd }|rdnd }t        | j                        D ]'  \  }}|r||fz   } |||      }	|	d   }|s||	d   fz   }) |r||fz   }|st        d |||fD              S t        |||      S )N r   r   c              3   &   K   | ]	  }||  y wr   r  ).0vs     r,   	<genexpr>z(VitDetEncoder.forward.<locals>.<genexpr>4  s     mq_`_lms   last_hidden_stater   
attentions)	enumerater   r   r
   )
r(   r   r   r  r  all_hidden_statesall_self_attentionsr  layer_modulelayer_outputss
             r,   rL   zVitDetEncoder.forward  s     #7BD$5b4(4 		POA|#$58H$H!(8IJM)!,M &9]1=M<O&O#		P   1]4D Dm]4EGZ$[mmm++*
 	
r-   )FFT)rM   rN   rO   r   r   r#   rQ   r   r   r
   rL   rR   rS   s   @r,   r   r     s_    ,| , ,2 #(%* 
||
  
 #	

 
 
	 
r-   r   c                       e Zd ZU eed<   dZdZdZdZg Z	 e
j                         dej                  ej                  z  ej                  z  ddfd	       Zy)
VitDetPreTrainedModelr)   vitdetrG   )imageTmodulerH   Nc                    t        |t        j                  t        j                  f      rct	        j
                  |j                  d| j                  j                         |j                   t	        j                  |j                         yyt        |t        j                        r?t	        j                  |j                         t	        j                  |j                         yt        |t              r7t	        j
                  |j                  d| j                  j                         yt        |t              r| j                  j                   rmt	        j
                  |j"                  d| j                  j                         t	        j
                  |j$                  d| j                  j                         yt        |t&              r%|j(                  |j*                  |j,                  fD ]Q  }t	        j.                  |j                  dd       |j                  2t	        j0                  |j                  d       S |j2                  |j4                  fD ]@  }t	        j                  |j                         t	        j                  |j                         B t	        j                  |j6                  j                         t	        j                  |j6                  j                         yy)zInitialize the weightsr   )r   stdNfan_outrelu)r3   nonlinearityr   )r   r   r}   r&   inittrunc_normal_r   r)   initializer_rangery   zeros_r   ones_r   r%   rv   r   rg   rh   r   r   r   r   kaiming_normal_	constant_r   r   r   )r(   r   r   s      r,   _init_weightsz#VitDetPreTrainedModel._init_weightsE  s    fryy"))45v}}3DKK<Y<YZ{{&FKK( '-KK$JJv}}% 01v99IfIfg0T[[5a5av//ct{{?\?\]v//ct{{?\?\] 89 ,,fllC 2$$U\\	PVW::)NN5::q12 !,,5 (

5<<(EJJ'( KK++,KK))* :r-   )rM   rN   rO   r   __annotations__base_model_prefixmain_input_nameinput_modalitiessupports_gradient_checkpointing_no_split_modulesr#   no_gradr   r}   r&   r   r-  r  r-   r,   r  r  <  sc     $O!&*#U]]_+BII		$9BLL$H +T + +r-   r  c                        e Zd Zdef fdZdefdZe	 	 	 	 ddej                  dz  de
dz  de
dz  d	e
dz  deez  f
d
       Z xZS )VitDetModelr)   c                     t         |   |       || _        t        |      | _        t        |      | _        | j                          y r   )r   r   r)   r   rK   r   encoder	post_init)r(   r)   r+   s     r,   r   zVitDetModel.__init__c  s;     *62$V, 	r-   rH   c                 .    | j                   j                  S r   rK   r'   r   s    r,   get_input_embeddingsz VitDetModel.get_input_embeddingsm      )))r-   NrG   r   r  r  c                 h   ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|t	        d      | j                  |      }| j                  ||||      }|d   }|s	|f|dd z   S t        ||j                  |j                        S )a  
        Examples:

        ```python
        >>> from transformers import VitDetConfig, VitDetModel
        >>> import torch

        >>> config = VitDetConfig()
        >>> model = VitDetModel(config)

        >>> pixel_values = torch.randn(1, 3, 224, 224)

        >>> with torch.no_grad():
        ...     outputs = model(pixel_values)

        >>> last_hidden_states = outputs.last_hidden_state
        >>> list(last_hidden_states.shape)
        [1, 768, 14, 14]
        ```Nz You have to specify pixel_values)r   r  r  r   r   r  )
r)   r   r  use_return_dictr9   rK   r8  r
   r   r  )	r(   rG   r   r  r  kwargsembedding_outputencoder_outputssequence_outputs	            r,   rL   zVitDetModel.forwardp  s    8 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]?@@??<8,,/!5#	 ' 
 *!,#%(;;;-)77&11
 	
r-   )NNNN)rM   rN   rO   r   r   r   r<  r   r#   rQ   r   r   r
   rL   rR   rS   s   @r,   r6  r6  a  s    | *&6 *  -1)-,0#'5
llT)5
  $;5
 #Tk	5

 D[5
 
	 5
 5
r-   r6  zF
    ViTDet backbone, to be used with frameworks like Mask R-CNN.
    )custom_introc                   ~     e Zd Z fdZdefdZe	 	 	 d
dej                  de	dz  de	dz  de	dz  de
f
d	       Z xZS )VitDetBackbonec                     t         |   |       t        |      | _        t	        |      | _        t        |j                  dz         D cg c]  }|j                   c}| _	        | j                          y c c}w )Nr   )r   r   r   rK   r   r8  r  r   r   num_featuresr9  )r(   r)   rp   r+   s      r,   r   zVitDetBackbone.__init__  sd     *62$V,9>v?W?WZ[?[9\]AV//] 	 ^s   A7rH   c                 .    | j                   j                  S r   r;  r   s    r,   r<  z#VitDetBackbone.get_input_embeddings  r=  r-   NrG   r  r   r  c                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }| j	                  |      }| j                  |d||      }|r|j                  n|d   }d}	t        | j                  |      D ]  \  }
}|
| j                  v s|	|fz  }	 |s|r|	f|dd z   }|S |	f|dd z   }|S t        |	|r|j                  nd|j                        S )a  
        Examples:

        ```python
        >>> from transformers import VitDetConfig, VitDetBackbone
        >>> import torch

        >>> config = VitDetConfig()
        >>> model = VitDetBackbone(config)

        >>> pixel_values = torch.randn(1, 3, 224, 224)

        >>> with torch.no_grad():
        ...     outputs = model(pixel_values)

        >>> feature_maps = outputs.feature_maps
        >>> list(feature_maps[-1].shape)
        [1, 768, 14, 14]
        ```NT)r  r   r  r   r  r0   )feature_mapsr   r  )r)   r?  r  r   rK   r8  r   zipstage_namesout_featuresr	   r  )r(   rG   r  r   r  r@  rA  r   r   rK  stager   r   s                r,   rL   zVitDetBackbone.forward  s5   8 &1%<k$++B]B]$8$D $++JjJj 	 2C1N-TXT_T_TqTq??<8,,!%/#	  
 2=--'!*#&t'7'7#G 	0E<)))/	0 #&712;6 M '712;6M%3G'//T))
 	
r-   )NNN)rM   rN   rO   r   r   r<  r   r#   rQ   r   r	   rL   rR   rS   s   @r,   rF  rF    st    *&6 *  -1)-#'<
ll<
 #Tk<
  $;	<

 D[<
 
<
 <
r-   rF  )r6  r  rF  )r   F)3rP   collections.abcr   r7   r#   r    r   r&  activationsr   backbone_utilsr   modeling_layersr   modeling_outputsr	   r
   modeling_utilsr   utilsr   r   configuration_vitdetr   
get_loggerrM   loggerModuler   r:   script_if_tracingra   rt   rv   rQ   r   r   r   r   r   r   r   r   r   r   r   r  r6  rF  __all__r  r-   r,   <module>r^     s        & ! + 9 ? - , . 
		H	%Uryy Up !3 !3H&R;bii ;~U\\ e T V[VbVb  %RYY %bii ,$ryy $N		 $2@>M, M`5
BII 5
p !+O !+ !+H D
' D
 D
N 
K
]$9 K

K
\ Er-   