o
    Zh                 	   @   s  d Z ddlZddlZddlZddlmZ ddlmZm	Z	m
Z
mZ ddlZddlZddlmZmZ ddlmZmZmZ ddlmZ dd	lmZmZmZmZmZmZ dd
lmZ ddlm Z m!Z!m"Z" ddl#m$Z$m%Z%m&Z& ddl'm(Z( ddl)m*Z* e%+e,Z-g dZ.dZ/dZ0eG dd deZ1dSdejde2de3dejfddZ4G dd dej5Z6G dd  d ej5Z7G d!d" d"ej5Z8G d#d$ d$ej5Z9G d%d& d&e9Z:G d'd( d(ej5Z;e9e:d)Z<G d*d+ d+ej5Z=G d,d- d-ej5Z>G d.d/ d/ej5Z?G d0d1 d1ej5Z@G d2d3 d3ej5ZAG d4d5 d5ej5ZBe$G d6d7 d7eZCe$G d8d9 d9eCZDG d:d; d;ej5ZEe$d<d=G d>d? d?eCZFe$d@d=G dAdB dBeCZGG dCdD dDej5ZHG dEdF dFej5ZIG dGdH dHej5ZJG dIdJ dJej5ZKG dKdL dLej5ZLe$G dMdN dNeCZMe$dOd=G dPdQ dQeCe(ZNg dRZOdS )TzPyTorch BEiT model.    N)	dataclass)ListOptionalTupleUnion)Tensornn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)BackboneOutputBaseModelOutputBaseModelOutputWithPoolingImageClassifierOutputMaskedLMOutputSemanticSegmenterOutput)PreTrainedModel)#compile_compatible_method_lru_cache find_pruneable_heads_and_indicesprune_linear_layer)auto_docstringlogging	torch_int)BackboneMixin   )
BeitConfig)r      i   zmicrosoft/beit-base-patch16-224ztabby, tabby catc                   @   s   e Zd ZdZdS )BeitModelOutputWithPoolinga  
    Class for outputs of [`BeitModel`].

    Args:
        last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
            Sequence of hidden-states at the output of the last layer of the model.
        pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`):
            Average of the last layer hidden states of the patch tokens (excluding the *[CLS]* token) if
            *config.use_mean_pooling* is set to True. If set to False, then the final hidden state of the *[CLS]* token
            will be returned.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
            shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
    N)__name__
__module____qualname____doc__ r$   r$   U/var/www/auris/lib/python3.10/site-packages/transformers/models/beit/modeling_beit.pyr   8   s    r           Finput	drop_probtrainingreturnc                 C   sd   |dks|s| S d| }| j d fd| jd   }|tj|| j| jd }|  | || }|S )aF  
    Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).

    Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
    however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
    See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
    layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
    argument.
    r&   r   r   r   )dtypedevice)shapendimtorchZrandr,   r-   Zfloor_div)r'   r(   r)   Z	keep_probr.   Zrandom_tensoroutputr$   r$   r%   	drop_pathR   s   
r3   c                       sT   e Zd ZdZddee ddf fddZdejdejfdd	Z	de
fd
dZ  ZS )BeitDropPathzXDrop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).Nr(   r*   c                    s   t    || _d S N)super__init__r(   )selfr(   	__class__r$   r%   r7   i   s   

zBeitDropPath.__init__hidden_statesc                 C   s   t || j| jS r5   )r3   r(   r)   r8   r;   r$   r$   r%   forwardm   s   zBeitDropPath.forwardc                 C   s   d | jS )Nzp={})formatr(   r8   r$   r$   r%   
extra_reprp   s   zBeitDropPath.extra_reprr5   )r    r!   r"   r#   r   floatr7   r0   r   r=   strr@   __classcell__r$   r$   r9   r%   r4   f   s
    r4   c                	       sv   e Zd ZdZdeddf fddZdejded	edejfd
dZ			ddejde
ej de
e dejfddZ  ZS )BeitEmbeddingszc
    Construct the CLS token, position and patch embeddings. Optionally, also the mask token.

    configr*   Nc                    s   t    ttdd|j| _|jr!ttdd|j| _	nd | _	t
|| _|j| _t|jtjjr8|jn|j|jf| _| jj}|jrUttd|d |j| _nd | _t|j| _d S )Nr   )r6   r7   r   	Parameterr0   zeroshidden_size	cls_tokenZuse_mask_token
mask_tokenBeitPatchEmbeddingspatch_embeddings
patch_size
isinstance
image_sizecollectionsabcIterablenum_patchesZ use_absolute_position_embeddingsposition_embeddingsDropouthidden_dropout_probdropout)r8   rE   rS   r9   r$   r%   r7   |   s    


zBeitEmbeddings.__init__
embeddingsheightwidthc                 C   s   |j d d }| jj d d }tj s||kr||kr| jS | jddddf }| jddddf }|j d }|| j }	|| j }
t|d }|d|||}|dddd}t	j
j||	|
fdd	d
}|dddddd|}tj||fd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.

        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   Ng      ?r   r      ZbicubicFsizemodealign_cornersdim)r.   rT   r0   Zjit
is_tracingrM   r   reshapepermuter   
functionalinterpolateviewcat)r8   rX   rY   rZ   rS   Znum_positionsZclass_pos_embedZpatch_pos_embedrb   
new_height	new_widthZsqrt_num_positionsr$   r$   r%   interpolate_pos_encoding   s(   



z'BeitEmbeddings.interpolate_pos_encodingpixel_valuesbool_masked_posrl   c                 C   s   | j d ur|d urtd |j\}}}}| |\}\}}	| \}
}}|d urC| j|
|d}|d	|}|d|  ||  }| j
|
dd}tj||fdd}| j d urb|| ||| }| |}|||	ffS )Nz`interpolate_pos_encoding` argument has no effect for BEiTEmbeddings, embeddings are always interpolated to the input image size. The argument will be removed in transformers v4.51.0.r[   r   ra   )rT   warningswarnr.   rL   r^   rJ   expand	unsqueezeZtype_asrI   r0   ri   rl   rW   )r8   rm   rn   rl   _rY   rZ   rX   patch_heightpatch_width
batch_sizeZseq_lenZmask_tokenswZ
cls_tokensr$   r$   r%   r=      s"   

zBeitEmbeddings.forwardNN)r    r!   r"   r#   r   r7   r0   r   intrl   r   
BoolTensorboolr=   rC   r$   r$   r9   r%   rD   v   s    +rD   c                       s6   e Zd ZdZ fddZdejdejfddZ  ZS )rK   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                    s   t    |j|j}}|j|j}}t|tjj	r|n||f}t|tjj	r)|n||f}|d |d  |d |d   }|d |d  |d |d  f}|| _|| _|| _|| _
|| _tj||||d| _d S )Nr   r   kernel_sizeZstride)r6   r7   rO   rM   num_channelsrH   rN   rP   rQ   rR   rS   patch_shaper   Conv2d
projection)r8   rE   rO   rM   r~   rH   rS   r   r9   r$   r%   r7      s   
  zBeitPatchEmbeddings.__init__rm   r*   c           	      C   s^   |j \}}}}|| jkrtd| |}|j d |j d }}|ddd}|||ffS )NzeMake sure that the channel dimension of the pixel values match with the one set in the configuration.r\   r   r   )r.   r~   
ValueErrorr   flatten	transpose)	r8   rm   rv   r~   rY   rZ   rX   rt   ru   r$   r$   r%   r=      s   

zBeitPatchEmbeddings.forward)	r    r!   r"   r#   r7   r0   r   r=   rC   r$   r$   r9   r%   rK      s    rK   c                          e Zd Zddedee ddf fddZdd Z							dd
ej	deej	 de
deej	 de
deee  deeej	 eej	ej	f f fddZ  ZS )BeitSelfAttentionNrE   window_sizer*   c                    s   t    || _|j|j dkr"t|ds"td|j d|j d|j| _t|j|j | _| j| j | _	t
|j| j	| _t
j|j| j	dd| _t
|j| j	| _t
|j| _t|| _| jrkt||d| _d S d S )	Nr   Zembedding_sizezThe hidden size z4 is not a multiple of the number of attention heads .F)biasr   )r6   r7   rE   rH   num_attention_headshasattrr   ry   attention_head_sizeall_head_sizer   LinearquerykeyvaluerU   attention_probs_dropout_probrW   r{   has_relative_position_biasBeitRelativePositionBiasrelative_position_biasr8   rE   r   r9   r$   r%   r7     s&   


zBeitSelfAttention.__init__c                 C   s6   |  d d | j| jf }|j| }|ddddS )Nr[   r   r\   r   r   )r^   r   r   rh   re   )r8   xZnew_x_shaper$   r$   r%   transpose_for_scores  s   
z&BeitSelfAttention.transpose_for_scoresFr;   	head_maskoutput_attentionsr   rl   
resolutionc                 C   s.  |  |}| | |}| | |}	| |}
t|
|dd}|t| j	 }| j
rL|\}}|| jj || jj f}|| j|||jd d }|d urT|| }tjj|dd}| |}|d uri|| }t||	}|dddd }| d d | jf }|j| }|r||f}|S |f}|S )	Nr[   r   dim_sizera   r   r\   r   )r   r   r   r   r0   matmulr   mathsqrtr   r   rE   rM   r   r.   r   rf   ZsoftmaxrW   re   
contiguousr^   r   rh   )r8   r;   r   r   r   rl   r   mixed_query_layer	key_layervalue_layerquery_layerZattention_scoresrY   rZ   r   Zattention_probscontext_layernew_context_layer_shapeoutputsr$   r$   r%   r=     s4   
	


zBeitSelfAttention.forwardr5   NFNFN)r    r!   r"   r   r   tupler7   r   r0   r   r{   r   ry   r   r=   rC   r$   r$   r9   r%   r     s.     
r   c                       sv   e Zd Z					ddejdeej dedeej dedeee  d	e	eej eejejf f f fd
dZ
  ZS )BeitSdpaSelfAttentionNFr;   r   r   r   rl   r   r*   c              	      s8  |s|d urt d t j||||||dS | |}| | |}| | |}	| |}
d }| jrQ|\}}|| j	j
 || j	j
 f}| j|||jd d}|d ur`|d u r\|}n||7 }dt| j }tjjj|
||	|| jrw| j	jndd|d}|dd	dd
 }| d d | jf }|j| }|d fS )Na  `BeitSdpaSelfAttention` is used but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True` or `head_mask`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.)r;   r   r   r   rl   r   r   r   r&   F)Z	attn_maskZ	dropout_pZ	is_causalscaler   r\   r   r   )loggerZwarning_oncer6   r=   r   r   r   r   r   rE   rM   r   r.   r   r   r   r0   r   rf   Zscaled_dot_product_attentionr)   r   re   r   r^   r   rh   )r8   r;   r   r   r   rl   r   r   r   r   r   Z	attn_biasrY   rZ   r   Zscalingr   r   r9   r$   r%   r=   V  sR   	
	
	
zBeitSdpaSelfAttention.forwardr   )r    r!   r"   r0   r   r   r{   r   ry   r   r=   rC   r$   r$   r9   r%   r   U  s*    
r   c                       sH   e Zd ZdZdeddf fddZddejdejdejfd	d
Z  Z	S )BeitSelfOutputz
    The residual connection is defined in BeitLayer instead of here (as is the case with other models), due to the
    layernorm applied before each block.
    rE   r*   Nc                    s.   t    t|j|j| _t|j| _d S r5   )	r6   r7   r   r   rH   denserU   rV   rW   r8   rE   r9   r$   r%   r7        
zBeitSelfOutput.__init__r;   input_tensorc                 C      |  |}| |}|S r5   r   rW   )r8   r;   r   gammar$   r$   r%   r=        

zBeitSelfOutput.forwardr5   )
r    r!   r"   r#   r   r7   r0   r   r=   rC   r$   r$   r9   r%   r     s    &r   )eagerZsdpac                       r   )BeitAttentionNrE   r   r*   c                    s4   t    t|j ||d| _t|| _t | _d S )Nr   )	r6   r7   BEIT_SELF_ATTENTION_CLASSESZ_attn_implementation	attentionr   r2   setpruned_headsr   r9   r$   r%   r7     s   

zBeitAttention.__init__c                 C   s   t |dkrd S t|| jj| jj| j\}}t| jj|| j_t| jj|| j_t| jj	|| j_	t| j
j|dd| j
_| jjt | | j_| jj| jj | j_| j|| _d S )Nr   r   ra   )lenr   r   r   r   r   r   r   r   r   r2   r   r   union)r8   headsindexr$   r$   r%   prune_heads  s   zBeitAttention.prune_headsFr;   r   r   r   rl   r   c           
      C   s:   |  ||||||}| |d |}|f|dd   }	|	S )Nr   r   )r   r2   )
r8   r;   r   r   r   rl   r   Zself_outputsattention_outputr   r$   r$   r%   r=     s   	zBeitAttention.forwardr5   r   )r    r!   r"   r   r   r   r7   r   r0   r   r{   r   ry   r   r=   rC   r$   r$   r9   r%   r     s.     
r   c                       <   e Zd Zdeddf fddZdejdejfddZ  ZS )	BeitIntermediaterE   r*   Nc                    sD   t    t|j|j| _t|jt	rt
|j | _d S |j| _d S r5   )r6   r7   r   r   rH   intermediate_sizer   rN   Z
hidden_actrB   r   intermediate_act_fnr   r9   r$   r%   r7     s
   
zBeitIntermediate.__init__r;   c                 C   r   r5   )r   r   r<   r$   r$   r%   r=     r   zBeitIntermediate.forward	r    r!   r"   r   r7   r0   r   r=   rC   r$   r$   r9   r%   r     s    r   c                       r   )	
BeitOutputrE   r*   Nc                    s.   t    t|j|j| _t|j| _	d S r5   )
r6   r7   r   r   r   rH   r   rU   rV   rW   r   r9   r$   r%   r7     r   zBeitOutput.__init__r;   c                 C   r   r5   r   r<   r$   r$   r%   r=     r   zBeitOutput.forwardr   r$   r$   r9   r%   r     s    r   c                       s   e Zd ZdZddedee deddf fdd	Z		
		
	dde	j
dee	j
 dedee	j
 dedeee  deee	j
 ee	j
e	j
f f fddZ  ZS )	BeitLayerz?This corresponds to the Block class in the timm implementation.Nr&   rE   r   drop_path_rater*   c                    s   t    |j| _d| _t||d| _t|| _t|| _	t
j|j|jd| _|dkr/t|nt
 | _t
j|j|jd| _|j}|dkrct
j|t|j dd| _t
j|t|j dd| _d S d\| _| _d S )	Nr   r   Zepsr&   r   T)Zrequires_gradrx   )r6   r7   Zchunk_size_feed_forwardZseq_len_dimr   r   r   intermediater   r2   r   	LayerNormrH   layer_norm_epslayernorm_beforer4   Identityr3   layernorm_afterlayer_scale_init_valuerF   r0   Zoneslambda_1lambda_2)r8   rE   r   r   Zinit_valuesr9   r$   r%   r7     s   


 zBeitLayer.__init__Fr;   r   r   r   rl   r   c                 C   s   | j | ||||||d}|d }|dd  }	| jd ur"| j| }| || }| |}
| |
}
| |
}
| jd urB| j|
 }
| |
| }
|
f|	 }	|	S )N)r   r   rl   r   r   r   )r   r   r   r3   r   r   r2   r   )r8   r;   r   r   r   rl   r   Zself_attention_outputsr   r   Zlayer_outputr$   r$   r%   r=   	  s*   	







zBeitLayer.forward)Nr&   r   )r    r!   r"   r#   r   r   r   rA   r7   r0   r   r{   r   ry   r   r=   rC   r$   r$   r9   r%   r     s.    $
r   c                       sf   e Zd Zdededdf fddZedddeeef de	j
fd	d
Zddede	j
fddZ  ZS )r   rE   r   r*   Nc                    sR   t    || _d|d  d d|d  d  d | _tt| j|j| _	d S )Nr\   r   r   r   )
r6   r7   r   num_relative_distancer   rF   r0   rG   r   relative_position_bias_tabler   r9   r$   r%   r7   6  s   
&
z!BeitRelativePositionBias.__init__
   )maxsizec           	      C   s  d|d  d d|d  d  d }|d |d  }t jt |d t |d dd}t |}t |d}|dddddf |dddddf  }|ddd }|dddddf  |d d 7  < |dddddf  |d d 7  < |dddddf  d|d  d 9  < t j|d fd |jd}|	d	|ddddf< |d |dddf< |d |dddf< |d |d
< |S )z
        This method creates the relative position index, modified to support arbitrary window sizes,
        as introduced in [MiDaS v3.1](https://arxiv.org/abs/2307.14460).
        r\   r   r   r   Zij)ZindexingN)r^   r,   r[   )r   r   )
r0   ZmeshgridZarangestackr   re   r   rG   r,   sum)	r8   r   r   Zwindow_areagridZcoordsZcoords_flattenZrelative_coordsrelative_position_indexr$   r$   r%    generate_relative_position_index?  s    $$
,&&*z9BeitRelativePositionBias.generate_relative_position_indexFrl   c                 C   sf  d| j d  d }d| j d  d }d|d  d }d|d  d }| j}| j}	|| d }
|d|	d  }|d||ddddd}tjj|t|t|fdd}|dddd|
d d}t	
|||	d d g}| |}||d }||d |d  d |d |d  d d}|ddd }|rtjj|d||fdd	d
d}|dS )zu
        Modification of timm.models.beit.py: Attention._get_rel_pos_bias to support arbitrary window sizes.
        r\   r   r   r   Nr[   bilinear)r^   r_   Fr]   )r   r   r   rd   re   r   rf   rg   r   r0   ri   r   rh   r   rr   squeeze)r8   r   rl   r   Z
old_heightZ	old_widthrj   rk   Z old_relative_position_bias_tableZold_num_relative_distanceZnew_num_relative_distanceZold_sub_tableZnew_sub_tableZ new_relative_position_bias_tabler   r   r$   r$   r%   r=   X  s@   
&
z BeitRelativePositionBias.forward)FN)r    r!   r"   r   r   r7   r   r   ry   r0   r   r   r{   r=   rC   r$   r$   r9   r%   r   5  s
    	r   c                       s   e Zd Zddedee ddf fddZ						dd	ejd
eej de	de	de	dee
eef  de	deeef fddZ  ZS )BeitEncoderNrE   r   r*   c                    sz   t     | _ j| _| jrt d| _dd tjd j	 j
ddD t fddt j
D | _d| _d S )	Nr   c                 S   s   g | ]}|  qS r$   )item.0r   r$   r$   r%   
<listcomp>  s    z(BeitEncoder.__init__.<locals>.<listcomp>r   cpu)r-   c                    s(   g | ]}t   jrnd | dqS )N)r   r   )r   Zuse_relative_position_biasr   irE   Zdprr   r$   r%   r     s    F)r6   r7   rE   Z!use_shared_relative_position_biasr   r   r   r0   Zlinspacer   num_hidden_layersr   
ModuleListrangelayergradient_checkpointingr   r9   r   r%   r7     s   
 

zBeitEncoder.__init__FTr;   r   r   output_hidden_statesrl   r   return_dictc              
   C   s  |rdnd }|r
dnd }	t | jD ]_\}
}|r||f }| jr;|\}}|| jj || jj f}| j|||jd d}nd }|d urE||
 nd }| jrZ| jrZ| 	|j
||||||}n	|||||||}|d }|rp|	|d f }	q|rx||f }|stdd |||	fD S t|||	dS )Nr$   r   )rl   r   r   c                 s   s    | ]	}|d ur|V  qd S r5   r$   )r   vr$   r$   r%   	<genexpr>  s    z&BeitEncoder.forward.<locals>.<genexpr>)last_hidden_stater;   
attentions)	enumerater   r   rE   rM   r   r.   r   r)   Z_gradient_checkpointing_func__call__r   r   )r8   r;   r   r   r   rl   r   r   Zall_hidden_statesZall_self_attentionsr   Zlayer_modulerY   rZ   r   r   Zlayer_head_maskZlayer_outputsr$   r$   r%   r=     sX   


	
zBeitEncoder.forwardr5   )NFFFNT)r    r!   r"   r   r   r   r7   r0   r   r{   r   ry   r   r   r=   rC   r$   r$   r9   r%   r     s2     
	r   c                   @   s4   e Zd ZeZdZdZdZdgZdgZ	dZ
dd ZdS )	BeitPreTrainedModelbeitrm   Tr   z.*relative_position_index.*c                 C   sb  t |tj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rH|jjjd| jj	d |jdurF|jj|j   dS dS t |tjr]|j
j  |jjd dS t |tr|jj  |jdurs|jj  |jdur|jj  dS dS t |tr|jj  dS t |tr|jdur|jj| jj |jj| jj dS dS dS )zInitialize the weightsr&   )meanZstdNg      ?)rN   r   r   r   ConvTranspose2dweightdataZnormal_rE   Zinitializer_ranger   Zzero_Z	EmbeddingZpadding_idxr   Zfill_rD   rI   rJ   rT   r   r   r   r   r   r   )r8   moduler$   r$   r%   _init_weights  s8   







z!BeitPreTrainedModel._init_weightsN)r    r!   r"   r   Zconfig_classZbase_model_prefixZmain_input_nameZsupports_gradient_checkpointingZ_no_split_modulesZ"_keys_to_ignore_on_load_unexpectedZ_supports_sdpar   r$   r$   r$   r%   r     s    r   c                       s   e Zd Zddededdf fddZdd	 Zd
d Ze						dde	j
dee	j dee	j
 dee dee dedee deeef fddZ  ZS )	BeitModelTrE   add_pooling_layerr*   Nc                    sp   t  | || _t|| _t|| jjjd| _|j	rt
 nt
j|j|jd| _|r/t|nd| _|   dS )zv
        add_pooling_layer (bool, *optional*, defaults to `True`):
            Whether to add a pooling layer
        r   r   N)r6   r7   rE   rD   rX   r   rL   r   encoderuse_mean_poolingr   r   r   rH   r   	layernorm
BeitPoolerpooler	post_init)r8   rE   r  r9   r$   r%   r7     s   
zBeitModel.__init__c                 C      | j jS r5   rX   rL   r?   r$   r$   r%   get_input_embeddings     zBeitModel.get_input_embeddingsc                 C   s*   |  D ]\}}| jj| j| qdS )z
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        N)itemsr  r   r   r   )r8   Zheads_to_pruner   r   r$   r$   r%   _prune_heads  s   zBeitModel._prune_headsFrm   rn   r   r   r   rl   r   c              	   C   s   |dur|n| j j}|dur|n| j j}|dur|n| j j}| || j j}| j||d\}}	|jdd }
| j|||||
||d}|d }| 	|}| j
durU| 
|nd}|sl|dura||fn|f}||dd  S t|||j|jd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).
        N)rn   r\   )r   r   r   r   r   rl   r   r   )r   pooler_outputr;   r   )rE   r   r   use_return_dictZget_head_maskr   rX   r.   r  r  r  r   r;   r   )r8   rm   rn   r   r   r   rl   r   embedding_outputrs   r   Zencoder_outputssequence_outputpooled_outputZhead_outputsr$   r$   r%   r=   &  s8   	
zBeitModel.forward)T)NNNNFN)r    r!   r"   r   r{   r7   r
  r  r   r0   r   r   rz   r   r   r   r=   rC   r$   r$   r9   r%   r     s8    
	r   c                       r   )	r  rE   r*   Nc                    s2   t    |jrtj|j|jd| _d S d | _d S )Nr   )r6   r7   r  r   r   rH   r   r  r   r9   r$   r%   r7   _  s
   
zBeitPooler.__init__r;   c                 C   sL   | j d ur|d d dd d d f }|  |d}|S |d d df }|S )Nr   r   )r  r   )r8   r;   Zpatch_tokensr  r$   r$   r%   r=   e  s   
zBeitPooler.forwardr   r$   r$   r9   r%   r  ^  s    r  a  
    Beit Model transformer with a 'language' modeling head on top. BEiT does masked image modeling by predicting
    visual tokens of a Vector-Quantize Variational Autoencoder (VQ-VAE), whereas other vision models like ViT and DeiT
    predict RGB pixel values. As a result, this class is incompatible with [`AutoModelForMaskedImageModeling`], so you
    will need to use [`BeitForMaskedImageModeling`] directly if you wish to do masked image modeling with BEiT.
    )Zcustom_introc                       s   e Zd Zdeddf fddZe								ddeej deej	 d	eej d
eej dee
 dee
 de
dee
 deeef fddZ  ZS )BeitForMaskedImageModelingrE   r*   Nc                    sT   t  | |j| _t|dd| _tj|j|jd| _	t
|j|j| _|   d S )NFr  r   )r6   r7   
num_labelsr   r   r   r   rH   r   r  r   Z
vocab_sizelm_headr  r   r9   r$   r%   r7   z  s   z#BeitForMaskedImageModeling.__init__Frm   rn   r   labelsr   r   rl   r   c	              	   C   s   |dur|n| j j}| j|||||||d}	|	d }
| |
}
| |
ddddf }d}|dur<t }||| |}|sR|f|	dd  }|durP|f| S |S t|||	j|	jd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).
        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, BeitForMaskedImageModeling
        >>> 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("microsoft/beit-base-patch16-224-pt22k")
        >>> model = BeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k")

        >>> 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, logits = outputs.loss, outputs.logits
        >>> list(logits.shape)
        [1, 196, 8192]
        ```N)rn   r   r   r   rl   r   r   r   losslogitsr;   r   )	rE   r  r   r  r  r
   r   r;   r   )r8   rm   rn   r   r  r   r   rl   r   r   r  Zprediction_scoresZmasked_lm_lossloss_fctr2   r$   r$   r%   r=     s4   ,

z"BeitForMaskedImageModeling.forward)NNNNNNFN)r    r!   r"   r   r7   r   r   r0   r   rz   r{   r   r   r   r=   rC   r$   r$   r9   r%   r  q  s<    		

r  z
    Beit Model transformer with an image classification head on top (a linear layer on top of the average of the final
    hidden states of the patch tokens) e.g. for ImageNet.
    c                       s   e Zd Zdeddf fddZe							ddeej deej d	eej d
ee	 dee	 de	dee	 de
eef fddZ  ZS )BeitForImageClassificationrE   r*   Nc                    sR   t  | |j| _t|dd| _|jdkrt|j|jnt | _	| 
  d S )NTr  r   )r6   r7   r  r   r   r   r   rH   r   
classifierr  r   r9   r$   r%   r7     s
   $z#BeitForImageClassification.__init__Frm   r   r  r   r   rl   r   c                 C   sl  |dur|n| j j}| j||||||d}|r|jn|d }	| |	}
d}|dur| j jdu rS| jdkr9d| j _n| jdkrO|jtj	ksJ|jtj
krOd| j _nd| j _| j jdkrqt }| jdkrk||
 | }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|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).
        Nr   r   r   rl   r   r   Z
regressionZsingle_label_classificationZmulti_label_classificationr[   r\   r  )rE   r  r   r  r  Zproblem_typer  r,   r0   longry   r   r   r
   rh   r	   r   r;   r   )r8   rm   r   r  r   r   rl   r   r   r  r  r  r  r2   r$   r$   r%   r=     sN   	


"


z"BeitForImageClassification.forwardNNNNNFN)r    r!   r"   r   r7   r   r   r0   r   r{   r   r   r   r=   rC   r$   r$   r9   r%   r    s6    
	r  c                       s   e Zd ZdZ			ddededeeeeef f deeeeef ef d	ed
eeeeef f ddf fddZ	de
jde
jfddZ  ZS )BeitConvModuleaD  
    A convolutional block that bundles conv/norm/activation layers. This block simplifies the usage of convolution
    layers, which are commonly used with a norm layer (e.g., BatchNorm) and activation layer (e.g., ReLU).

    Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
    r   Fr   in_channelsout_channelsr}   paddingr   dilationr*   Nc                    s<   t    tj||||||d| _t|| _t | _d S )N)r"  r#  r}   r$  r   r%  )	r6   r7   r   r   convBatchNorm2dbnZReLU
activation)r8   r"  r#  r}   r$  r   r%  r9   r$   r%   r7   0  s   
	zBeitConvModule.__init__r'   c                 C   s"   |  |}| |}| |}|S r5   )r&  r(  r)  )r8   r'   r2   r$   r$   r%   r=   E  s   


zBeitConvModule.forward)r   Fr   )r    r!   r"   r#   ry   r   r   rB   r{   r7   r0   r   r=   rC   r$   r$   r9   r%   r!  (  s*    r!  c                       sD   e Zd Zdedededdf fddZdejdejfd	d
Z  ZS )BeitPyramidPoolingBlock
pool_scaler"  channelsr*   Nc                    sL   t    t|t||ddg| _t| jD ]\}}| t|| qd S )Nr   r}   )	r6   r7   r   ZAdaptiveAvgPool2dr!  layersr   
add_modulerB   )r8   r+  r"  r,  r   r   r9   r$   r%   r7   N  s   
z BeitPyramidPoolingBlock.__init__r'   c                 C   s   |}| j D ]}||}q|S r5   )r.  )r8   r'   hidden_stater   r$   r$   r%   r=   W  s   

zBeitPyramidPoolingBlock.forward)	r    r!   r"   ry   r7   r0   r   r=   rC   r$   r$   r9   r%   r*  M  s    	r*  c                
       sX   e Zd ZdZdeedf dedededdf
 fd	d
Zdej	de
ej	 fddZ  ZS )BeitPyramidPoolingModulea  
    Pyramid Pooling Module (PPM) used in PSPNet.

    Args:
        pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid
            Module.
        in_channels (int): Input channels.
        channels (int): Channels after modules, before conv_seg.
        align_corners (bool): align_corners argument of F.interpolate.

    Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
    pool_scales.r"  r,  r`   r*   Nc                    sh   t    || _|| _|| _|| _g | _t|D ]\}}t|||d}| j	| | 
t|| qd S )N)r+  r"  r,  )r6   r7   r2  r`   r"  r,  blocksr   r*  appendr/  rB   )r8   r2  r"  r,  r`   r   r+  blockr9   r$   r%   r7   l  s   
z!BeitPyramidPoolingModule.__init__r   c                 C   sH   g }| j D ]}||}tjj|| dd  d| jd}|| q|S )Nr\   r   r]   )r3  r   rf   rg   r^   r`   r4  )r8   r   Zppm_outsppmZppm_outZupsampled_ppm_outr$   r$   r%   r=   x  s   
z BeitPyramidPoolingModule.forward)r    r!   r"   r#   r   ry   r{   r7   r0   r   r   r=   rC   r$   r$   r9   r%   r1  ^  s    *"r1  c                       sH   e Zd ZdZdeddf fddZdd Zd	ejdejfd
dZ	  Z
S )BeitUperHeadz
    Unified Perceptual Parsing for Scene Understanding. This head is the implementation of
    [UPerNet](https://arxiv.org/abs/1807.10221).

    Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
    rE   r*   Nc                    s  t    |j| _|jgd | _|j| _d| _tj| j|j	dd| _
t| j| jd | j| jd| _t| jd t| j| j  | jddd| _t | _t | _| jd d D ] }t|| jdd}t| j| jddd}| j| | j| qWtt| j| j | jddd| _d S )	N   Fr   r-  r[   )r`   r   r}   r$  )r6   r7   r2  rH   r"  r,  r`   r   r   r  r  r1  psp_modulesr!  r   
bottleneckr   lateral_convs	fpn_convsr4  fpn_bottleneck)r8   rE   r"  Zl_convZfpn_convr9   r$   r%   r7     s>   


zBeitUperHead.__init__c                 C   s:   |d }|g}| | | tj|dd}| |}|S )Nr[   r   ra   )extendr:  r0   ri   r;  )r8   Zinputsr   Zpsp_outsr2   r$   r$   r%   psp_forward  s   
zBeitUperHead.psp_forwardencoder_hidden_statesc                    s   fddt jD   t}t|d ddD ]$}|d  jdd  }|d  tjj	| |dj
d |d < q fd	dt|d D }|d  t|d ddD ]}tjj	|| |d jdd  dj
d||< qbtj|dd
}|}|}|S )Nc                    s   g | ]
\}}| | qS r$   r$   )r   r   Zlateral_conv)rA  r$   r%   r     s    z(BeitUperHead.forward.<locals>.<listcomp>r   r   r[   r\   r   r]   c                    s   g | ]}j |  | qS r$   )r=  r   )lateralsr8   r$   r%   r     s    ra   )r   r<  r4  r@  r   r   r.   r   rf   rg   r`   r0   ri   r>  r  )r8   rA  Zused_backbone_levelsr   Z
prev_shapeZfpn_outsr2   r$   )rA  rB  r8   r%   r=     s$   

zBeitUperHead.forward)r    r!   r"   r#   r   r7   r@  r0   r   r=   rC   r$   r$   r9   r%   r7    s
    &	r7  c                       s`   e Zd ZdZ	ddedededeeeeef f d	d
f
 fddZde	j
d	e	j
fddZ  ZS )BeitFCNHeada  
    Fully Convolution Networks for Semantic Segmentation. This head is implemented of
    [FCNNet](https://arxiv.org/abs/1411.4038>).

    Args:
        config (BeitConfig): Configuration.
        in_channels
        kernel_size (int): The kernel size for convs in the head. Default: 3.
        dilation (int): The dilation rate for convs in the head. Default: 1.


    Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
    r\   r   r   rE   in_indexr}   r%  r*   Nc              
      s   t    |j| _|j| _|j| _|j| _	|| _
|d | }g }|t| j| j|||d t| jd D ]}|t| j| j|||d q5| jdkrQt | _ntj| | _| j	rjt| j| j | j||d d| _tj| j|jdd| _d S )Nr\   )r}   r$  r%  r   r   r9  r-  )r6   r7   rH   r"  Zauxiliary_channelsr,  Zauxiliary_num_convsZ	num_convsZauxiliary_concat_inputconcat_inputrD  r4  r!  r   r   r   convs
Sequentialconv_catr   r  r  )r8   rE   rD  r}   r%  Zconv_paddingrF  r   r9   r$   r%   r7     s6   

zBeitFCNHead.__init__rA  c                 C   s@   || j  }| |}| jr| tj||gdd}| |}|S )Nr   ra   )rD  rF  rE  rH  r0   ri   r  )r8   rA  r;   r2   r$   r$   r%   r=   	  s   


zBeitFCNHead.forward)r\   r   r   )r    r!   r"   r#   r   ry   r   r   r7   r0   r   r=   rC   r$   r$   r9   r%   rC    s    "rC  c                       s   e Zd Zdeddf fddZdd Ze							dd	eej	 d
eej	 deej	 dee
 dee
 de
dee
 deeef fddZ  ZS )BeitForSemanticSegmentationrE   r*   Nc                    s   t  | |j| _t|dd| _t| jjdkrtdt	
t	j|j|jdddt	|jt	 t	j|j|jddd| _t	
t	j|j|jddd| _t	 | _t	jddd| _t|| _|jrft|nd | _|   d S )NFr  r8  zBeitForSemanticSegmentation requires config.out_indices to be a list of 4 integers, specifying which features to use from the backbone. One can use [3, 5, 7, 11] in case of a base-sized architecture.r\   r|   )r6   r7   r  r   r   r   rE   out_indicesr   r   rG  r   rH   r'  GELUfpn1fpn2r   fpn3	MaxPool2dfpn4r7  decode_headZuse_auxiliary_headrC  auxiliary_headr  r   r9   r$   r%   r7     s*   


z$BeitForSemanticSegmentation.__init__c           
      C   s   t jj||jdd  ddd}|d ur"t jj||jdd  ddd}t| jjd}|||}|}|d urA|||}	|| jj|	 7 }|S )Nr   r   Fr]   )Zignore_index)r   rf   rg   r.   r
   rE   Zsemantic_loss_ignore_indexZauxiliary_loss_weight)
r8   r  auxiliary_logitsr  Zupsampled_logitsZupsampled_auxiliary_logitsr  Z	main_lossr  Zauxiliary_lossr$   r$   r%   compute_loss5  s   

z(BeitForSemanticSegmentation.compute_lossFrm   r   r  r   r   rl   r   c                    s  |dur|nj j}|dur|nj j}|dur"j jdkr"tdj|||d||d}|r2|jn|d }	fddt|	D }
|jd  j j	j j
  fd	d|
D }
jjjjg}tt|
D ]}|| |
| |
|< qh|
}d}jdur|
}d}|dur|||}|s|r|f|dd  }n	|f|d
d  }|dur|f| S |S t|||r|jnd|jdS )aD  
        labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
            Ground truth semantic segmentation maps for computing the loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels > 1`, a classification loss is computed (Cross-Entropy).

        Examples:

        ```python
        >>> from transformers import AutoImageProcessor, BeitForSemanticSegmentation
        >>> 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("microsoft/beit-base-finetuned-ade-640-640")
        >>> model = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640")

        >>> inputs = image_processor(images=image, return_tensors="pt")
        >>> outputs = model(**inputs)
        >>> # logits are of shape (batch_size, num_labels, height, width)
        >>> logits = outputs.logits
        ```Nr   z/The number of labels should be greater than oneTr  c                    s$   g | ]\}}|d   j jv r|qS r+   )rE   rJ  )r   idxfeaturer?   r$   r%   r     s   $ z7BeitForSemanticSegmentation.forward.<locals>.<listcomp>r   c                    s<   g | ]}|d d dd d d f  ddd dqS )Nr   r   r\   r[   )re   rd   r   )rv   patch_resolutionr$   r%   r     s    0r\   r  )rE   r  r   r  r   r   r;   r   r.   rO   rM   rL  rM  rN  rP  r   r   rQ  rR  rT  r   r   )r8   rm   r   r  r   r   rl   r   r   rA  featuresopsr   r  rS  r  r2   r$   )rv   rW  r8   r%   r=   H  sR   "	



z#BeitForSemanticSegmentation.forwardr   )r    r!   r"   r   r7   rT  r   r   r0   r   r{   r   r   r   r=   rC   r$   r$   r9   r%   rI    s8     
	rI  zM
    BEiT backbone, to be used with frameworks like DETR and MaskFormer.
    c                       sZ   e Zd Z fddZdd Ze			ddedee dee d	ee d
e	f
ddZ
  ZS )BeitBackbonec                    s   t    t     fddt jd D | _t | _t | jj	j
d| _ jrut| jjdkr9td j}ttj||dddtj| jd	t tj||ddd| _ttj||ddd| _t | _tjddd| _|   d S )
Nc                    s   g | ]} j qS r$   )rH   )r   rs   rE   r$   r%   r     s    z)BeitBackbone.__init__.<locals>.<listcomp>r   r   r8  zBeitBackbone requires config.out_indices to be a list of 4 integers, specifying which features to use from the backbone. One can use [3, 5, 7, 11] in case of a base-sized architecture.r\   r|   r   )r6   r7   Z_init_backboner   r   Znum_featuresrD   rX   r   rL   r   r  add_fpnr   rE   rJ  r   rH   r   rG  r   r'  Zbatch_norm_epsrK  rL  rM  r   rN  rO  rP  r  )r8   rE   rH   r9   r[  r%   r7     s*   

zBeitBackbone.__init__c                 C   r  r5   r	  r?   r$   r$   r%   r
    r  z!BeitBackbone.get_input_embeddingsNrm   r   r   r   r*   c                 C   s  |dur|n| j j}|dur|n| j j}|dur|n| j j}|jd }| |\}\}}|jdd }	| j|d||	|d}
|rB|
jn|
d }d}t| j	|D ].\}}|| j
v r|| j jrw|ddddddf }|ddd}||d||}||f7 }qN| j jr| |d | |d | |d | |d	 g}t|}|s|r|f|
dd  }|S |f|
dd  }|S t||r|
jnd|
jd
S )a:  
        Examples:

        ```python
        >>> from transformers import AutoImageProcessor, AutoBackbone
        >>> 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)

        >>> processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-patch16-224")
        >>> model = AutoBackbone.from_pretrained(
        ...     "microsoft/beit-base-patch16-224", out_features=["stage1", "stage2", "stage3", "stage4"]
        ... )

        >>> inputs = processor(image, return_tensors="pt")

        >>> outputs = model(**inputs)
        >>> feature_maps = outputs.feature_maps
        >>> list(feature_maps[-1].shape)
        [1, 768, 14, 14]
        ```Nr   r\   T)r   r   r   r   r   r$   r[   r   )feature_mapsr;   r   )rE   r  r   r   r.   rX   r  r;   zipZstage_namesZout_featuresZreshape_hidden_statesre   rd   r\  rL  rM  rN  rP  r   r   r   )r8   rm   r   r   r   rv   r  rt   ru   r   r   r;   r]  Zstager0  r2   r$   r$   r%   r=     sT    


zBeitBackbone.forward)NNN)r    r!   r"   r7   r
  r   r   r   r{   r   r=   rC   r$   r$   r9   r%   rZ    s$    rZ  )r  r  rI  r   r   rZ  )r&   F)Pr#   collections.abcrP   r   ro   dataclassesr   typingr   r   r   r   r0   Ztorch.utils.checkpointr   r   Ztorch.nnr	   r
   r   Zactivationsr   Zmodeling_outputsr   r   r   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   r   utilsr   r   r   Zutils.backbone_utilsr   Zconfiguration_beitr   Z
get_loggerr    r   Z_EXPECTED_OUTPUT_SHAPEZ_IMAGE_CLASS_CHECKPOINTZ_IMAGE_CLASS_EXPECTED_OUTPUTr   rA   r{   r3   Moduler4   rD   rK   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r!  r*  r1  r7  rC  rI  rZ  __all__r$   r$   r$   r%   <module>   s    
 f&S>,ASW&W[N%%U; w