
    ^jdn                     j   d dl mZ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 dd
l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 ddlmZm Z  ddl!m"Z" ddl#m$Z$  G d dejJ                        Z& G d dejJ                        Z'	 	 d9dejJ                  dejP                  dejP                  dejP                  dejP                  dz  de)dz  de)dee   fdZ* G d d ejJ                        Z+ G d! d"ejJ                        Z, G d# d$e      Z-e G d% d&e             Z. G d' d(ejJ                        Z/e G d) d*e.             Z0 ed+,       G d- d.e.             Z1 ed/,       G d0 d1e.             Z2 ed2,      e G d3 d4e                    Z3 ed5,       G d6 d7e.             Z4g d8Z5y):    )CallableIterable)	dataclassN)nn   )initialization)ACT2FN)create_bidirectional_mask)GradientCheckpointingLayer)BaseModelOutputWithPoolingImageClassifierOutputMaskedImageModelingOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)ModelOutputTransformersKwargsauto_docstring	torch_int)can_return_tuplemerge_with_config_defaults)capture_outputs   )
DeiTConfigc                   `     e Zd ZdZdef fdZdej                  dej                  fdZ xZ	S )DeiTPatchEmbeddingsz
    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.
    configc                    t         |           |j                  }|j                  }t	        |t
              r|n||f}t	        |t
              r|n||f}|d   |d   z  |d   |d   z  z  | _        || _        || _        |j                  | _        t        j                  |j                  |j                  ||      | _        y )Nr   r   )kernel_sizestride)super__init__
image_size
patch_size
isinstancer   num_patchesnum_channelsr   Conv2dhidden_size
projection)selfr   r#   r$   	__class__s       q/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/deit/modeling_deit.pyr"   zDeiTPatchEmbeddings.__init__/   s    &&
&&
#-j(#CZ*V`Ia
#-j(#CZ*V`Ia
&qMZ]:z!}PZ[\P]?]^$$"//))F$7$79K9KYclvw    pixel_valuesreturnc                     |j                   d   }|| j                  k7  rt        d| j                   d| d      | j                  |      j	                  d      j                  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 .   )shaper'   
ValueErrorr*   flatten	transpose)r+   r/   r'   s      r-   forwardzDeiTPatchEmbeddings.forward<   su    #))!,4,,,!../yaI  |,44Q7AA!QGGr.   )
__name__
__module____qualname____doc__r   r"   torchTensorr8   __classcell__r,   s   @r-   r   r   (   s4    xz xHELL HU\\ Hr.   r   c            	            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 )DeiTEmbeddingsa  
    Construct the CLS token, distillation token, position and patch embeddings. Optionally, also the mask token.

    Differences from ViTEmbeddings:
    - Adds a distillation token (for distillation pre-training).
    - Position embeddings include +2 slots (CLS + distillation) instead of +1.
    - interpolate_pos_encoding handles 2 special tokens instead of 1.
    - forward concatenates distillation token and handles position encoding for both.
    r   use_mask_tokenr0   Nc                    t         |           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                   | _        | j                  j"                  | _        t        j                  t	        j
                  dd|j                              | _        y )Nr   r3   )r!   r"   r   	Parameterr=   zerosr)   	cls_token
mask_tokenr   patch_embeddingsr&   position_embeddingsDropouthidden_dropout_probdropoutr$   r#   distillation_token)r+   r   rC   r&   r,   s       r-   r"   zDeiTEmbeddings.__init__Q   s    ekk!Q8J8J&KLQ_",,u{{1a9K9K'LMei 3F ;++77#%<<A{QPVPbPb0c#d zz&"<"<= ++//::"$,,u{{1aASAS/T"Ur.   
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   r3   N      ?r   r   bicubicF)sizemodealign_cornersdim)r4   rJ   r=   jit
is_tracingr$   r   reshapepermuter   
functionalinterpolateviewcat)r+   rO   rP   rQ   r&   num_positionsclass_and_dist_pos_embedpatch_pos_embedrZ   
new_height	new_widthsqrt_num_positionss               r-   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Lr.   r/   bool_masked_posri   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      }|r|| j                  |||      z   }ne|| j                  d   k7  s|| j                  d   k7  r2t        d| d| d| j                  d    d| j                  d    d		      || j                  z   }| j                  |      }|S )
NrS   g      ?r   rY   r   zInput image size (*z) doesn't match model (z).)r4   rI   rV   rH   expand	unsqueezetype_asrG   rN   r=   rb   ri   r#   r5   rJ   rM   )r+   r/   rj   ri   _rP   rQ   rO   
batch_size
seq_lengthmask_tokensmask
cls_tokensdistillation_tokenss                 r-   r8   zDeiTEmbeddings.forward   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
##d&C&CJPVX]&^^J++u8J/J (% 9+,Adooa.@-AE  $d&>&>>J\\*-
r.   )F)NF)r9   r:   r;   r<   r   boolr"   r=   r>   intri   
BoolTensorr8   r?   r@   s   @r-   rB   rB   F   s    Vz V4 VD V&M5<< &M &MUX &M]b]i]i &MV 48).	 ll  ))D0  #'	 
 
 r.   rB   modulequerykeyvalueattention_maskscalingrM   kwargsc                    ||j                  d      dz  }t        j                  ||j                  dd            |z  }|||z   }t        j
                  j                  |dt        j                        j                  |j                        }t        j
                  j                  ||| j                        }t        j                  ||      }	|	j                  dd      j                         }	|	|fS )NrS         r3   r   )rZ   dtype)ptrainingr   )rV   r=   matmulr7   r   r_   softmaxfloat32tor   rM   r   
contiguous)
rz   r{   r|   r}   r~   r   rM   r   attn_weightsattn_outputs
             r-   eager_attention_forwardr      s     **R.D( <<s}}Q':;gEL!#n4==((2U]](SVVW\WbWbcL==((6??([L,,|U3K''1-88:K$$r.   c                        e Zd Zdef fdZ	 d	dej                  dej                  dz  dee   de	ej                  ej                  f   fdZ
 xZS )
DeiTAttentionr   c                 (   t         |           || _        |j                  | _        t	        |d|j
                  |j                  z        | _        |j                  | _        | j                  dz  | _	        d| _
        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j                  |j                  | j                  z  |j
                  d      | _        y )Nhead_dimr   F)biasT)r!   r"   r   num_attention_headsgetattrr)   r   attention_probs_dropout_probattention_dropoutr   	is_causalr   Linearqkv_biasq_projk_projv_projo_projr+   r   r,   s     r-   r"   zDeiTAttention.__init__   s,   #)#=#= 
F4F4F&JdJd4de!'!D!D}}d*ii 2 2F4N4NQUQ^Q^4^eketetuii 2 2F4N4NQUQ^Q^4^eketetuii 2 2F4N4NQUQ^Q^4^eketetuii : :T]] JFL^L^eijr.   Nhidden_statesr~   r   r0   c                    |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }| j                  |      j                  |      j	                  dd      }| j                  |      j                  |      j	                  dd      }t        j                  | j                  j                  t              }	 |	| ||||f| j                  sdn| j                  | j                  d|\  }
} |
j                  g |d j!                         }
| j#                  |
      }
|
|fS )NrS   r   r3           )rM   r   )r4   r   r   ra   r7   r   r   r   get_interfacer   _attn_implementationr   r   r   r   r]   r   r   )r+   r   r~   r   input_shapehidden_shapequery_states
key_statesvalue_statesattention_interfacer   r   s               r-   r8   zDeiTAttention.forward   sK    $))#2.88b8$--8{{=166|DNNqRST[[/44\BLLQPQR
{{=166|DNNqRST(?(M(MKK,,.E)
 %8	%
  $}}C$2H2HLL	%
 	%
!\ *k));;;;FFHkk+.L((r.   N)r9   r:   r;   r   r"   r=   r>   r   r   tupler8   r?   r@   s   @r-   r   r      sf    kz k" /3)||) t+) +,	)
 
u||U\\)	*)r.   r   c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )DeiTMLPr   c                    t         |           || _        t        |j                     | _        t        j                  |j                  |j                        | _
        t        j                  |j                  |j                        | _        y r   )r!   r"   r   r	   
hidden_actactivation_fnr   r   r)   intermediate_sizefc1fc2r   s     r-   r"   zDeiTMLP.__init__   sd    #F$5$5699V//1I1IJ99V55v7I7IJr.   r   r0   c                 l    | j                  |      }| j                  |      }| j                  |      }|S r   )r   r   r   )r+   r   s     r-   r8   zDeiTMLP.forward   s4    /**=9/r.   	r9   r:   r;   r   r"   r=   r>   r8   r?   r@   s   @r-   r   r      s,    Kz KU\\ ell r.   r   c            	            e Zd Zdef fdZ	 d	dej                  dej                  dz  dee   dej                  fdZ	 xZ
S )
	DeiTLayerr   c                 j   t         |           t        |      | _        t	        j
                  |j                  |j                        | _        t	        j
                  |j                  |j                        | _	        t        |      | _        t	        j                  |j                        | _        y )Neps)r!   r"   r   	attentionr   	LayerNormr)   layer_norm_epslayernorm_beforelayernorm_afterr   mlprK   rL   rM   r   s     r-   r"   zDeiTLayer.__init__  sy    &v. "V-?-?VEZEZ [!||F,>,>FDYDYZ6?zz&"<"<=r.   Nr   r~   r   r0   c                     |}| j                  |      } | j                  ||fi |\  }}| j                  |      }||z   }|}| j                  |      }| j	                  |      }| j                  |      }||z   }|S r   )r   r   rM   r   r   )r+   r   r~   r   residualrp   s         r-   r8   zDeiTLayer.forward  s     !--m<)4>>-R6Rq]3%0 !,,];/]3%0r.   r   )r9   r:   r;   r   r"   r=   r>   r   r   r8   r?   r@   s   @r-   r   r     sV    >z > /3|| t+ +,	
 
r.   r   c                        e Zd ZU eed<   dZdZdZdZddgZ	dZ
dZdZdZdZeedZd	Z ej(                         d
ej,                  ej.                  z  ej0                  z  ddf fd       Z xZS )DeiTPreTrainedModelr   deitr/   )imageTrB   r   )r   
attentionsrI   rz   r0   Nc                    t         |   |       t        |t              r|j                  6t        j                  |j                  d| j                  j                         t        j                  |j                  d| j                  j                         |j                  t        j                  |j                         t        |t              rt        j                  |j                         t        j                  |j                         t        j                  |j                         |j                   t        j                  |j                         yyy)zInitialize the weightsNr   )meanstd)r!   _init_weightsr%   rB   rJ   inittrunc_normal_r   initializer_rangerG   rH   zeros_rN   )r+   rz   r,   s     r-   r   z!DeiTPreTrainedModel._init_weights9  s     	f%fn-))5""6#=#=CT[[MjMjkv//ct{{?\?\]  ,F--.fn-KK(()KK223KK112  ,F--. -	 .r.   )r9   r:   r;   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_backend_can_compile_fullgraphr   r   _can_record_outputs_input_embed_layerr=   no_gradr   r   r(   r   r   r?   r@   s   @r-   r   r   &  s    $O!&*#);7N"&!"# ,U]]_/BII		$9BLL$H /T / /r.   r   c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )
DeiTPoolerr   c                     t         |           t        j                  |j                  |j
                        | _        t        |j                     | _	        y r   )
r!   r"   r   r   r)   pooler_output_sizedenser	   
pooler_act
activationr   s     r-   r"   zDeiTPooler.__init__L  s>    YYv1163L3LM
 !2!23r.   r   r0   c                 \    |d d df   }| j                  |      }| j                  |      }|S )Nr   )r   r   )r+   r   first_token_tensorpooled_outputs       r-   r8   zDeiTPooler.forwardQ  s6     +1a40

#566r.   r   r@   s   @r-   r   r   K  s*    4z 4
U\\ ell r.   r   c                        e Zd Zddededef fdZe ed      e	 	 	 	 dde	j                  dz  d	e	j                  dz  d
edz  de	j                  dz  dee   defd                     Z xZS )	DeiTModelFr   add_pooling_layerrC   c                    t         |   |       || _        t        ||      | _        t        j                  t        |j                        D cg c]  }t        |       c}      | _
        t        j                  |j                  |j                        | _        |rt        |      nd| _        | j#                          yc c}w )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.
        )rC   r   N)r!   r"   r   rB   rO   r   
ModuleListrangenum_hidden_layersr   layersr   r)   r   	layernormr   pooler	post_init)r+   r   r   rC   rp   r,   s        r-   r"   zDeiTModel.__init__\  s     	 (OmmfF^F^@_$`1Yv%6$`af&8&8f>S>ST,=j(4	 %as   C)tie_last_hidden_statesNr/   rj   ri   r~   r   r0   c                    | j                   j                  j                  j                  j                  }|j                  |k7  r|j                  |      }| j                  |||      }t        | j                  ||      }|}| j                  D ]  }	 |	||fi |} | 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).
        )rj   ri   )r   inputs_embedsr~   N)last_hidden_statepooler_output)rO   rI   r*   weightr   r   r
   r   r   r   r   r   )r+   r/   rj   ri   r~   r   expected_dtypeembedding_outputr   layersequence_outputr   s               r-   r8   zDeiTModel.forwardl  s      99DDKKQQ/'??>:L??/Tl + 
 3;;*)

 )[[ 	KE!-J6JM	K ..78<8OO4UY)O[hiir.   )TFNNNN)r9   r:   r;   r   rw   r"   r   r   r   r=   r>   ry   r   r   r   r8   r?   r@   s   @r-   r   r   Z  s    z d [_    E2 -13704.2 jllT) j ))D0 j #'+	 j
 t+ j +, j 
$ j  3   jr.   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f fdZee	 	 	 	 ddej                  dz  dej                  dz  de
dej                  dz  dee   d	efd
              Z xZS )DeiTForMaskedImageModelingr   c                 N   t         |   |       t        |dd      | _        t	        j
                  t	        j                  |j                  |j                  dz  |j                  z  d      t	        j                  |j                              | _        | j                          y )NFT)r   rC   r3   r   )in_channelsout_channelsr   )r!   r"   r   r   r   
Sequentialr(   r)   encoder_strider'   PixelShuffledecoderr   r   s     r-   r"   z#DeiTForMaskedImageModeling.__init__  s     fdS	}}II"..#22A58K8KK
 OOF112
 	r.   Nr/   rj   ri   r~   r   r0   c                 h    | 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 requests

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

        >>> 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]
        ```)rj   ri   r~   Nr3   rT   r   r   rS   none)	reductiongh㈵>)lossreconstructionr   r   )r   r   r4   rx   r^   r]   r  r   r#   r$   repeat_interleavern   r   r   r_   l1_losssumr'   r   r   r   )r+   r/   rj   ri   r~   r   outputsr   rq   sequence_lengthr'   rP   rQ   reconstructed_pixel_valuesmasked_im_lossrV   rt   reconstruction_losss                     r-   r8   z"DeiTForMaskedImageModeling.forward  s   L /8dii/
+%=)	/

 /
 "33 *!QR%0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!//))	
 	
r.   )NNFN)r9   r:   r;   r   r"   r   r   r=   r>   ry   rw   r   r   r   r8   r?   r@   s   @r-   r   r     s    z "  -137)..2J
llT)J
 ))D0J
 #'	J

 t+J
 +,J
 
#J
  J
r.   r   a  
    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.

    <Tip>

        Note that it's possible to fine-tune DeiT on higher resolution images than the ones it has been trained on, by
        setting `interpolate_pos_encoding` to `True` in the forward of the model. This will interpolate the pre-trained
        position embeddings to the higher resolution.

    </Tip>
    c                        e Zd Zdef fdZee	 	 	 	 ddej                  dz  dej                  dz  de	dz  dej                  dz  de
e   d	efd
              Z xZS )DeiTForImageClassificationr   c                 .   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     r-   r"   z#DeiTForImageClassification.__init__  ss      ++f>	 OUN_N_bcNc"))F$6$68I8IJikititiv 	r.   Nr/   labelsri   r~   r   r0   c                     | j                   |f||d|}|j                  }|dddddf   }| j                  |      }	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).
        ri   r~   Nr   )r  logitsr   r   )r   r   r  loss_functionr   r   r   r   )r+   r/   r  ri   r~   r   r  r   r   r  r  s              r-   r8   z"DeiTForImageClassification.forward  s    " /8dii/
%=)/
 	/
 "33'1a0/%4%%ffdkkLVLD$!//))	
 	
r.   r   )r9   r:   r;   r   r"   r   r   r=   r>   rw   r   r   r   r8   r?   r@   s   @r-   r  r    s    
z 
  -1&*04.2#
llT)#
 t##
 #'+	#

 t+#
 +,#
 
#
  #
r.   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).
    Nr  
cls_logitsdistillation_logitsr   r   )r9   r:   r;   r<   r  r=   FloatTensorr   r#  r$  r   r   r    r.   r-   r"  r"  B  s}    	 (,FE$++/J!!D(/48**T1859M5**+d2926Je''(4/6r.   r"  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                        e Zd Zdeddf fdZee	 	 	 d
dej                  dz  de	dej                  dz  de
e   def
d	              Z xZS )%DeiTForImageClassificationWithTeacherr   r0   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     r-   r"   z.DeiTForImageClassificationWithTeacher.__init__g  s      ++f>	 AG@Q@QTU@UBIIf((&*;*;<[][f[f[h 	 AG@Q@QTU@UBIIf((&*;*;<[][f[f[h 	$
 	r.   r/   ri   r~   r   c                 
    | j                   |f||d|}|j                  }| j                  |d d dd d f         }| j                  |d d dd d f         }||z   dz  }	t	        |	|||j
                  |j                        S )Nr  r   r   r3   )r  r#  r$  r   r   )r   r   r*  r+  r"  r   r   )
r+   r/   ri   r~   r   r  r   r#  r$  r  s
             r-   r8   z-DeiTForImageClassificationWithTeacher.forwardx  s     /8dii/
%=)/
 	/
 "33((Aq)AB
"::?1aQR7;ST 22a7:! 3!//))
 	
r.   )NFN)r9   r:   r;   r   r"   r   r   r=   r>   rw   r   r   r"  r8   r?   r@   s   @r-   r(  r(  [  s    z d "  -1)..2	
llT)
 #'
 t+	

 +,
 
5
  
r.   r(  )r  r(  r   r   r   )Nr   )6collections.abcr   r   dataclassesr   r=   r    r   r   activationsr	   masking_utilsr
   modeling_layersr   modeling_outputsr   r   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   utils.genericr   r   utils.output_capturingr   configuration_deitr   Moduler   rB   r>   floatr   r   r   r   r   r   r   r   r  r"  r(  __all__r&  r.   r-   <module>r=     s  * / !   & ! 6 9 l l F & O O I 5 *H")) H<`RYY `R !%II%<<% 
% <<	%
 LL4'% T\% % '(%8.)BII .)bbii  * @ !// !/ !/H  4j# 4j 4jn 	^
!4 ^
^
B 2
!4 2
2
j 
 7+ 7 7& 
0
,? 0

0
fr.   