
    qiHv                     :   d Z ddlZddlmZ ddlm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mZmZmZ ddlmZmZ ddlmZ ddlmZmZmZmZmZ ddlm Z m!Z! ddl"m#Z# ddl$m%Z%  ejL                  e'      Z( G d dejR                        Z* G d dejR                        Z+	 	 dAdejR                  dejX                  dejX                  dejX                  dejX                  dz  de-dz  de-dee   fdZ. G d d ejR                        Z/ G d! d"ejR                        Z0 G d# d$ejR                        Z1 G d% d&ejR                        Z2 G d' d(ejR                        Z3 G d) d*e      Z4 G d+ d,ejR                        Z5e G d- d.e             Z6e G d/ d0e6             Z7 G d1 d2ejR                        Z8 ed34       G d5 d6e6             Z9 ed74       G d8 d9e6             Z:e ed:4       G d; d<e                    Z; ed=4       G d> d?e6             Z<g d@Z=y)BzPyTorch DeiT model.    N)Callable)	dataclass)nn   )initialization)ACT2FN)GradientCheckpointingLayer)BaseModelOutputBaseModelOutputWithPoolingImageClassifierOutputMaskedImageModelingOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)ModelOutputTransformersKwargsauto_docstringlogging	torch_int)can_return_tuplemerge_with_config_defaults)capture_outputs   )
DeiTConfigc            	            e Zd ZdZddededdf fdZdej                  de	d	e	dej                  fd
Z
	 	 ddej                  dej                  dz  dedej                  fdZ xZS )DeiTEmbeddingszv
    Construct the CLS token, distillation token, position and patch embeddings. Optionally, also the mask token.
    configuse_mask_tokenreturnNc                    t         |           t        j                  t	        j
                  dd|j                              | _        t        j                  t	        j
                  dd|j                              | _        |r4t        j                  t	        j
                  dd|j                              nd | _	        t        |      | _        | j                  j                  }t        j                  t	        j
                  d|dz   |j                              | _        t        j                  |j                        | _        |j"                  | _        y )Nr      )super__init__r   	Parametertorchzeroshidden_size	cls_tokendistillation_token
mask_tokenDeiTPatchEmbeddingspatch_embeddingsnum_patchesposition_embeddingsDropouthidden_dropout_probdropout
patch_size)selfr   r   r-   	__class__s       X/opt/pipecat/venv/lib/python3.12/site-packages/transformers/models/deit/modeling_deit.pyr#   zDeiTEmbeddings.__init__0   s    ekk!Q8J8J&KL"$,,u{{1aASAS/T"UQ_",,u{{1a9K9K'LMei 3F ;++77#%<<A{QPVPbPb0c#d zz&"<"<= ++    
embeddingsheightwidthc                    |j                   d   dz
  }| j                  j                   d   dz
  }t        j                  j	                         s||k(  r||k(  r| j                  S | j                  ddddf   }| j                  ddddf   }|j                   d   }|| j
                  z  }	|| j
                  z  }
t        |dz        }|j                  d|||      }|j                  dddd      }t        j                  j                  ||	|
fdd	
      }|j                  dddd      j                  dd|      }t        j                  ||fd      S )a  
        This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
        images. This method is also adapted to support torch.jit tracing and 2 class embeddings.

        Adapted from:
        - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
        - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
        r   r!   N      ?r   r   bicubicF)sizemodealign_cornersdim)shaper.   r%   jit
is_tracingr2   r   reshapepermuter   
functionalinterpolateviewcat)r3   r7   r8   r9   r-   num_positionsclass_and_dist_pos_embedpatch_pos_embedrB   
new_height	new_widthsqrt_num_positionss               r5   interpolate_pos_encodingz'DeiTEmbeddings.interpolate_pos_encoding<   sb    !&&q)A-0066q9A= yy##%+*F6UZ?+++#'#;#;ArrE#B 221ab59r"t.
T__,	&}c'9:)11!5GI[]`a)11!Q1=--33i(	 4 
 *11!Q1=BB1b#Nyy2OD!LLr6   pixel_valuesbool_masked_posrR   c                 "   |j                   \  }}}}| j                  |      }|j                         \  }}	}|K| j                  j	                  ||	d      }
|j                  d      j                  |
      }|d|z
  z  |
|z  z   }| j                  j	                  |dd      }| j                  j	                  |dd      }t        j                  |||fd      }| j                  }|r| j                  |||      }||z   }| j                  |      }|S )Nr;   g      ?r   rA   )rC   r,   r>   r*   expand	unsqueezetype_asr(   r)   r%   rK   r.   rR   r1   )r3   rS   rT   rR   _r8   r9   r7   
batch_size
seq_lengthmask_tokensmask
cls_tokensdistillation_tokensposition_embeddings                  r5   forwardzDeiTEmbeddings.forwardd   s    +001fe**<8
$.OO$5!
J&//00ZLK",,R088ED#sTz2[45GGJ^^**:r2>
"55<<ZRPYY
,?LRST
!55#!%!>!>z6SX!Y"44
\\*-
r6   )FNF)__name__
__module____qualname____doc__r   boolr#   r%   TensorintrR   
BoolTensorra   __classcell__r4   s   @r5   r   r   +   s    
,z 
,4 
,D 
,&M5<< &M &MUX &M]b]i]i &MV 48).	ll ))D0 #'	
 
r6   r   c                   Z     e Zd ZdZ fdZdej                  dej                  fdZ xZS )r+   z
    This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
    `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
    Transformer.
    c                    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  }|| _        || _        || _        || _
        t        j                  ||||      | _        y )Nr   r   )kernel_sizestride)r"   r#   
image_sizer2   num_channelsr'   
isinstancecollectionsabcIterabler-   r   Conv2d
projection)r3   r   rq   r2   rr   r'   r-   r4   s          r5   r#   zDeiTPatchEmbeddings.__init__   s    !'!2!2F4E4EJ
$*$7$79K9Kk#-j+//:R:R#SZZdfpYq
#-j+//:R:R#SZZdfpYq
!!}
15*Q-:VW=:XY$$(&))L+:^hir6   rS   r   c                     |j                   \  }}}}|| j                  k7  rt        d      | j                  |      j	                  d      j                  dd      }|S )NzeMake sure that the channel dimension of the pixel values match with the one set in the configuration.r!   r   )rC   rr   
ValueErrorrx   flatten	transpose)r3   rS   rZ   rr   r8   r9   xs          r5   ra   zDeiTPatchEmbeddings.forward   sa    2>2D2D/
L&%4,,,w  OOL)11!4>>q!Dr6   )	rc   rd   re   rf   r#   r%   rh   ra   rk   rl   s   @r5   r+   r+      s)    jELL U\\ r6   r+   modulequerykeyvalueattention_maskscalingr1   kwargsc                    ||j                  d      dz  }t        j                  ||j                  dd            |z  }|||z   }t        j
                  j                  |d      }t        j
                  j                  ||| j                        }t        j                  ||      }	|	j                  dd      j                         }	|	|fS )Nr;         r!   r   rA   )ptrainingr   )
r>   r%   matmulr|   r   rH   softmaxr1   r   
contiguous)
r~   r   r   r   r   r   r1   r   attn_weightsattn_outputs
             r5   eager_attention_forwardr      s     **R.D( <<s}}Q':;gEL!#n4==((2(>L==((6??([L,,|U3K''1-88:K$$r6   c                   z     e Zd Zdef fdZdej                  deej                  ej                  f   fdZ xZ	S )DeiTSelfAttentionr   c                 2   t         |           |j                  |j                  z  dk7  r2t	        |d      s&t        d|j                   d|j                   d      || _        |j                  | _        t        |j                  |j                  z        | _        | j                  | j                  z  | _	        |j                  | _        | j                  dz  | _        d| _        t        j                  |j                  | j                  |j                         | _        t        j                  |j                  | j                  |j                         | _        t        j                  |j                  | j                  |j                         | _        y )	Nr   embedding_sizezThe hidden size z4 is not a multiple of the number of attention heads .r   F)bias)r"   r#   r'   num_attention_headshasattrrz   r   ri   attention_head_sizeall_head_sizeattention_probs_dropout_probdropout_probr   	is_causalr   Linearqkv_biasr   r   r   r3   r   r4   s     r5   r#   zDeiTSelfAttention.__init__   sF    : ::a?PVXhHi"6#5#5"6 7334A7 
 #)#=#= #&v'9'9F<V<V'V#W !558P8PP"??//5YYv1143E3EFOO\
99V//1C1C&//ZYYv1143E3EFOO\
r6   hidden_statesr   c           
         |j                   d   }|d| j                  | j                  f} | j                  |      j                  | j                  dd      } | j                  |      j                  | j                  dd      } | j                  |      j                  | j                  dd      }t        j                  | j                  j                  t              } || |||d | j                  | j                  | j                  sdn| j                         \  }}	|j#                         d d | j$                  fz   }
|j'                  |
      }||	fS )Nr   r;   r   r!           )r   r   r1   )rC   r   r   r   rJ   r|   r   r   r   get_interfacer   _attn_implementationr   r   r   r   r   r>   r   rF   )r3   r   rZ   	new_shape	key_layervalue_layerquery_layerattention_interfacecontext_layerattention_probsnew_context_layer_shapes              r5   ra   zDeiTSelfAttention.forward   sF   "((+
D$<$<d>V>VV	0DHH]+00)<FFq!L	4djj/44i@JJ1aP4djj/44i@JJ1aP(?(M(MKK,,.E)
 *=nnLL#}}C$2C2C	*
& #0"4"4"6s";t?Q?Q>S"S%--.EFo--r6   )
rc   rd   re   r   r#   r%   rh   tuplera   rk   rl   s   @r5   r   r      s:    ]z ](.U\\ .eELL%,,<V6W .r6   r   c                   x     e Zd ZdZdef fdZdej                  dej                  dej                  fdZ xZ	S )DeiTSelfOutputz
    The residual connection is defined in DeiTLayer instead of here (as is the case with other models), due to the
    layernorm applied before each block.
    r   c                     t         |           t        j                  |j                  |j                        | _        t        j                  |j                        | _        y N)	r"   r#   r   r   r'   denser/   r0   r1   r   s     r5   r#   zDeiTSelfOutput.__init__   sB    YYv1163E3EF
zz&"<"<=r6   r   input_tensorr   c                 J    | j                  |      }| j                  |      }|S r   r   r1   r3   r   r   s      r5   ra   zDeiTSelfOutput.forward   s$    

=1]3r6   
rc   rd   re   rf   r   r#   r%   rh   ra   rk   rl   s   @r5   r   r      s=    
>z >
U\\  RWR^R^ r6   r   c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )DeiTAttentionr   c                 b    t         |           t        |      | _        t	        |      | _        y r   )r"   r#   r   	attentionr   outputr   s     r5   r#   zDeiTAttention.__init__  s&    *62$V,r6   r   r   c                 R    | j                  |      \  }}| j                  ||      }|S r   )r   r   )r3   r   self_attn_outputrY   r   s        r5   ra   zDeiTAttention.forward  s,    "nn];!-}=r6   	rc   rd   re   r   r#   r%   rh   ra   rk   rl   s   @r5   r   r     s*    -z -
U\\ ell r6   r   c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )DeiTIntermediater   c                    t         |           t        j                  |j                  |j
                        | _        t        |j                  t              rt        |j                     | _        y |j                  | _        y r   )r"   r#   r   r   r'   intermediate_sizer   rs   
hidden_actstrr   intermediate_act_fnr   s     r5   r#   zDeiTIntermediate.__init__  s]    YYv1163K3KL
f''-'-f.?.?'@D$'-'8'8D$r6   r   r   c                 J    | j                  |      }| j                  |      }|S r   )r   r   )r3   r   s     r5   ra   zDeiTIntermediate.forward  s&    

=100?r6   r   rl   s   @r5   r   r     s*    9z 9U\\ ell r6   r   c                   t     e Zd Zdef fdZdej                  dej                  dej                  fdZ xZS )
DeiTOutputr   c                     t         |           t        j                  |j                  |j
                        | _        t        j                  |j                        | _	        y r   )
r"   r#   r   r   r   r'   r   r/   r0   r1   r   s     r5   r#   zDeiTOutput.__init__%  sB    YYv779K9KL
zz&"<"<=r6   r   r   r   c                 T    | j                  |      }| j                  |      }||z   }|S r   r   r   s      r5   ra   zDeiTOutput.forward*  s.    

=1]3%4r6   r   rl   s   @r5   r   r   $  s8    >z >
U\\  RWR^R^ r6   r   c                   `     e Zd ZdZdef fdZdej                  dej                  fdZ xZ	S )	DeiTLayerz?This corresponds to the Block class in the timm implementation.r   c                 r   t         |           |j                  | _        d| _        t	        |      | _        t        |      | _        t        |      | _	        t        j                  |j                  |j                        | _        t        j                  |j                  |j                        | _        y )Nr   eps)r"   r#   chunk_size_feed_forwardseq_len_dimr   r   r   intermediater   r   r   	LayerNormr'   layer_norm_epslayernorm_beforelayernorm_afterr   s     r5   r#   zDeiTLayer.__init__5  s    '-'E'E$&v.,V4 ( "V-?-?VEZEZ [!||F,>,>FDYDYZr6   r   r   c                     | j                  |      }| j                  |      }||z   }| j                  |      }| j                  |      }| j	                  ||      }|S r   )r   r   r   r   r   )r3   r   hidden_states_normattention_outputlayer_outputs        r5   ra   zDeiTLayer.forward?  si    !22=A>>*<= )=8 ++M:((6 {{<?r6   r   rl   s   @r5   r   r   2  s/    I[z [U\\ ell r6   r   c                   H     e Zd Zdef fdZdej                  defdZ xZ	S )DeiTEncoderr   c                     t         |           || _        t        j                  t        |j                        D cg c]  }t        |       c}      | _        d| _	        y c c}w rb   )
r"   r#   r   r   
ModuleListrangenum_hidden_layersr   layergradient_checkpointing)r3   r   rY   r4   s      r5   r#   zDeiTEncoder.__init__R  sN    ]]uVE]E]?^#_!If$5#_`
&+# $`s   A#r   r   c                 d    t        | j                        D ]  \  }} ||      } t        |      S )N)last_hidden_state)	enumerater   r
   )r3   r   ilayer_modules       r5   ra   zDeiTEncoder.forwardX  s5    (4 	8OA|(7M	8 ??r6   )
rc   rd   re   r   r#   r%   rh   r
   ra   rk   rl   s   @r5   r   r   Q  s)    ,z ,@U\\ @o @r6   r   c                       e Zd ZU eed<   dZdZdZdZdgZ	dZ
dZdZdZeedZ ej$                         dej(                  ej*                  z  ej,                  z  d	d
fd       Zy
)DeiTPreTrainedModelr   deitrS   )imageTr   )r   
attentionsr~   r   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              rt	        j                  |j                         t	        j                  |j                         t	        j                  |j                          |j"                   t	        j                  |j"                         yyy)zInitialize the weightsr   )meanstdN)rs   r   r   rw   inittrunc_normal_weightr   initializer_ranger   zeros_r   ones_r   r(   r.   r)   r*   )r3   r~   s     r5   _init_weightsz!DeiTPreTrainedModel._init_weightsp  s     fryy"))45v}}3DKK<Y<YZ{{&FKK( '-KK$JJv}}%/KK(()KK223KK112  ,F--. -	 0r6   )rc   rd   re   r   __annotations__base_model_prefixmain_input_nameinput_modalitiessupports_gradient_checkpointing_no_split_modules_supports_sdpa_supports_flash_attn_supports_flex_attn_supports_attention_backendr   r   _can_record_outputsr%   no_gradr   r   rw   r   r    r6   r5   r   r   _  s    $O!&*#$N"&"'
 U]]_/BII		$9BLL$H /T / /r6   r   c                        e Zd Zddedededdf fdZdefdZe e	d	      e
	 	 	 dd
ej                  dz  dej                  dz  dedee   def
d                     Z xZS )	DeiTModelFr   add_pooling_layerr   r   Nc                    t         |   |       || _        t        ||      | _        t        |      | _        t        j                  |j                  |j                        | _        |rt        |      nd| _        | j                          y)z
        add_pooling_layer (bool, *optional*, defaults to `True`):
            Whether to add a pooling layer
        use_mask_token (`bool`, *optional*, defaults to `False`):
            Whether to use a mask token for masked image modeling.
        )r   r   N)r"   r#   r   r   r7   r   encoderr   r   r'   r   	layernorm
DeiTPoolerpooler	post_init)r3   r   r  r   r4   s       r5   r#   zDeiTModel.__init__  sm     	 (O"6*f&8&8f>S>ST,=j(4 	r6   c                 .    | j                   j                  S r   )r7   r,   )r3   s    r5   get_input_embeddingszDeiTModel.get_input_embeddings  s    ///r6   )tie_last_hidden_statesrS   rT   rR   r   c                    |t        d      | j                  j                  j                  j                  j
                  }|j
                  |k7  r|j                  |      }| j                  |||      }| j                  |      }|j                  }| j                  |      }| j                  | j                  |      nd}	t        ||	      S )z
        bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
            Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
        Nz You have to specify pixel_valuesrT   rR   )r   pooler_output)rz   r7   r,   rx   r   dtypetor	  r   r
  r  r   )
r3   rS   rT   rR   r   expected_dtypeembedding_outputencoder_outputssequence_outputpooled_outputs
             r5   ra   zDeiTModel.forward  s     ?@@ 99DDKKQQ/'??>:L??/Tl + 
 ,0<<8H+I);;..98<8OO4UY)-'
 	
r6   )TFNNF)rc   rd   re   r   rg   r#   r+   r  r   r   r   r%   rh   rj   r   r   r   ra   rk   rl   s   @r5   r  r    s    z d [_ lp &0&9 0  E2 -137).	 
llT) 
 ))D0 
 #'	 

 +, 
 
$ 
  3   
r6   r  c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )r  r   c                     t         |           t        j                  |j                  |j
                        | _        t        |j                     | _	        y r   )
r"   r#   r   r   r'   pooler_output_sizer   r   
pooler_act
activationr   s     r5   r#   zDeiTPooler.__init__  s>    YYv1163L3LM
 !2!23r6   r   r   c                 \    |d d df   }| j                  |      }| j                  |      }|S )Nr   )r   r   )r3   r   first_token_tensorr  s       r5   ra   zDeiTPooler.forward  s6     +1a40

#566r6   r   rl   s   @r5   r  r    s*    4z 4
U\\ ell r6   r  ad  
    DeiT Model with a decoder on top for masked image modeling, as proposed in [SimMIM](https://huggingface.co/papers/2111.09886).

    <Tip>

    Note that we provide a script to pre-train this model on custom data in our [examples
    directory](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining).

    </Tip>
    )custom_introc                        e Zd Zdeddf fdZee	 	 	 d
dej                  dz  dej                  dz  de
dee   def
d	              Z xZS )DeiTForMaskedImageModelingr   r   Nc                 N   t         |   |       t        |dd      | _        t	        j
                  t	        j                  |j                  |j                  dz  |j                  z  d      t	        j                  |j                              | _        | j                          y )NFT)r  r   r!   r   )in_channelsout_channelsro   )r"   r#   r  r   r   
Sequentialrw   r'   encoder_striderr   PixelShuffledecoderr  r   s     r5   r#   z#DeiTForMaskedImageModeling.__init__  s     fdS	}}II"..#22A58K8KK
 OOF112
 	r6   rS   rT   rR   r   c                 f    | j                   |f||d|}|j                  }|ddddf   }|j                  \  }}}	t        |dz        x}
}|j	                  ddd      j                  ||	|
|      }| j                  |      }d}|| j                  j                  | j                  j                  z  }|j                  d||      }|j                  | j                  j                  d      j                  | j                  j                  d      j                  d      j                         }t        j                  j                  ||d	      }||z  j!                         |j!                         d
z   z  | j                  j"                  z  }t%        |||j&                  |j(                        S )a  
        bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
            Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).

        Examples:
        ```python
        >>> from transformers import AutoImageProcessor, DeiTForMaskedImageModeling
        >>> import torch
        >>> from PIL import Image
        >>> import httpx
        >>> from io import BytesIO

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> with httpx.stream("GET", url) as response:
        ...     image = Image.open(BytesIO(response.read()))

        >>> image_processor = AutoImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224")
        >>> model = DeiTForMaskedImageModeling.from_pretrained("facebook/deit-base-distilled-patch16-224")

        >>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
        >>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
        >>> # create random boolean mask of shape (batch_size, num_patches)
        >>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()

        >>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
        >>> loss, reconstructed_pixel_values = outputs.loss, outputs.reconstruction
        >>> list(reconstructed_pixel_values.shape)
        [1, 3, 224, 224]
        ```r  Nr   r;   r<   r   r!   none)	reductiongh㈵>)lossreconstructionr   r   )r   r   rC   ri   rG   rF   r,  r   rq   r2   repeat_interleaverW   r   r   rH   l1_losssumrr   r   r   r   )r3   rS   rT   rR   r   outputsr  rZ   sequence_lengthrr   r8   r9   reconstructed_pixel_valuesmasked_im_lossr>   r]   reconstruction_losss                    r5   ra   z"DeiTForMaskedImageModeling.forward  s   N /8dii/
+%=/
 	/
 "33 *!QrT'24C4I4I1
O\_c122)11!Q:BB:|]cejk &*\\/%B"&;;))T[[-C-CCD-55b$EO11$++2H2H!L""4;;#9#91=1	  #%--"7"7F`lr"7"s1D8==?488:PTCTUX\XcXcXpXppN(5!//))	
 	
r6   r  )rc   rd   re   r   r#   r   r   r%   rh   rj   rg   r   r   r   ra   rk   rl   s   @r5   r%  r%    s    z d "  -137).	I
llT)I
 ))D0I
 #'	I

 +,I
 
#I
  I
r6   r%  z
    DeiT Model transformer with an image classification head on top (a linear layer on top of the final hidden state of
    the [CLS] token) e.g. for ImageNet.
    c                        e Zd Zdeddf fdZee	 	 	 d
dej                  dz  dej                  dz  de	de
e   def
d	              Z xZS )DeiTForImageClassificationr   r   Nc                 .   t         |   |       |j                  | _        t        |d      | _        |j                  dkD  r*t        j                  |j                  |j                        nt        j                         | _	        | j                          y NF)r  r   )r"   r#   
num_labelsr  r   r   r   r'   Identity
classifierr  r   s     r5   r#   z#DeiTForImageClassification.__init__C  ss      ++f>	 OUN_N_bcNc"))F$6$68I8IJikititiv 	r6   rS   labelsrR   r   c                     | j                   |fd|i|}|j                  }| j                  |dddddf         }d}| | j                  ||| j                  fi |}t        |||j                  |j                        S )a  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).

        Examples:

        ```python
        >>> from transformers import AutoImageProcessor, DeiTForImageClassification
        >>> import torch
        >>> from PIL import Image
        >>> import httpx
        >>> from io import BytesIO

        >>> torch.manual_seed(3)  # doctest: +IGNORE_RESULT
        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> with httpx.stream("GET", url) as response:
        ...     image = Image.open(BytesIO(response.read()))

        >>> # note: we are loading a DeiTForImageClassificationWithTeacher from the hub here,
        >>> # so the head will be randomly initialized, hence the predictions will be random
        >>> image_processor = AutoImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224")
        >>> model = DeiTForImageClassification.from_pretrained("facebook/deit-base-distilled-patch16-224")

        >>> inputs = image_processor(images=image, return_tensors="pt")
        >>> outputs = model(**inputs)
        >>> logits = outputs.logits
        >>> # model predicts one of the 1000 ImageNet classes
        >>> predicted_class_idx = logits.argmax(-1).item()
        >>> print("Predicted class:", model.config.id2label[predicted_class_idx])
        Predicted class: Polaroid camera, Polaroid Land camera
        ```rR   Nr   )r0  logitsr   r   )r   r   r@  loss_functionr   r   r   r   )	r3   rS   rA  rR   r   r5  r  rC  r0  s	            r5   ra   z"DeiTForImageClassification.forwardO  s    V /8dii/
%=/
 /
 "33Aq!9: %4%%ffdkkLVLD$!//))	
 	
r6   r  )rc   rd   re   r   r#   r   r   r%   rh   rg   r   r   r   ra   rk   rl   s   @r5   r;  r;  <  s    
z 
d 
  -1&*).	=
llT)=
 t#=
 #'	=

 +,=
 
=
  =
r6   r;  zC
    Output type of [`DeiTForImageClassificationWithTeacher`].
    c                       e Zd ZU dZdZej                  dz  ed<   dZej                  dz  ed<   dZ	ej                  dz  ed<   dZ
eej                     dz  ed<   dZeej                     dz  ed<   y)+DeiTForImageClassificationWithTeacherOutputaj  
    logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
        Prediction scores as the average of the cls_logits and distillation logits.
    cls_logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
        Prediction scores of the classification head (i.e. the linear layer on top of the final hidden state of the
        class token).
    distillation_logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
        Prediction scores of the distillation head (i.e. the linear layer on top of the final hidden state of the
        distillation token).
    NrC  
cls_logitsdistillation_logitsr   r   )rc   rd   re   rf   rC  r%   FloatTensorr   rG  rH  r   r   r   r  r6   r5   rF  rF    s}    	 (,FE$++/J!!D(/48**T1859M5**+d2926Je''(4/6r6   rF  a  
    DeiT Model transformer with image classification heads on top (a linear layer on top of the final hidden state of
    the [CLS] token and a linear layer on top of the final hidden state of the distillation token) e.g. for ImageNet.

    .. warning::

           This model supports inference-only. Fine-tuning with distillation (i.e. with a teacher) is not yet
           supported.
    c                   z     e Zd Zdeddf fdZee	 	 d	dej                  dz  de	de
e   defd              Z xZS )
%DeiTForImageClassificationWithTeacherr   r   Nc                    t         |   |       |j                  | _        t        |d      | _        |j                  dkD  r*t        j                  |j                  |j                        nt        j                         | _	        |j                  dkD  r*t        j                  |j                  |j                        nt        j                         | _
        | j                          y r=  )r"   r#   r>  r  r   r   r   r'   r?  cls_classifierdistillation_classifierr  r   s     r5   r#   z.DeiTForImageClassificationWithTeacher.__init__  s      ++f>	 AG@Q@QTU@UBIIf((&*;*;<[][f[f[h 	 AG@Q@QTU@UBIIf((&*;*;<[][f[f[h 	$
 	r6   rS   rR   r   c                     | j                   |fd|i|}|j                  }| j                  |d d dd d f         }| j                  |d d dd d f         }||z   dz  }t	        ||||j
                  |j                        S )NrR   r   r   r!   )rC  rG  rH  r   r   )r   r   rM  rN  rF  r   r   )	r3   rS   rR   r   r5  r  rG  rH  rC  s	            r5   ra   z-DeiTForImageClassificationWithTeacher.forward  s     /8dii/
%=/
 /
 "33((Aq)AB
"::?1aQR7;ST 22a7:! 3!//))
 	
r6   rb   )rc   rd   re   r   r#   r   r   r%   rh   rg   r   r   rF  ra   rk   rl   s   @r5   rK  rK    so    z d "  -1).
llT)
 #'
 +,	

 
5
  
r6   rK  )r;  rK  r%  r  r   )Nr   )>rf   collections.abcrt   r   dataclassesr   r%   r    r   r   activationsr   modeling_layersr	   modeling_outputsr
   r   r   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   r   utils.genericr   r   utils.output_capturingr   configuration_deitr   
get_loggerrc   loggerModuler   r+   rh   floatr   r   r   r   r   r   r   r   r   r  r  r%  r;  rF  rK  __all__r  r6   r5   <module>ra     s`     $ !   & ! 9  G & X X I 5 * 
		H	%VRYY Vr")) N !%II%<<% 
% <<	%
 LL4'% T\% % '(%:/.		 /.fRYY $	BII 	ryy  
 
* >@")) @ // / /D :
# :
 :
|  	]
!4 ]
]
@ L
!4 L
L
^ 
7+ 7 7& 
.
,? .

.
br6   