o
    wi                    @   s  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m	  m
Z d dlZd dlm	Z	 d dlmZmZ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mZmZ ddlm Z  ddl!m"Z"m#Z#m$Z$ ddl%m&Z& ddl'm(Z(m)Z) e# rd dl*m+Z+ d dl,m-Z- d dl.m/Z/ ne0Z-e$1e2Z3G dd deZ4		dXdej5dej5deej5 deej5 de6ej5ej5ej5e7eej5 eej5 f f
ddZ8dej5dej5de7de7dej5f
d d!Z9G d"d# d#ej:j;Z<		dXd$eej5 d%ee7 fd&d'Z=G d(d) d)e-Z>G d*d+ d+e	j?Z@G d,d- d-e	j?ZAG d.d/ d/e(ZB	0dYd1d2d3ej5dej5d4ej5deejC d5e6e7e7f d6e7d7e7d8eeD dee6ej5ej5f e6ej5 f fd9d:ZEejFfd1d2d3ej5d;e>d$ej5d%e7d5e6e7e7f d6e7d7e7d<ejGde6ej5 fd=d>ZHd1d2d3ej5dej5d4ej5deejC d5e6e7e7f d6e7d7e7de6ej5 fd?d@ZIeHeEeIdAZJG dBd2 d2e	j?ZKG dCdD dDeZLe"G dEdF dFe ZMe"G dGdH dHeMZNG dIdJ dJe	j?ZOe"dKdLG dMdN dNeMZPe"dOdLG dPdQ dQeMZQe"dRdLG dSdT dTeMZRe"G dUdV dVeMZSg dWZTdS )Z    N)nullcontext)LiteralOptionalUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)PretrainedConfig)_prepare_4d_attention_mask)GradientCheckpointingLayer)BaseModelOutputMaskedLMOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel)auto_docstringis_flash_attn_2_availablelogging)is_triton_available   )GemmaRotaryEmbeddingapply_rotary_pos_emb) flash_attn_varlen_qkvpacked_func)RotaryEmbedding)apply_rotaryc                       s   e Zd ZdZdZdgZ								
																													d!ded f fddZ fdd Z  Z	S )"ModernBertConfiga  
    This is the configuration class to store the configuration of a [`ModernBertModel`]. It is used to instantiate an ModernBert
    model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
    defaults will yield a similar configuration to that of the ModernBERT-base.
    e.g. [answerdotai/ModernBERT-base](https://huggingface.co/answerdotai/ModernBERT-base)

    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information.

    Args:
        vocab_size (`int`, *optional*, defaults to 50368):
            Vocabulary size of the ModernBert model. Defines the number of different tokens that can be represented by the
            `inputs_ids` passed when calling [`ModernBertModel`]
        hidden_size (`int`, *optional*, defaults to 768):
            Dimension of the hidden representations.
        intermediate_size (`int`, *optional*, defaults to 1152):
            Dimension of the MLP representations.
        num_hidden_layers (`int`, *optional*, defaults to 22):
            Number of hidden layers in the Transformer decoder.
        num_attention_heads (`int`, *optional*, defaults to 12):
            Number of attention heads for each attention layer in the Transformer decoder.
        hidden_activation (`str` or `function`, *optional*, defaults to `"gelu"`):
            The non-linear activation function (function or string) in the decoder. Will default to `"gelu"`
            if not specified.
        max_position_embeddings (`int`, *optional*, defaults to 8192):
            The maximum sequence length that this model might ever be used with.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        initializer_cutoff_factor (`float`, *optional*, defaults to 2.0):
            The cutoff factor for the truncated_normal_initializer for initializing all weight matrices.
        norm_eps (`float`, *optional*, defaults to 1e-05):
            The epsilon used by the rms normalization layers.
        norm_bias (`bool`, *optional*, defaults to `False`):
            Whether to use bias in the normalization layers.
        pad_token_id (`int`, *optional*, defaults to 50283):
            Padding token id.
        eos_token_id (`int`, *optional*, defaults to 50282):
            End of stream token id.
        bos_token_id (`int`, *optional*, defaults to 50281):
            Beginning of stream token id.
        cls_token_id (`int`, *optional*, defaults to 50281):
            Classification token id.
        sep_token_id (`int`, *optional*, defaults to 50282):
            Separation token id.
        global_rope_theta (`float`, *optional*, defaults to 160000.0):
            The base period of the global RoPE embeddings.
        attention_bias (`bool`, *optional*, defaults to `False`):
            Whether to use a bias in the query, key, value and output projection layers during self-attention.
        attention_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the attention probabilities.
        global_attn_every_n_layers (`int`, *optional*, defaults to 3):
            The number of layers between global attention layers.
        local_attention (`int`, *optional*, defaults to 128):
            The window size for local attention.
        local_rope_theta (`float`, *optional*, defaults to 10000.0):
            The base period of the local RoPE embeddings.
        embedding_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the embeddings.
        mlp_bias (`bool`, *optional*, defaults to `False`):
            Whether to use bias in the MLP layers.
        mlp_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the MLP layers.
        decoder_bias (`bool`, *optional*, defaults to `True`):
            Whether to use bias in the decoder layers.
        classifier_pooling (`str`, *optional*, defaults to `"cls"`):
            The pooling method for the classifier. Should be either `"cls"` or `"mean"`. In local attention layers, the
            CLS token doesn't attend to all tokens on long sequences.
        classifier_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the classifier.
        classifier_bias (`bool`, *optional*, defaults to `False`):
            Whether to use bias in the classifier.
        classifier_activation (`str`, *optional*, defaults to `"gelu"`):
            The activation function for the classifier.
        deterministic_flash_attn (`bool`, *optional*, defaults to `False`):
            Whether to use deterministic flash attention. If `False`, inference will be faster but not deterministic.
        sparse_prediction (`bool`, *optional*, defaults to `False`):
            Whether to use sparse prediction for the masked language model instead of returning the full dense logits.
        sparse_pred_ignore_index (`int`, *optional*, defaults to -100):
            The index to ignore for the sparse prediction.
        reference_compile (`bool`, *optional*):
            Whether to compile the layers of the model which were compiled during pretraining. If `None`, then parts of
            the model will be compiled if 1) `triton` is installed, 2) the model is not on MPS, 3) the model is not
            shared between devices, and 4) the model is not resized after initialization. If `True`, then the model may
            be faster in some scenarios.
        repad_logits_with_grad (`bool`, *optional*, defaults to `False`):
            When True, ModernBertForMaskedLM keeps track of the logits' gradient when repadding for output. This only
            applies when using Flash Attention 2 with passed labels. Otherwise output logits always have a gradient.

    Examples:

    ```python
    >>> from transformers import ModernBertModel, ModernBertConfig

    >>> # Initializing a ModernBert style configuration
    >>> configuration = ModernBertConfig()

    >>> # Initializing a model from the modernbert-base style configuration
    >>> model = ModernBertModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```
modernbertpast_key_values             gelu    {Gz?       @h㈵>Fk  j  i       A        r
           @TclsNclassifier_poolingr3   meanc$           %         s   t  jd|||||d|$ || _|| _|| _|| _|| _|| _|| _|	| _	|
| _
|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _| | _|!| _|"| _|#| _| jdvrwt d| j dd S )N)pad_token_idbos_token_ideos_token_idcls_token_idsep_token_idr6   zQInvalid value for `classifier_pooling`, should be either "cls" or "mean", but is . )!super__init__
vocab_sizemax_position_embeddingshidden_sizeintermediate_sizenum_hidden_layersnum_attention_headsinitializer_rangeinitializer_cutoff_factornorm_eps	norm_biasglobal_rope_thetaattention_biasattention_dropouthidden_activationglobal_attn_every_n_layerslocal_attentionlocal_rope_thetaembedding_dropoutmlp_biasmlp_dropoutdecoder_biasr5   classifier_dropoutclassifier_biasclassifier_activationdeterministic_flash_attnsparse_predictionsparse_pred_ignore_indexreference_compilerepad_logits_with_grad
ValueError)%selfrA   rC   rD   rE   rF   rN   rB   rG   rH   rI   rJ   r8   r:   r9   r;   r<   rK   rL   rM   rO   rP   rQ   rR   rS   rT   rU   r5   rV   rW   rX   rY   rZ   r[   r\   r]   kwargs	__class__r>   n/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/transformers/models/modernbert/modular_modernbert.pyr@      sX   '
zModernBertConfig.__init__c                    s   t   }|dd  |S )Nr\   )r?   to_dictpopr_   outputra   r>   rc   rd      s   
zModernBertConfig.to_dict)#r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   Fr,   r-   r.   r.   r-   r/   Fr0   r
   r1   r2   r0   Fr0   Tr3   r0   Fr'   FFr4   NF)
__name__
__module____qualname____doc__
model_typekeys_to_ignore_at_inferencer   r@   rd   __classcell__r>   r>   ra   rc   r   6   sV    gSr   inputsattention_maskposition_idslabelsreturnc                 C   s   |j dtjd}tj| dd }t|  }tjj	
tj|dtjdd}|  dkr7|  | }n| j^}	}
}|	|
 }| j|g|R  | }|durV| | nd}|durb| | nd}||||||fS )	a  
    Remove padding from input sequences.

    Args:
        inputs: (batch, seqlen, ...) or (batch, seqlen)
        attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid.
        position_ids: (batch, seqlen), int, position ids
        labels: (batch, seqlen), int, labels

    Returns:
        unpadded_inputs: (total_nnz, ...), where total_nnz = number of tokens selected in attention_mask.
        indices: (total_nnz)
        cu_seqlens: (batch + 1), the cumulative sequence lengths
        max_seqlen_in_batch: int
        unpadded_position_ids: (total_nnz) or None
        unpadded_labels: (total_nnz) or None
    dimdtypeF)as_tupler   )   r   r   N)sumtorchint32nonzeroflattenintmaxitemr   
functionalpadcumsumrv   shapeview)ro   rp   rq   rr   seqlens_in_batchindicesmax_seqlen_in_batch
cu_seqlensunpadded_inputsbatchseqlenrestr   unpadded_position_idsunpadded_labelsr>   r>   rc   _unpad_modernbert_input   s   r   r   r   r   c                 C   s   |   dkrtj|| | j| jd}| ||< |||}|S | j^}}tj|| g|R | j| jd}| ||< |j||g|R  }|S )aQ  
    Add padding to sequences.

    Args:
        inputs: (total_nnz, ...) or (total_nnz,), where total_nnz = number of tokens selected in attention_mask.
        indices: (total_nnz)
        batch: int, batch size
        seqlen: int, max sequence length

    Returns:
        padded_inputs: (batch, seqlen, ...) or (batch, seqlen)
    ry   )rw   device)rv   r{   zerosrw   r   r   r   )ro   r   r   r   rg   padded_inputs_r   r>   r>   rc   _pad_modernbert_output#  s   
"r   c                   @   s>   e Zd Ze		ddeej dee fddZedd Z	dS )	ApplyRotaryEmbUnpadNr   
max_seqlenc              
   C   sd   |  }|j\}}}}	|d d d df |d|	}
t|
||d||ddd | ||| || _|S )Nr   rt   r   FT)seqlen_offsetsr   r   interleavedinplace)
contiguousr   r   r   save_for_backwardr   )ctxqkvcossinr   r   	total_nnz_three_nheadsheaddimqkr>   r>   rc   forwardC  s    
zApplyRotaryEmbUnpad.forwardc           
      C   sn   | j \}}}| }|j\}}}}|d d d df |d|}	t|	||d|| jdddd	 |d d d d d d fS )Nr   rt   r   FT)r   r   r   r   r   	conjugate)saved_tensorsr   r   r   r   r   )
r   dor   r   r   r   r   r   r   dqkr>   r>   rc   backwardb  s    zApplyRotaryEmbUnpad.backwardNN)
rh   ri   rj   staticmethodr   r{   Tensorr   r   r   r>   r>   r>   rc   r   B  s    r   r   r   c                 C   s   t | ||||S )a  
    Arguments:
        qkv: (total_nnz, 3, nheads, headdim) - input tensor for packed QKV.
        cos, sin: (seqlen_rotary, rotary_dim / 2)
        interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead
            of 1st half and 2nd half (GPT-NeoX style).
        inplace: if True, apply rotary embedding in-place.
        seqlen_offsets: (batch_size,) or int. Each sequence in x is shifted by this amount.
            Most commonly used in inference when we have KV cache.
        cu_seqlens: (batch + 1,) or None
        max_seqlen: int
    Return:
        out: (total_nnz, dim)
    rotary_dim must be <= headdim
    Apply rotary embedding to the first rotary_dim of x.
    )r   apply)r   r   r   r   r   r>   r>   rc   apply_rotary_unpaddedy  s   r   c                       s   e Zd ZdZ				ddededee deej deej	 f
 fd	d
Z
	ddejdejdee deejeejejf f fddZdefddZ  ZS )!ModernBertUnpaddedRotaryEmbeddingzP
    The rotary position embeddings applied directly to unpadded sequences.
    r2   Nrv   baser   r   rw   c                    sR   t  j|||dd || _|dur#|dur%|dur'| j|||d dS dS dS dS )a  
        max_seqlen: if max_seqlen, device, and dtype are provided, we precompute the cos_sin_cache
            up to max_seqlen. If the max_seqlen, device, or dtype during training/inference differ,
            the cos_sin_cache will be recomputed during the forward pass.
        F)rv   r   r   r   Nr   rw   )r?   r@   r   _update_cos_sin_cache)r_   rv   r   r   r   rw   ra   r>   rc   r@     s
   z*ModernBertUnpaddedRotaryEmbedding.__init__r   r   rs   c                 C   s6   |dur| j ||j|jd t|| j| j||d}|S )z
        Apply rotary embedding *inplace* to qkv.
        qkv: (total_nnz, 3, nheads, headdim)
        cu_seqlens: (batch + 1,) cumulative sequence lengths
        max_seqlen: int max seq length in the batch
        Nr   r   r   )r   r   rw   r   _cos_cached_sin_cached)r_   r   r   r   r>   r>   rc   r     s   z)ModernBertUnpaddedRotaryEmbedding.forwardc                 C   s   d| j  d| j d| j S )Nzdim=z, base=z, scale_base=)rv   r   
scale_baser_   r>   r>   rc   
extra_repr  s   z,ModernBertUnpaddedRotaryEmbedding.extra_repr)r2   NNNN)rh   ri   rj   rk   r   floatr   r{   r   rw   r@   r   r   tupler   strr   rn   r>   r>   ra   rc   r     s8    
r   c                       sp   e Zd ZdZdef fddZejdddejdej	fd	d
Z
	ddeej deej	 dej	fddZ  ZS )ModernBertEmbeddingszV
    Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
    configc                    sR   t    || _tj|j|j|jd| _tj	|j|j
|jd| _t|j| _d S )N)padding_idxepsbias)r?   r@   r   r   	EmbeddingrA   rC   r8   tok_embeddings	LayerNormrI   rJ   normDropoutrR   dropr_   r   ra   r>   rc   r@     s
   
zModernBertEmbeddings.__init__Tdynamic	input_idsrs   c                 C      |  | | |S r   )r   r   r   )r_   r   r>   r>   rc   compiled_embeddings  s   z(ModernBertEmbeddings.compiled_embeddingsNinputs_embedsc                 C   sH   |d ur|  | |}|S | jjr| |n
|  | | |}|S r   )r   r   r   r\   r   r   )r_   r   r   hidden_statesr>   r>   rc   r     s   zModernBertEmbeddings.forwardr   )rh   ri   rj   rk   r   r@   r{   compile
LongTensorr   r   r   r   rn   r>   r>   ra   rc   r     s    
r   c                       s<   e Zd ZdZdef fddZdejdejfddZ  Z	S )	ModernBertMLPa6  Applies the GLU at the end of each ModernBERT layer.

    Compared to the default BERT architecture, this block replaces :class:`~transformers.model.bert.modeling_bert.BertIntermediate`
    and :class:`~transformers.model.bert.modeling_bert.SelfOutput` with a single module that has similar functionality.
    r   c                    sf   t    || _tj|jt|jd |jd| _	t
|j | _t|j| _tj|j|j|jd| _d S )Nr   r   )r?   r@   r   r   LinearrC   r   rD   rS   Wir   rN   actr   rT   r   Wor   ra   r>   rc   r@     s   
 zModernBertMLP.__init__r   rs   c                 C   s2   |  |jddd\}}| | | || S )Nr   rt   rv   )r   chunkr   r   r   )r_   r   inputgater>   r>   rc   r     s   zModernBertMLP.forward)
rh   ri   rj   rk   r   r@   r{   r   r   rn   r>   r>   ra   rc   r     s    r   c                
       s6   e Zd Zddedededeej f fddZ	  Z
S )	ModernBertRotaryEmbeddingNr   rv   r   r   c                    s.   t  j| ||d | jd |||d\}| _d S )N)r   r   )rv   r   )r?   r@   rope_init_fnattention_scaling)r_   r   rv   r   r   inv_freqra   r>   rc   r@     s   z"ModernBertRotaryEmbedding.__init__r   )rh   ri   rj   r   r   r   r   r{   r   r@   rn   r>   r>   ra   rc   r     s    .r   FmoduleModernBertAttentionr   sliding_window_maskrP   bsrv   output_attentionsc	                 K   s   | j ||d\}
}|ddjdd\}}}t|||
|\}}| jd }t||dd| }|dkr6|}|| }tjj	|dtj
d	|j}tjj|| j| jd
}t||}|dd }||d|}|rn||fS |fS )Nrq   r
   ry   r   r         ࿩rt   rt   rt   ru   )ptraining)
rotary_emb	transposeunbindr   head_dimr{   matmulr   r   softmaxfloat32torw   dropoutrM   r   r   r   )r   r   rp   r   rq   rP   r   rv   r   _kwargsr   r   querykeyvaluescaleattn_weightsattn_outputr>   r>   rc   eager_attention_forward   s    
r   r   target_dtypec	                 K   s   ||||d}|j tjtjfv}
|
r1|j }||}t|||| jr$| jnd| j|d}||}nt|||| jr;| jnd| j|d}|	||fS )Nr   r0   )r   r   	dropout_pdeterministicwindow_size)
rw   r{   float16bfloat16r   r   r   rM   rY   r   )r   r   r   r   r   rP   r   rv   r   r   convert_dtype
orig_dtypeattnr>   r>   rc   flash_attention_forward%  s.   
r  c                 K   s   | j ||d\}	}
|ddjdd\}}}t|||	|
\}}|dkr%|}tj|||| jr0| jnd|ddd }|	|d	|}|fS )
Nr   r
   ry   r   r   r   r0   )r   	attn_maskrt   )
r   r   r   r   Fscaled_dot_product_attentionr   rM   r   r   )r   r   rp   r   rq   rP   r   rv   r   r   r   r   r   r   r   r>   r>   rc   sdpa_attention_forwardP  s"   r  )flash_attention_2eagersdpac                       sR   e Zd ZdZddedee f fddZ	ddej	d	ee
 d
ej	fddZ  ZS )r   a  Performs multi-headed self attention on a batch of unpadded sequences.

    If Flash Attention 2 is installed, this module uses Flash Attention to improve throughput.
    If Flash Attention 2 is not installed, the implementation will use PyTorch's SDPA kernel,
    which requires padding and unpadding inputs, adding some overhead.

    See `forward` method for additional details.
    Nr   layer_idc                    s\  t    || _|| _|j|j dkr td|j d|j d|j| _|j| _|j| _	|j|j | _
| j
| j	 | _tj|jd| j |jd| _||j dkr[|jd |jd f| _nd| _|j}|j}| jdkrt|jd urq|j}|j}|jd	krt| j
||d
| _n	t|| j
|d| _tj|j|j|jd| _|jdkrt|jnt | _t | _d S )Nr   zThe hidden size (z6) is not a multiple of the number of attention heads ()r
   r   r   r   r  )rv   r   r   )r   rv   r   r0   )r?   r@   r   r  rC   rF   r^   rM   rY   	num_headsr   all_head_sizer   r   rL   WqkvrO   rP   rK   rB   rQ   _attn_implementationr   r   r   r   r   Identityout_dropsetpruned_heads)r_   r   r  
rope_thetarB   ra   r>   rc   r@     s<   




 zModernBertAttention.__init__Fr   r   rs   c              	   K   s   |  |}|jd }| jjdkr|dd| j| j}n||dd| j| j}t| jj | f|| j| j	|| j
|d|}|d }| | |}|f|dd   S )Nr   r  rt   r
   )r   r   rP   r   rv   r   ry   )r  r   r   r  r   r  r   MODERNBERT_ATTENTION_FUNCTIONr   rP   r  r  r   )r_   r   r   r`   r   r   attn_outputsr>   r>   rc   r     s(   



zModernBertAttention.forwardr   F)rh   ri   rj   rk   r   r   r   r@   r{   r   boolr   rn   r>   r>   ra   rc   r   z  s    	+c                       s   e Zd Zddedee f fddZejdddej	d	ej	fd
dZ
						ddej	deej	 deej	 deej deej	 dee dee d	ej	fddZ  ZS )ModernBertEncoderLayerNr   r  c                    sp   t    || _|dkrt | _ntj|j|j|j	d| _t
||d| _tj|j|j|j	d| _t|| _d S )Nr   r   )r   r  )r?   r@   r   r   r  	attn_normr   rC   rI   rJ   r   r  mlp_normr   mlp)r_   r   r  ra   r>   rc   r@     s   
zModernBertEncoderLayer.__init__Tr   r   rs   c                 C      |  | |S r   )r"  r!  r_   r   r>   r>   rc   compiled_mlp     z#ModernBertEncoderLayer.compiled_mlpFrp   r   rq   r   r   r   c           
   	   C   sf   | j | |||||||d}||d  }| jjr| |n| | |}	||	 }|f|dd   S )Nrp   r   rq   r   r   r   r   ry   )r  r   r   r\   r%  r"  r!  )
r_   r   rp   r   rq   r   r   r   r  
mlp_outputr>   r>   rc   r     s    
	zModernBertEncoderLayer.forwardr   )NNNNNF)rh   ri   rj   r   r   r   r@   r{   r   r   r%  r   r  r   rn   r>   r>   ra   rc   r    s6    
	r  c                       s   e Zd ZeZdZdZddgZdZdZ	dZ
dejfddZe					dd
eej deeeeeef f  def fddZdd Z fddZ  ZS )ModernBertPreTrainedModelmodelTr   r  Fr   c                    sv  | j j  d u r
d dtjdtf fdd}| j j| j jtd| j j  | j j| j j	d d}t
|tr?||j|d	  d S t
|trV||j|d
  ||j|d  d S t
|trm||j|d
  ||j|d  d S t
|tr|||j|d  d S t
|tr||j|d  d S t
|tttfr||j|d  d S t
|tjr|jjd |jd ur|jj  d S d S d S )Nr
   r   stdc                    sR   t jj| jd|  |  | d t| t jr%| jd ur't j| j d S d S d S )Nr0   )r7   r+  ab)r   inittrunc_normal_weight
isinstancer   r   zeros_)r   r+  cutoff_factorr>   rc   init_weight  s   
z<ModernBertPreTrainedModel._init_weights.<locals>.init_weightr*   r   )inout	embedding	final_outr8  r6  r7  r9  g      ?) r   rH   r   Moduler   rG   mathsqrtrE   rC   r1  r   r   r   r   r   r   r  ModernBertPredictionHeaddenseModernBertForMaskedLMdecoder#ModernBertForSequenceClassification ModernBertForTokenClassificationModernBertForQuestionAnswering
classifierr   r0  datafill_r   zero_)r_   r   r5  stdsr>   r3  rc   _init_weights  s@   






z'ModernBertPreTrainedModel._init_weightsNtorch_dtype
device_mapcheck_device_mapc              	      sZ   |j d u r#d|_ z| j|tj|d|dW S  ttfy"   d |_ Y nw t j||||dS )Nr  F)rJ  rK  hard_check_onlyrL  )rJ  rK  rL  )_attn_implementation_internal_check_and_enable_flash_attn_2r{   r  r^   ImportErrorr?   _autoset_attn_implementation)r3   r   rJ  rK  rL  ra   r>   rc   rQ  1  s&   

z6ModernBertPreTrainedModel._autoset_attn_implementationc                 C   s   | j jdu rd S t| dr!t| jdkr!| j jrtd d| j _| jjdkr4| j jr0td d| j _| jjdkrG| j jrCtd d| j _| j jd u rTt	 | j _d S d S )	NFhf_device_mapry   zqIf `accelerate` split the model across devices, `torch.compile` will not work. Falling back to non-compiled mode.mpsz|Compiling the model with `torch.compile` and using a `torch.mps` device is not supported. Falling back to non-compiled mode.cpuz|Compiling the model with `torch.compile` and using a `torch.cpu` device is not supported. Falling back to non-compiled mode.)
r   r\   hasattrlenrR  loggerwarning_oncer   typer   r   r>   r>   rc   _maybe_set_compileP  s.   z,ModernBertPreTrainedModel._maybe_set_compilec                    s<   t  j|i |}| jjdv r| jjrtd d| j_|S )N>   NTzcResizing token embeddings with `torch.compile` is not supported. Falling back to non-compiled mode.F)r?   resize_token_embeddingsr   r\   rW  rX  )r_   argsr`   model_embedsra   r>   rc   r[  o  s   z1ModernBertPreTrainedModel.resize_token_embeddings)NNT)rh   ri   rj   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_supports_flash_attn_2_supports_sdpa_supports_flex_attnr   r:  rI  classmethodr   r{   rw   r   r   dictr   r  rQ  rZ  r[  rn   r>   r>   ra   rc   r)    s,    /r)  c                !       s  e Zd Zdef fddZdd Zdd Ze													dd	ee	j
 d
ee	j dee	j dee	j
 dee	j dee	j dee	j dee dee dee dee dee dee deee	jdf ef fddZd
e	jdede	jfddZ  ZS )ModernBertModelr   c                    sf   t     | _t | _t fddt jD | _	tj
 j j jd| _d| _|   d S )Nc                    s   g | ]}t  |qS r>   )r  ).0r  r   r>   rc   
<listcomp>  s    z,ModernBertModel.__init__.<locals>.<listcomp>r   F)r?   r@   r   r   
embeddingsr   
ModuleListrangerE   layersr   rC   rI   rJ   
final_normgradient_checkpointing	post_initr   ra   ri  rc   r@   ~  s   
zModernBertModel.__init__c                 C   s   | j jS r   rk  r   r   r>   r>   rc   get_input_embeddings  s   z$ModernBertModel.get_input_embeddingsc                 C   s   || j _d S r   rr  )r_   r   r>   r>   rc   set_input_embeddings  s   z$ModernBertModel.set_input_embeddingsNr   rp   r   rq   r   r   r   r   
batch_sizeseq_lenr   output_hidden_statesreturn_dictrs   .c              
      s  |dur|n| j j}|dur|n| j j}|dur|n| j j}|du |duA r*td|r.dnd}|r4dnd}|   |durD| ||  du rcdu rc|durZ|jdd \ n	|jdd \ |durj|jn|j}|du r|t	j
 f|t	jd}d}| j jdkrdu r|du r|du rd}|du rt	  t||d	^}}}}W d   n1 sw   Y  n#t||d	^}}}}n|du rt	j|d
d}| j||d\}}| j||d}| jD ])}|r||f }||||||||d}|d }|rt|dkr||d f }q|r||f }| |}|r7t| d}|dur7t fdd|D }|sFtdd |||fD S t|||dS )  
        sliding_window_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding or far-away tokens. In ModernBert, only every few layers
            perform global attention, while the rest perform local attention. This mask is used to avoid attending to
            far-away tokens in the local attention layers when not using Flash Attention.
        indices (`torch.Tensor` of shape `(total_unpadded_tokens,)`, *optional*):
            Indices of the non-padding tokens in the input sequence. Used for unpadding the output.
        cu_seqlens (`torch.Tensor` of shape `(batch + 1,)`, *optional*):
            Cumulative sequence lengths of the input sequences. Used to index the unpadded tensors.
        max_seqlen (`int`, *optional*):
            Maximum sequence length in the batch excluding padding tokens. Used to unpad input_ids and pad output tensors.
        batch_size (`int`, *optional*):
            Batch size of the input sequences. Used to pad the output tensors.
        seq_len (`int`, *optional*):
            Sequence length of the input sequences including padding tokens. Used to pad the output tensors.
        Nz:You must specify exactly one of input_ids or inputs_embedsr>   r   r   Fr  T)ro   rp   )r   r   )r   )r   r   r'  ry   ro   r   r   r   c                 3   s     | ]}t | d V  qdS )rz  N)r   )rh  hsru  r   rv  r>   rc   	<genexpr>  s
    
z*ModernBertModel.forward.<locals>.<genexpr>c                 s   s    | ]	}|d ur|V  qd S r   r>   )rh  vr>   r>   rc   r}    s    )last_hidden_stater   
attentions)r   r   rw  use_return_dictr^   rZ  %warn_if_padding_and_no_attention_maskr   r   r{   onesr  r  no_gradr   arange	unsqueeze_update_attention_maskrk  rn  rV  ro  r   r   r   )r_   r   rp   r   rq   r   r   r   r   ru  rv  r   rw  rx  all_hidden_statesall_self_attentionsr   repadr   r   encoder_layerlayer_outputsr>   r|  rc   r     s   !



	


zModernBertModel.forwardc                 C   s   |r#| j jdkrtd d| j _n| j jdkr#td| j j d t|| j}t|jd 	d}t
||j }|| j jd k	d	d|j}|| t| jj}||fS )Nr  zOutputting attentions is only supported with the 'eager' attention implementation, not with "sdpa". Falling back to `attn_implementation="eager"`.r  zZOutputting attentions is only supported with the eager attention implementation, not with zT. Consider setting `attn_implementation="eager"`. Setting `output_attentions=False`.r   r   )r   r  rW  rX  r   rw   r{   r  r   r  absTrP   r   r   masked_filllogical_notfinfomin)r_   rp   r   global_attention_maskrowsdistancewindow_maskr   r>   r>   rc   r  
  s&   
"z&ModernBertModel._update_attention_maskNNNNNNNNNNNNN)rh   ri   rj   r   r@   rs  rt  r   r   r{   r   r   r   r  r   r   r   r   r  rn   r>   r>   ra   rc   rg  |  s`    	
"zrg  c                       s8   e Zd Zdef fddZdejdejfddZ  ZS )r=  r   c                    sN   t    || _t|j|j|j| _t|j	 | _
tj|j|j|jd| _d S )Nr   )r?   r@   r   r   r   rC   rW   r>  r   rX   r   r   rI   rJ   r   r   ra   r>   rc   r@   +  s
   
z!ModernBertPredictionHead.__init__r   rs   c                 C   r   r   )r   r   r>  r$  r>   r>   rc   r   2  s   z ModernBertPredictionHead.forward)	rh   ri   rj   r   r@   r{   r   r   rn   r>   r>   ra   rc   r=  *  s    r=  zd
    The ModernBert Model with a decoder head on top that is used for masked language modeling.
    )custom_introc                "       s   e Zd ZdgZdef fddZdd Zdejfdd	Z	e
jd
dde
jde
j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
j dee
j dee
j dee
j dee dee dee dee dee dee deee
j ef fdd Z  ZS )"r?  zdecoder.weightr   c                    s^   t  | || _t|| _t|| _tj|j	|j
|jd| _| jj| _| jj| _|   d S )Nr   )r?   r@   r   rg  r*  r=  headr   r   rC   rA   rU   r@  rZ   r[   rq  r   ra   r>   rc   r@   >  s   



zModernBertForMaskedLM.__init__c                 C   s   | j S r   r@  r   r>   r>   rc   get_output_embeddingsK  s   z+ModernBertForMaskedLM.get_output_embeddingsnew_embeddingsc                 C   s
   || _ d S r   r  )r_   r  r>   r>   rc   set_output_embeddingsN  s   
z+ModernBertForMaskedLM.set_output_embeddingsTr   rg   rs   c                 C   r#  r   )r@  r  rf   r>   r>   rc   compiled_headQ  r&  z#ModernBertForMaskedLM.compiled_headNr   rp   r   rq   r   rr   r   r   r   ru  rv  r   rw  rx  c                 K   sj  |dur|n| j j}|   | j jdkr|du r|du r|	du r|
du r?|du r?|dur6|jdd \}
}n	|jdd \}
}|durF|jn|j}|du rXtj|
|f|tjd}|du rt	  t
||||d\}}}}	}}W d   n1 syw   Y  nt
||||d\}}}}	}}| j||||||||	|
||||d}|d }| jr|dur|d}||jd d}|| jk}|| }|| }| j jr| |n| | |}d}|dur| j||fd	| j ji|}| j jdkr| j js|du rt nt	  t|||
|d
}W d   n	1 sw   Y  |s+|f}|dur)|f| S |S t|||j|jdS )ry  Nr  r   r   )ro   rp   rq   rr   r   rp   r   rq   r   r   r   r   ru  rv  r   rw  rx  r   rt   rA   rz  losslogitsr   r  )r   r  rZ  r  r   r   r{   r  r  r  r   r*  rZ   r   r[   r\   r  r@  r  loss_functionrA   r]   r   r   r   r   r  )r_   r   rp   r   rq   r   rr   r   r   r   ru  rv  r   rw  rx  r`   r   outputsr  mask_tokensr  r  rg   r>   r>   rc   r   U  s~   #


 zModernBertForMaskedLM.forwardNNNNNNNNNNNNNN)rh   ri   rj   _tied_weights_keysr   r@   r  r   r   r  r{   r   r   r  r   r   r   r   r  r   r   r   r   rn   r>   r>   ra   rc   r?  6  sj    
	
r?  z`
    The ModernBert Model with a sequence classification head on top that performs pooling.
    c                "          e Zd Zde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j	 d
eej	 deej	 deej	 dee
 dee
 dee
 dee dee dee deeej	 ef fddZ  ZS )rA  r   c                    s\   t  | |j| _|| _t|| _t|| _tj	
|j| _t	|j|j| _|   d S r   )r?   r@   
num_labelsr   rg  r*  r=  r  r{   r   r   rV   r   r   rC   rD  rq  r   ra   r>   rc   r@     s   

z,ModernBertForSequenceClassification.__init__Nr   rp   r   rq   r   rr   r   r   r   ru  rv  r   rw  rx  rs   c                 K   s  |dur|n| j j}|   | j||||||||	|
||||d}|d }| j jdkr3|dddf }n| j jdkrK||d jdd|jdd	d
 }| |}| |}| 	|}d}|dur| j j
du r| jdkrpd| j _
n| jdkr|jtjks|jtjkrd| j _
nd| j _
| j j
dkrt }| jdkr|| | }n+|||}n%| j j
dkrt }||d| j|d}n| j j
dkrt }|||}|s|f}|dur|f| S |S t|||j|jdS )aB  
        sliding_window_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding or far-away tokens. In ModernBert, only every few layers
            perform global attention, while the rest perform local attention. This mask is used to avoid attending to
            far-away tokens in the local attention layers when not using Flash Attention.
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence 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).
        indices (`torch.Tensor` of shape `(total_unpadded_tokens,)`, *optional*):
            Indices of the non-padding tokens in the input sequence. Used for unpadding the output.
        cu_seqlens (`torch.Tensor` of shape `(batch + 1,)`, *optional*):
            Cumulative sequence lengths of the input sequences. Used to index the unpadded tensors.
        max_seqlen (`int`, *optional*):
            Maximum sequence length in the batch excluding padding tokens. Used to unpad input_ids and pad output tensors.
        batch_size (`int`, *optional*):
            Batch size of the input sequences. Used to pad the output tensors.
        seq_len (`int`, *optional*):
            Sequence length of the input sequences including padding tokens. Used to pad the output tensors.
        Nr  r   r3   r7   rt   ry   r   T)rv   keepdim
regressionsingle_label_classificationmulti_label_classificationr  )r   r  rZ  r*  r5   r  rz   r  r   rD  problem_typer  rw   r{   longr   r	   squeezer   r   r   r   r   r  )r_   r   rp   r   rq   r   rr   r   r   r   ru  rv  r   rw  rx  r`   r  r  pooled_outputr  r  loss_fctrg   r>   r>   rc   r     sn   '




"


z+ModernBertForSequenceClassification.forwardr  )rh   ri   rj   r   r@   r   r   r{   r   r   r   r  r   r   r   r   rn   r>   r>   ra   rc   rA    s`    	
rA  zv
    The ModernBert Model with a token classification head on top, e.g. for Named Entity Recognition (NER) tasks.
    c                "       r  )rB  r   c                    V   t  | |j| _t|| _t|| _tj	|j
| _t|j|j| _|   d S r   r?   r@   r  rg  r*  r=  r  r{   r   r   rV   r   r   rC   rD  rq  r   ra   r>   rc   r@   H  s   

z)ModernBertForTokenClassification.__init__Nr   rp   r   rq   r   rr   r   r   r   ru  rv  r   rw  rx  rs   c                 C   s   |dur|n| j j}|   | j||||||||	|
||||d}|d }| |}| |}| |}d}|durIt }||d| j	|d}|s_|f|dd  }|dur]|f| S |S t
|||j|jdS )a  
        sliding_window_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding or far-away tokens. In ModernBert, only every few layers
            perform global attention, while the rest perform local attention. This mask is used to avoid attending to
            far-away tokens in the local attention layers when not using Flash Attention.
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
        indices (`torch.Tensor` of shape `(total_unpadded_tokens,)`, *optional*):
            Indices of the non-padding tokens in the input sequence. Used for unpadding the output.
        cu_seqlens (`torch.Tensor` of shape `(batch + 1,)`, *optional*):
            Cumulative sequence lengths of the input sequences. Used to index the unpadded tensors.
        max_seqlen (`int`, *optional*):
            Maximum sequence length in the batch excluding padding tokens. Used to unpad input_ids and pad output tensors.
        batch_size (`int`, *optional*):
            Batch size of the input sequences. Used to pad the output tensors.
        seq_len (`int`, *optional*):
            Sequence length of the input sequences including padding tokens. Used to pad the output tensors.
        Nr  r   rt   ry   r  )r   r  rZ  r*  r  r   rD  r   r   r  r   r   r  )r_   r   rp   r   rq   r   rr   r   r   r   ru  rv  r   rw  rx  r  r  r  r  r  rg   r>   r>   rc   r   T  sD   $


z(ModernBertForTokenClassification.forwardr  )rh   ri   rj   r   r@   r   r   r{   r   r   r   r  r   r   r   r   rn   r>   r>   ra   rc   rB  B  s`    	
rB  c                "       s   e Zd Zde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j d
eej deej deej dee	 dee	 dee	 dee
 dee
 dee
 deeej ef fddZ  ZS )rC  r   c                    r  r   r  r   ra   r>   rc   r@     s   

z'ModernBertForQuestionAnswering.__init__Nr   rp   r   rq   start_positionsend_positionsr   r   r   ru  rv  r   rw  rx  rs   c                 K   s  |dur|n| j j}|   | j|||||||	|
||||d}|d }| |}| |}| |}|jddd\}}|d	 }|d	 }d}|dur_|dur_| j
||||fi |}|sv||f|dd  }|durt|f| S |S t||||j|jdS )ry  N)rp   r   rq   r   r   r   ru  rv  r   rw  rx  r   ry   rt   r   )r  start_logits
end_logitsr   r  )r   r  rZ  r*  r  r   rD  splitr  r   r  r   r   r  )r_   r   rp   r   rq   r  r  r   r   r   ru  rv  r   rw  rx  r`   r  r  r  r  r  r  rg   r>   r>   rc   r     sH   #


z&ModernBertForQuestionAnswering.forwardr  )rh   ri   rj   r   r@   r   r   r{   r   r   r  r   r   r   r   rn   r>   r>   ra   rc   rC    s^    	
rC  )r   rg  r)  r?  rA  rB  rC  r   r  )Ur;  
contextlibr   typingr   r   r   r{   torch.nn.functionalr   r   r
  torch.utils.checkpointtorch.nnr   r   r	   activationsr   configuration_utilsr   modeling_attn_mask_utilsr   modeling_layersr   modeling_outputsr   r   r   r   r   modeling_utilsr   utilsr   r   r   utils.import_utilsr   gemma.modeling_gemmar   r   flash_attn.flash_attn_interfacer   flash_attn.layers.rotaryr   flash_attn.ops.triton.rotaryr   object
get_loggerrh   rW  r   r   r   r   r   r   autogradFunctionr   r   r   r:  r   r   r   r   r  r   r  rw   r  r  r  r   r  r)  rg  r=  r?  rA  rB  rC  __all__r>   r>   r>   rc   <module>   s2  
 H$
)
;
5
	
.
	
+


$P.  . wZ[