o
    hs                     @   s  d Z ddlZddlmZ ddlmZmZmZ ddlZddl	Zddlm
Z
 ddlmZmZmZ ddlmZmZ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 eeZdZ dZ!g dZ"dZ#dZ$dgZ%eG dd deZ&G dd de
j'Z(G dd de
j'Z)G dd de
j'Z*G dd de
j'Z+G dd de
j'Z,G dd de
j'Z-G dd  d e
j'Z.G d!d" d"e
j'Z/G d#d$ d$e
j'Z0G d%d& d&e
j'Z1G d'd( d(e
j'Z2G d)d* d*eZ3d+Z4d,Z5ed-e4G d.d/ d/e3Z6ed0e4G d1d2 d2e3Z7ed3e4G d4d5 d5e3Z8dS )6z PyTorch LeViT model.    N)	dataclass)OptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )BaseModelOutputWithNoAttention(BaseModelOutputWithPoolingAndNoAttention$ImageClassifierOutputWithNoAttentionModelOutput)PreTrainedModel)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardlogging   )LevitConfigr   zfacebook/levit-128S)r      i  ztabby, tabby catc                   @   sR   e Zd ZU dZdZejed< dZejed< dZ	ejed< dZ
eeej  ed< dS ),LevitForImageClassificationWithTeacherOutputa  
    Output type of [`LevitForImageClassificationWithTeacher`].

    Args:
        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).
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
            shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
            plus the initial embedding outputs.
    Nlogits
cls_logitsdistillation_logitshidden_states)__name__
__module____qualname____doc__r   torchFloatTensor__annotations__r   r   r   r   r    r#   r#   ^/var/www/html/ai/venv/lib/python3.10/site-packages/transformers/models/levit/modeling_levit.pyr   8   s   
 r   c                       s,   e Zd ZdZ	d fdd	Zdd Z  ZS )LevitConvEmbeddingsz[
    LeViT Conv Embeddings with Batch Norm, used in the initial patch embedding layer.
    r   c	           	   
      s6   t    tj|||||||dd| _t|| _d S )NF)dilationgroupsbias)super__init__r   Conv2dconvolutionBatchNorm2d
batch_norm)	selfin_channelsout_channelskernel_sizestridepaddingr&   r'   bn_weight_init	__class__r#   r$   r*   W   s
   
zLevitConvEmbeddings.__init__c                 C   s   |  |}| |}|S N)r,   r.   )r/   
embeddingsr#   r#   r$   forward`      

zLevitConvEmbeddings.forward)r   r   r   r   r   r   r   r*   r:   __classcell__r#   r#   r6   r$   r%   R   s
    	r%   c                       (   e Zd ZdZ fddZdd Z  ZS )LevitPatchEmbeddingsz
    LeViT patch embeddings, for final embeddings to be passed to transformer blocks. It consists of multiple
    `LevitConvEmbeddings`.
    c                    s   t    t|j|jd d |j|j|j| _t	
 | _t|jd d |jd d |j|j|j| _t	
 | _t|jd d |jd d |j|j|j| _t	
 | _t|jd d |jd |j|j|j| _|j| _d S )Nr            )r)   r*   r%   num_channelshidden_sizesr2   r3   r4   embedding_layer_1r   	Hardswishactivation_layer_1embedding_layer_2activation_layer_2embedding_layer_3activation_layer_3embedding_layer_4r/   configr6   r#   r$   r*   l   s"   

$
$
 zLevitPatchEmbeddings.__init__c                 C   st   |j d }|| jkrtd| |}| |}| |}| |}| |}| |}| 	|}|
dddS )Nr   zeMake sure that the channel dimension of the pixel values match with the one set in the configuration.rB   )shaperC   
ValueErrorrE   rG   rH   rI   rJ   rK   rL   flatten	transpose)r/   pixel_valuesrC   r9   r#   r#   r$   r:      s   








zLevitPatchEmbeddings.forwardr<   r#   r#   r6   r$   r?   f   s    r?   c                       s&   e Zd Zd fdd	Zdd Z  ZS )MLPLayerWithBNr   c                    s,   t    tj||dd| _t|| _d S )NF)in_featuresout_featuresr(   )r)   r*   r   LinearlinearBatchNorm1dr.   )r/   	input_dim
output_dimr5   r6   r#   r$   r*      s   
zMLPLayerWithBN.__init__c                 C   s&   |  |}| |dd|}|S )Nr   r   )rX   r.   rQ   
reshape_asr/   hidden_stater#   r#   r$   r:      s   
zMLPLayerWithBN.forward)r   r   r   r   r*   r:   r=   r#   r#   r6   r$   rT      s    rT   c                       s$   e Zd Z fddZdd Z  ZS )LevitSubsamplec                       t    || _|| _d S r8   )r)   r*   r3   
resolution)r/   r3   rb   r6   r#   r$   r*         

zLevitSubsample.__init__c                 C   sL   |j \}}}||| j| j|d d d d | jd d | jf |d|}|S )N)rO   viewrb   r3   reshape)r/   r^   
batch_size_channelsr#   r#   r$   r:      s   
zLevitSubsample.forwardr_   r#   r#   r6   r$   r`      s    r`   c                       B   e Zd Z fddZe d
 fdd	Zdd Zdd	 Z  Z	S )LevitAttentionc                    sB  t    || _|d | _|| _|| _|| | || d  | _|| | | _t|| j| _	t
 | _t| j|dd| _ttt|t|}t|}i g }}	|D ],}
|D ]'}t|
d |d  t|
d |d  f}||vrwt|||< |	||  qWqSi | _tj
t|t|| _| jdt|	||dd d S )	N      rB   r   )r5   r   attention_bias_idxsF
persistent)r)   r*   num_attention_headsscalekey_dimattention_ratioout_dim_keys_valuesout_dim_projectionrT   queries_keys_valuesr   rF   
activation
projectionlist	itertoolsproductrangelenabsappendattention_bias_cacher    	Parameterzerosattention_biasesregister_buffer
LongTensorre   )r/   rD   rr   rp   rs   rb   points
len_pointsattention_offsetsindicesp1p2offsetr6   r#   r$   r*      s2   



(
zLevitAttention.__init__Tc                    (   t  | |r| jri | _d S d S d S r8   r)   trainr   r/   moder6   r#   r$   r         

zLevitAttention.trainc                 C   P   | j r| jd d | jf S t|}|| jvr#| jd d | jf | j|< | j| S r8   trainingr   rm   strr   r/   device
device_keyr#   r#   r$   get_attention_biases      

z#LevitAttention.get_attention_biasesc           
      C   s   |j \}}}| |}|||| jdj| j| j| j| j gdd\}}}|dddd}|dddd}|dddd}||dd | j	 | 
|j }	|	jdd}	|	| dd||| j}| | |}|S Nrd   r
   dimr   rB   r   )rO   rv   re   rp   splitrr   rs   permuterR   rq   r   r   softmaxrf   ru   rx   rw   )
r/   r^   rg   
seq_lengthrh   rv   querykeyvalue	attentionr#   r#   r$   r:      s   
"zLevitAttention.forwardT
r   r   r   r*   r    no_gradr   r   r:   r=   r#   r#   r6   r$   rk      s    	rk   c                       rj   )LevitAttentionSubsamplec	                    s  t    || _|d | _|| _|| _|| | ||  | _|| | | _|| _t	|| j| _
t||| _t	||| | _t | _t	| j|| _i | _ttt|t|}	ttt|t|}
t|	t|
}}i g }}|
D ]>}|	D ]9}d}t|d | |d  |d d  t|d | |d  |d d  f}||vrt|||< |||  qxqttjt|t|| _| jdt| ||dd d S )Nrl   r   r   rB   rm   Frn   )!r)   r*   rp   rq   rr   rs   rt   ru   resolution_outrT   keys_valuesr`   queries_subsamplequeriesr   rF   rw   rx   r   ry   rz   r{   r|   r}   r~   r   r    r   r   r   r   r   re   )r/   rZ   r[   rr   rp   rs   r3   resolution_inr   r   points_r   len_points_r   r   r   r   sizer   r6   r#   r$   r*      s<   



H
z LevitAttentionSubsample.__init__Tc                    r   r8   r   r   r6   r#   r$   r     r   zLevitAttentionSubsample.trainc                 C   r   r8   r   r   r#   r#   r$   r     r   z,LevitAttentionSubsample.get_attention_biasesc           	      C   s   |j \}}}| |||| jdj| j| j| j gdd\}}|dddd}|dddd}| | 	|}||| j
d | j| jdddd}||dd | j | |j }|jdd}|| dd|d| j}| | |}|S r   )rO   r   re   rp   r   rr   rs   r   r   r   r   rR   rq   r   r   r   rf   ru   rx   rw   )	r/   r^   rg   r   rh   r   r   r   r   r#   r#   r$   r:   '  s"   "zLevitAttentionSubsample.forwardr   r   r#   r#   r6   r$   r      s    -	r   c                       r>   )LevitMLPLayerzE
    MLP Layer with `2X` expansion in contrast to ViT with `4X`.
    c                    s0   t    t||| _t | _t||| _d S r8   )r)   r*   rT   	linear_upr   rF   rw   linear_down)r/   rZ   
hidden_dimr6   r#   r$   r*   B  s   

zLevitMLPLayer.__init__c                 C   s"   |  |}| |}| |}|S r8   )r   rw   r   r]   r#   r#   r$   r:   H  s   


zLevitMLPLayer.forwardr<   r#   r#   r6   r$   r   =  s    r   c                       r>   )LevitResidualLayerz"
    Residual Block for LeViT
    c                    ra   r8   )r)   r*   module	drop_rate)r/   r   r   r6   r#   r$   r*   T  rc   zLevitResidualLayer.__init__c                 C   sn   | j r.| jdkr.tj|ddd|jd}|| jd| j  }|| 	||  }|S || 	| }|S )Nr   r   )r   )
r   r   r    randr   r   ge_divdetachr   )r/   r^   rndr#   r#   r$   r:   Y  s   zLevitResidualLayer.forwardr<   r#   r#   r6   r$   r   O      r   c                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )
LevitStagezP
    LeViT Stage consisting of `LevitMLPLayer` and `LevitAttention` layers.
    c                    sD  t    g | _|| _|
| _t|D ])}| jtt|||||
| jj	 |dkr;|| }| jtt
||| jj	 q|	d dkr| jd |	d  d | _| jt| jj||d  |	d |	d |	d |	d |
| jd | j| _|	d dkr| jj|d  |	d  }| jtt
| jj|d  || jj	 t| j| _d S )	Nr   	Subsampler      rB   r
   )rr   rp   rs   r3   r   r   rA   )r)   r*   layersrN   r   r|   r   r   rk   drop_path_rater   r   r   rD   r   
ModuleList)r/   rN   idxrD   rr   depthsrp   rs   	mlp_ratiodown_opsr   rh   r   r6   r#   r$   r*   i  sN   
zLevitStage.__init__c                 C   s   | j S r8   )r   )r/   r#   r#   r$   get_resolution  s   zLevitStage.get_resolutionc                 C   s   | j D ]}||}q|S r8   )r   )r/   r^   layerr#   r#   r$   r:     r;   zLevitStage.forward)r   r   r   r   r*   r   r:   r=   r#   r#   r6   r$   r   d  s
    7r   c                       s*   e Zd ZdZ fddZdddZ  ZS )	LevitEncoderzC
    LeViT Encoder consisting of multiple `LevitStage` stages.
    c                    s   t    || _| jj| jj }g | _| jjdg tt	|j
D ].}t|||j| |j| |j
| |j| |j| |j| |j| |
}| }| j| q"t| j| _d S )N )r)   r*   rN   
image_size
patch_sizestagesr   r   r|   r}   r   r   rD   rr   rp   rs   r   r   r   r   )r/   rN   rb   	stage_idxstager6   r#   r$   r*     s*   
zLevitEncoder.__init__FTc                 C   sb   |rdnd }| j D ]}|r||f }||}q	|r||f }|s+tdd ||fD S t||dS )Nr#   c                 s   s    | ]	}|d ur|V  qd S r8   r#   ).0vr#   r#   r$   	<genexpr>  s    z'LevitEncoder.forward.<locals>.<genexpr>)last_hidden_stater   )r   tupler   )r/   r^   output_hidden_statesreturn_dictall_hidden_statesr   r#   r#   r$   r:     s   



zLevitEncoder.forward)FTr<   r#   r#   r6   r$   r     s    r   c                       r>   )LevitClassificationLayerz$
    LeViT Classification Layer
    c                    s(   t    t|| _t||| _d S r8   )r)   r*   r   rY   r.   rW   rX   )r/   rZ   r[   r6   r#   r$   r*     s   
z!LevitClassificationLayer.__init__c                 C   s   |  |}| |}|S r8   )r.   rX   )r/   r^   r   r#   r#   r$   r:     r;   z LevitClassificationLayer.forwardr<   r#   r#   r6   r$   r     r   r   c                   @   s$   e Zd ZdZeZdZdZdd ZdS )LevitPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    levitrS   c                 C   sz   t |tjtjfr#|jjjd| jjd |j	dur!|j	j
  dS dS t |tjtjfr;|j	j
  |jjd dS dS )zInitialize the weightsg        )meanstdNg      ?)
isinstancer   rW   r+   weightdatanormal_rN   initializer_ranger(   zero_rY   r-   fill_)r/   r   r#   r#   r$   _init_weights  s   
z"LevitPreTrainedModel._init_weightsN)	r   r   r   r   r   config_classbase_model_prefixmain_input_namer   r#   r#   r#   r$   r     s    r   aG  
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`LevitConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
aC  
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`LevitImageProcessor.__call__`] for details.

        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
zNThe bare Levit model outputting raw features without any specific head on top.c                       sj   e Zd Z fddZeeeeee	de
d			ddejdee dee d	eeef fd
dZ  ZS )
LevitModelc                    s2   t  | || _t|| _t|| _|   d S r8   )r)   r*   rN   r?   patch_embeddingsr   encoder	post_initrM   r6   r#   r$   r*     s
   

zLevitModel.__init__vision)
checkpointoutput_typer   modalityexpected_outputNrS   r   r   returnc                 C   s   |d ur|n| j j}|d ur|n| j j}|d u rtd| |}| j|||d}|d }|jdd}|s?||f|dd   S t|||jdS )Nz You have to specify pixel_valuesr   r   r   r   r   )r   pooler_outputr   )	rN   r   use_return_dictrP   r   r   r   r   r   )r/   rS   r   r   r9   encoder_outputsr   pooled_outputr#   r#   r$   r:   $  s(   
zLevitModel.forwardNNN)r   r   r   r*   r   LEVIT_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOC_EXPECTED_OUTPUT_SHAPEr    r!   r   boolr   r   r:   r=   r#   r#   r6   r$   r     s,    	
r   z
    Levit Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    c                       st   e Zd Z fddZeeeeee	e
d				ddejdeej dee dee d	eeef f
d
dZ  ZS )LevitForImageClassificationc                    sX   t  | || _|j| _t|| _|jdkr t|jd |jntj	
 | _|   d S Nr   rd   )r)   r*   rN   
num_labelsr   r   r   rD   r    r   Identity
classifierr   rM   r6   r#   r$   r*   X  s   

z$LevitForImageClassification.__init__r   r   r   r   NrS   labelsr   r   r   c                 C   sb  |dur|n| j j}| j|||d}|d }|d}| |}d}|dur| j jdu rP| jdkr6d| j _n| jdkrL|jtj	ksG|jtj
krLd| j _nd| j _| j jdkrnt }	| jdkrh|	| | }n+|	||}n%| j jdkrt }	|	|d| j|d}n| j jdkrt }	|	||}|s|f|d	d  }
|dur|f|
 S |
S t|||jd
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).
        Nr   r   r   
regressionsingle_label_classificationmulti_label_classificationrd   rB   )lossr   r   )rN   r   r   r   r  problem_typer  dtyper    longintr	   squeezer   re   r   r   r   )r/   rS   r  r   r   outputssequence_outputr   r  loss_fctoutputr#   r#   r$   r:   h  s@   



"


z#LevitForImageClassification.forward)NNNN)r   r   r   r*   r   r   r   _IMAGE_CLASS_CHECKPOINTr   r   _IMAGE_CLASS_EXPECTED_OUTPUTr    r!   r   r   r   r   r   r:   r=   r#   r#   r6   r$   r  P  s0    
r  ap  
    LeViT Model transformer with image classification heads on top (a linear layer on top of the final hidden state 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                       sh   e Zd Z fddZeeeeee	e
d			ddejdee dee deeef fd	d
Z  ZS )&LevitForImageClassificationWithTeacherc                    s   t  | || _|j| _t|| _|jdkr t|jd |jntj	
 | _|jdkr4t|jd |jntj	
 | _|   d S r  )r)   r*   rN   r  r   r   r   rD   r    r   r  r  classifier_distillr   rM   r6   r#   r$   r*     s   


z/LevitForImageClassificationWithTeacher.__init__r  NrS   r   r   r   c           
      C   s   |d ur|n| j j}| j|||d}|d }|d}| || |}}|| d }|s;|||f|dd   }	|	S t||||jdS )Nr   r   r   rB   )r   r   r   r   )rN   r   r   r   r  r  r   r   )
r/   rS   r   r   r  r  r   distill_logitsr   r  r#   r#   r$   r:     s   
z.LevitForImageClassificationWithTeacher.forwardr   )r   r   r   r*   r   r   r   r  r   r   r  r    r!   r   r   r   r   r:   r=   r#   r#   r6   r$   r    s*    

r  )9r   rz   dataclassesr   typingr   r   r   r    torch.utils.checkpointr   torch.nnr   r   r	   modeling_outputsr   r   r   r   modeling_utilsr   utilsr   r   r   r   configuration_levitr   
get_loggerr   loggerr   r   r   r  r  #LEVIT_PRETRAINED_MODEL_ARCHIVE_LISTr   Moduler%   r?   rT   r`   rk   r   r   r   r   r   r   r   LEVIT_START_DOCSTRINGr   r   r  r  r#   r#   r#   r$   <module>   sf   
,>SE.5N	