o
    Zh                    @   s   d dl Z d dlmZ d dlmZmZ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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		dWde	j5de	j5dee	j5 dee	j5 dee	j5e	j5e	j5e6ee	j5 ee	j5 f f
ddZ7de	j5de	j5de6de6de	j5f
dd Z8G d!d" d"e	j9j:Z;		dWd#ee	j5 d$ee6 fd%d&Z<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(ZA	/dXd0d1d2e	j5de	j5d3e	j5dee	jB d4ee6e6f d5e6d6e6d7eeC deee	j5e	j5f ee	j5 f fd8d9ZDe	jEfd0d1d2e	j5d:e=d#e	j5d$e6d4ee6e6f d5e6d6e6d;e	jFdee	j5 fd<d=ZGd0d1d2e	j5de	j5d3e	j5dee	jB d4ee6e6f d5e6d6e6dee	j5 fd>d?ZHeGeDeHd@ZIG dAd1 d1ej>ZJG dBdC dCej>ZKe"G dDdE dEe ZLe"G dFdG dGeLZMG dHdI dIej>ZNe"dJdKG dLdM dMeLZOe"dNdKG dOdP dPeLZPe"dQdKG dRdS dSeLZQe"G dTdU dUeLZRg dVZSdS )Y    N)nullcontext)DictLiteralOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)PretrainedConfig)_prepare_4d_attention_mask)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
    ```Z
modernbertZpast_key_values             gelu    {Gz?       @h㈵>Fk  j  i       A        r           @TclsNclassifier_poolingr2   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_idr5   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_biasr4   classifier_dropoutclassifier_biasclassifier_activationdeterministic_flash_attnsparse_predictionsparse_pred_ignore_indexreference_compilerepad_logits_with_grad
ValueError)%selfr@   rB   rC   rD   rE   rM   rA   rF   rG   rH   rI   r7   r9   r8   r:   r;   rJ   rK   rL   rN   rO   rP   rQ   rR   rS   rT   r4   rU   rV   rW   rX   rY   rZ   r[   r\   kwargs	__class__r=   `/var/www/auris/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^   outputr`   r=   rb   rc      s   
zModernBertConfig.to_dict)#r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   Fr+   r,   r-   r-   r,   r.   Fr/   r   r0   r1   r/   Fr/   Tr2   r/   Fr&   FFr3   NF)
__name__
__module____qualname____doc__Z
model_typeZkeys_to_ignore_at_inferencer   r?   rc   __classcell__r=   r=   r`   rb   r    5   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torchZint32Znonzeroflattenintmaxitemr   
functionalpadZcumsumrs   shapeview)rl   rm   rn   ro   Zseqlens_in_batchindicesZmax_seqlen_in_batch
cu_seqlensZunpadded_inputsbatchseqlenrestr   Zunpadded_position_idsZunpadded_labelsr=   r=   rb   _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)
    rv   )rt   device)rs   rx   Zzerosrt   r   r   r   )rl   r   r   r   rf   Zpadded_inputs_r   r=   r=   rb   _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   rq   r   FT)seqlen_offsetsr   r   interleavedinplace)
contiguousr   r   r   Zsave_for_backwardr   )ctxqkvcossinr   r   	total_nnz_three_nheadsheaddimZqkr=   r=   rb   forwardB  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   rq   r   FT)r   r   r   r   r   	conjugate)Zsaved_tensorsr   r   r   r   r   )
r   dor   r   r   r   r   r   r   Zdqkr=   r=   rb   backwarda  s    zApplyRotaryEmbUnpad.backwardNN)
rg   rh   ri   staticmethodr   rx   Tensorrz   r   r   r=   r=   r=   rb   r   A  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=   rb   apply_rotary_unpaddedx  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.
    r1   Nrs   baser   r   rt   c                    sT   t  j||d|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.
        TF)rs   r   Zpos_idx_in_fp32r   r   Nr   rt   )r>   r?   r   _update_cos_sin_cache)r^   rs   r   r   r   rt   r`   r=   rb   r?     s
   z*ModernBertUnpaddedRotaryEmbedding.__init__r   r   rp   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   rt   r   Z_cos_cachedZ_sin_cached)r^   r   r   r   r=   r=   rb   r     s   z)ModernBertUnpaddedRotaryEmbedding.forwardc                 C   s   d| j  d| j d| j S )Nzdim=z, base=z, scale_base=)rs   r   Z
scale_baser^   r=   r=   rb   
extra_repr  s   z,ModernBertUnpaddedRotaryEmbedding.extra_repr)r1   NNNN)rg   rh   ri   rj   rz   floatr   rx   r   rt   r?   r   r   r   r   strr   rk   r=   r=   r`   rb   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)Zpadding_idxZepsbias)r>   r?   r   r   Z	Embeddingr@   rB   r7   tok_embeddings	LayerNormrH   rI   normDropoutrQ   dropr^   r   r`   r=   rb   r?     s
   
zModernBertEmbeddings.__init__TZdynamic	input_idsrp   c                 C      |  | | |S r   )r   r   r   )r^   r   r=   r=   rb   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=   rb   r     s   zModernBertEmbeddings.forwardr   )rg   rh   ri   rj   r    r?   rx   compile
LongTensorr   r   r   r   rk   r=   r=   r`   rb   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   LinearrB   rz   rC   rR   Wir   rM   actr   rS   r   Wor   r`   r=   rb   r?     s   
 zModernBertMLP.__init__r   rp   c                 C   s2   |  |jddd\}}| | | || S )Nr   rq   rs   )r   chunkr   r   r   )r^   r   inputZgater=   r=   rb   r     s   zModernBertMLP.forward)
rg   rh   ri   rj   r    r?   rx   r   r   rk   r=   r=   r`   rb   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   rs   r   r   c                    s.   t  j| ||d | jd |||d\}| _d S )N)r   r   )rs   r   )r>   r?   Zrope_init_fnZattention_scaling)r^   r   rs   r   r   Zinv_freqr`   r=   rb   r?     s   z"ModernBertRotaryEmbedding.__init__r   )rg   rh   ri   r    rz   r   r   rx   r   r?   rk   r=   r=   r`   rb   r     s    .r   FmoduleModernBertAttentionr   sliding_window_maskrO   bsrs   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rn   r   rv   r   r         ࿩rq   rq   rq   rr   )ptraining)
rotary_emb	transposeunbindr   head_dimrx   matmulr   r}   ZsoftmaxZfloat32tort   ZdropoutrL   r   r   r   )r   r   rm   r   rn   rO   r   rs   r   _kwargsr   r   querykeyvaluescaleZattn_weightsattn_outputr=   r=   rb   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   r/   )r   r   	dropout_pZdeterministicZwindow_size)
rt   rx   float16bfloat16r   r   r   rL   rX   r   )r   r   r   r   r   rO   r   rs   r   r   Zconvert_dtypeZ
orig_dtypeattnr=   r=   rb   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   rv   r   r   r   r/   )r   Z	attn_maskrq   )
r   r   r   r   FZscaled_dot_product_attentionr   rL   r   r   )r   r   rm   r   rn   rO   r   rs   r   r   r   r   r   r   r   r=   r=   rb   sdpa_attention_forwardO  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   )rs   r   r   )r   rs   r   r/   )r>   r?   r   r   rB   rE   r]   rL   rX   	num_headsr   all_head_sizer   r   rK   WqkvrN   rO   rJ   rA   rP   _attn_implementationr   r   r   r   r   Identityout_dropsetZpruned_heads)r^   r   r   Z
rope_thetarA   r`   r=   rb   r?     s<   




 zModernBertAttention.__init__Fr   r   rp   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   rq   r   )r   r   rO   r   rs   r   rv   )r   r   r   r   r   r   r   MODERNBERT_ATTENTION_FUNCTIONr   rO   r   r   r   )r^   r   r   r_   r   r   attn_outputsr=   r=   rb   r     s(   



zModernBertAttention.forwardr   F)rg   rh   ri   rj   r    r   rz   r?   rx   r   boolr   rk   r=   r=   r`   rb   r   y  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   rB   rH   rI   r   r   mlp_normr   mlp)r^   r   r   r`   r=   rb   r?     s   
zModernBertEncoderLayer.__init__Tr   r   rp   c                 C      |  | |S r   )r   r   r^   r   r=   r=   rb   compiled_mlp     z#ModernBertEncoderLayer.compiled_mlpFrm   r   rn   r   r   r   c           
   	   C   sf   | j | |||||||d}||d  }| jjr| |n| | |}	||	 }|f|dd   S )Nrm   r   rn   r   r   r   r   rv   )r   r   r   r[   r   r   r   )
r^   r   rm   r   rn   r   r   r   r   Z
mlp_outputr=   r=   rb   r     s    
	zModernBertEncoderLayer.forwardr   )NNNNNF)rg   rh   ri   r    r   rz   r?   rx   r   r   r   r   r   r   rk   r=   r=   r`   rb   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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 )Nr/   )r6   r  ab)r   initZtrunc_normal_weight
isinstancer   r   Zzeros_)r   r  Zcutoff_factorr=   rb   init_weight  s   
z<ModernBertPreTrainedModel._init_weights.<locals>.init_weightr)   r   )inout	embedding	final_outr  r	  r
  r  g      ?) r   rG   r   Moduler   rF   mathsqrtrD   rB   r  r   r   r   r   r   r   r   ModernBertPredictionHeaddenseModernBertForMaskedLMdecoder#ModernBertForSequenceClassification ModernBertForTokenClassificationModernBertForQuestionAnswering
classifierr   r  dataZfill_r   Zzero_)r^   r   r  Zstdsr=   r  rb   _init_weights  s@   






z'ModernBertPreTrainedModel._init_weightsNuse_flash_attention_2torch_dtype
device_mapcheck_device_mapc              	      s^   |j d u r#d|_ z| j|tj|d|dW S  ttfy"   d |_ Y nw t j||tj||dS )Nr   F)r  r  Zhard_check_onlyr  )r  r  r  r  )Z_attn_implementation_internalZ_check_and_enable_flash_attn_2rx   r   r]   ImportErrorr>   _autoset_attn_implementation)r2   r   r  r  r  r  r`   r=   rb   r  0  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_maprv   zqIf `accelerate` split the model across devices, `torch.compile` will not work. Falling back to non-compiled mode.Z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lenr   loggerwarning_oncer   typer   r   r=   r=   rb   _maybe_set_compileQ  s.   z,ModernBertPreTrainedModel._maybe_set_compilec                    s<   t  j|i |}| jjdv r| jjrtd d| j_|S )N>   TNzcResizing token embeddings with `torch.compile` is not supported. Falling back to non-compiled mode.F)r>   resize_token_embeddingsr   r[   r$  r%  )r^   argsr_   Zmodel_embedsr`   r=   rb   r(  p  s   z1ModernBertPreTrainedModel.resize_token_embeddings)FNNT)rg   rh   ri   r    Zconfig_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_supports_flash_attn_2Z_supports_sdpaZ_supports_flex_attnr   r  r  classmethodr   r   rx   rt   r   r   r   rz   r  r'  r(  rk   r=   r=   r`   rb   r     s2    / 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=   rb   
<listcomp>  s    z,ModernBertModel.__init__.<locals>.<listcomp>r   F)r>   r?   r   r   
embeddingsr   Z
ModuleListrangerD   layersr   rB   rH   rI   
final_normgradient_checkpointing	post_initr   r`   r-  rb   r?     s   
zModernBertModel.__init__c                 C   s   | j jS r   r/  r   r   r=   r=   rb   get_input_embeddings  s   z$ModernBertModel.get_input_embeddingsc                 C   s   || j _d S r   r5  )r^   r   r=   r=   rb   set_input_embeddings  s   z$ModernBertModel.set_input_embeddingsNr   rm   r   rn   r   r   r   r   
batch_sizeseq_lenr   output_hidden_statesreturn_dictrp   .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 }| jr| jr| |j|||||||}n||||||||d}|d }|r"t|dkr"||d f }q|r+||f }| |}|rMt| d}|durMt fdd|D }|s\t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)rl   rm   )r   r   )r   )r   r   r   rv   rl   r   r   r   c                 3   s     | ]}t | d V  qdS )r=  N)r   )r,  hsr8  r   r9  r=   rb   	<genexpr>
  s
    
z*ModernBertModel.forward.<locals>.<genexpr>c                 s   s    | ]	}|d ur|V  qd S r   r=   )r,  vr=   r=   rb   r@    s    )last_hidden_stater   
attentions)r   r   r:  use_return_dictr]   r'  Z%warn_if_padding_and_no_attention_maskr   r   rx   onesr   r   no_gradr   arange	unsqueeze_update_attention_maskr/  r1  r3  r   Z_gradient_checkpointing_func__call__r#  r2  r   tupler   )r^   r   rm   r   rn   r   r   r   r   r8  r9  r   r:  r;  Zall_hidden_statesZall_self_attentionsr   Zrepadr   r   Zencoder_layerZlayer_outputsr=   r?  rb   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   r$  r%  r   rt   rx   rG  r   rH  absTrO   r   r   Zmasked_fillZlogical_notZfinfomin)r^   rm   r   Zglobal_attention_maskrowsZdistanceZwindow_maskr   r=   r=   rb   rI    s&   
"z&ModernBertModel._update_attention_maskNNNNNNNNNNNNN)rg   rh   ri   r    r?   r6  r7  r   r   rx   r   r   rz   r   r   r   r   r   rI  rk   r=   r=   r`   rb   r+  }  sb    	
 "r+  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   rB   rV   r  r   rW   r   r   rH   rI   r   r   r`   r=   rb   r?   8  s
   
z!ModernBertPredictionHead.__init__r   rp   c                 C   r   r   )r   r   r  r   r=   r=   rb   r   ?  s   z ModernBertPredictionHead.forward)	rg   rh   ri   r    r?   rx   r   r   rk   r=   r=   r`   rb   r  7  s    r  zd
    The ModernBert Model with a decoder head on top that is used for masked language modeling.
    )Z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   r+  r   r  headr   r   rB   r@   rT   r  rY   rZ   r4  r   r`   r=   rb   r?   K  s   



zModernBertForMaskedLM.__init__c                 C   s   | j S r   r  r   r=   r=   rb   get_output_embeddingsX  s   z+ModernBertForMaskedLM.get_output_embeddingsnew_embeddingsc                 C   s
   || _ d S r   rR  )r^   rT  r=   r=   rb   set_output_embeddings[  s   
z+ModernBertForMaskedLM.set_output_embeddingsTr   rf   rp   c                 C   r   r   )r  rQ  re   r=   r=   rb   compiled_head^  r   z#ModernBertForMaskedLM.compiled_headNr   rm   r   rn   r   ro   r   r   r   r8  r9  r   r:  r;  c                 K   sb  |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||| j jd	}| 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 )r<  Nr   r   r   )rl   rm   rn   ro   r   rm   r   rn   r   r   r   r   r8  r9  r   r:  r;  r   rq   )r@   r=  losslogitsr   rC  )r   rD  r'  r   r   r   rx   rE  r   rF  r   r   rY   r   rZ   r[   rV  r  rQ  loss_functionr@   r\   r   r   r   r   rC  )r^   r   rm   r   rn   r   ro   r   r   r   r8  r9  r   r:  r;  r_   r   outputsrB  Zmask_tokensrZ  rY  rf   r=   r=   rb   r   b  s~   #


 zModernBertForMaskedLM.forwardNNNNNNNNNNNNNN)rg   rh   ri   Z_tied_weights_keysr    r?   rS  r   r   rU  rx   r   r   rV  r   r   r   rz   r   r   r   r   r   rk   r=   r=   r`   rb   r  C  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 )r  r   c                    s\   t  | |j| _|| _t|| _t|| _tj	
|j| _t	|j|j| _|   d S r   )r>   r?   
num_labelsr   r+  r   r  rQ  rx   r   r   rU   r   r   rB   r  r4  r   r`   r=   rb   r?     s   

z,ModernBertForSequenceClassification.__init__Nr   rm   r   rn   r   ro   r   r   r   r8  r9  r   r:  r;  rp   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.
        NrW  r   r2   r6   rq   rv   r   T)rs   ZkeepdimZ
regressionZsingle_label_classificationZmulti_label_classificationrX  )r   rD  r'  r   r4   rH  rw   rQ  r   r  Zproblem_typer_  rt   rx   longrz   r   squeezer
   r   r	   r   r   rC  )r^   r   rm   r   rn   r   ro   r   r   r   r8  r9  r   r:  r;  r_   r\  rB  Zpooled_outputrZ  rY  loss_fctrf   r=   r=   rb   r     sn   '




"


z+ModernBertForSequenceClassification.forwardr]  )rg   rh   ri   r    r?   r   r   rx   r   r   rz   r   r   r   r   r   rk   r=   r=   r`   rb   r    s`    	
r  zv
    The ModernBert Model with a token classification head on top, e.g. for Named Entity Recognition (NER) tasks.
    c                "       r^  )r  r   c                    V   t  | |j| _t|| _t|| _tj	|j
| _t|j|j| _|   d S r   r>   r?   r_  r+  r   r  rQ  rx   r   r   rU   r   r   rB   r  r4  r   r`   r=   rb   r?   U  s   

z)ModernBertForTokenClassification.__init__Nr   rm   r   rn   r   ro   r   r   r   r8  r9  r   r:  r;  rp   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.
        NrW  r   rq   rv   rX  )r   rD  r'  r   rQ  r   r  r
   r   r_  r   r   rC  )r^   r   rm   r   rn   r   ro   r   r   r   r8  r9  r   r:  r;  r\  rB  rZ  rY  rb  rf   r=   r=   rb   r   a  sD   $


z(ModernBertForTokenClassification.forwardr]  )rg   rh   ri   r    r?   r   r   rx   r   r   rz   r   r   r   r   r   rk   r=   r=   r`   rb   r  O  s`    	
r  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 )r  r   c                    rc  r   rd  r   r`   r=   rb   r?     s   

z'ModernBertForQuestionAnswering.__init__Nr   rm   r   rn   start_positionsend_positionsr   r   r   r8  r9  r   r:  r;  rp   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 )r<  N)rm   r   rn   r   r   r   r8  r9  r   r:  r;  r   rv   rq   r   )rY  start_logits
end_logitsr   rC  )r   rD  r'  r   rQ  r   r  splitra  r   r[  r   r   rC  )r^   r   rm   r   rn   re  rf  r   r   r   r8  r9  r   r:  r;  r_   r\  rB  rZ  rg  rh  rY  rf   r=   r=   rb   r     sH   #


z&ModernBertForQuestionAnswering.forwardrP  )rg   rh   ri   r    r?   r   r   rx   r   rz   r   r   r   r   r   rk   r=   r=   r`   rb   r    s^    	
r  )r    r+  r   r  r  r  r  r   r   )Tr  
contextlibr   typingr   r   r   r   r   rx   Ztorch.nn.functionalr   r}   r   Ztorch.utils.checkpointZtorch.nnr	   r
   r   Zactivationsr   Zconfiguration_utilsr   Zmodeling_attn_mask_utilsr   Zmodeling_outputsr   r   r   r   r   Zmodeling_utilsr   utilsr   r   r   Zutils.import_utilsr   Zgemma.modeling_gemmar   r   Zflash_attn.flash_attn_interfacer   Zflash_attn.layers.rotaryr   Zflash_attn.ops.triton.rotaryr   objectZ
get_loggerrg   r$  r    r   rz   r   r   ZautogradFunctionr   r   r   r  r   r   r   r   r   r   r   rt   r   r   r   r   r   r   r+  r  r  r  r  r  __all__r=   r=   r=   rb   <module>   s0  
 H$
)
;
5
	
.
	
+


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