o
    wi                     @   s  d dl Z d dlmZ d dlmZmZ d dlZd dlm  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 dd	lmZ dd
lmZmZmZmZmZ ddlmZmZ ddlmZ ddl m!Z!m"Z"m#Z# ddl$m%Z% ddl&m'Z' e" rd dl(m)Z) d dl*m+Z+ d dl,m-Z- ne.Z+e#/e0Z1G dd dej2j3Z4		dZdeej5 dee6 fddZ7G dd de+Z8G dd dej9Z:G dd dej9Z;G d d! d!ej9Z<d"d# Z=d[d$d%Z>	&d\d'd(d)ej5d*ej5d+ej5d,eej? d-e@e6e6f d.e6d/e6d0eeA d1ee@ej5ej5f e@ej5 f fd2d3ZBejCfd'd(d)ej5d4e8dej5de6d-e@e6e6f d.e6d/e6d5ejDd1e@ej5 fd6d7ZEd'd(d)ej5d*ej5d+ej5d,eej? d-e@e6e6f d.e6d/e6d1e@ej5 fd8d9ZFeEeBeFd:ZGG d;d( d(ej9ZHG d<d= d=eZIe!G d>d? d?eZJ		dZd@ej5d*ej5d,eej5 dAeej5 d1e@ej5ej5ej5e6eej5 eej5 f f
dBdCZKd@ej5dDej5dEe6dFe6d1ej5f
dGdHZLe!G dIdJ dJeJZMG dKdL dLej9ZNe!dMdNG dOdP dPeJZOe!dQdNG dRdS dSeJZPe!dTdNG dUdV dVeJZQe!G dWdX dXeJZRg dYZSdS )]    N)nullcontext)OptionalUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)_prepare_4d_attention_mask)GradientCheckpointingLayer)BaseModelOutputMaskedLMOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)PreTrainedModel)auto_docstringis_flash_attn_2_availablelogging)is_triton_available   )ModernBertConfig) flash_attn_varlen_qkvpacked_func)RotaryEmbedding)apply_rotaryc                   @   s>   e Zd Ze		ddeej dee fddZedd Z	dS )	ApplyRotaryEmbUnpadN
cu_seqlens
max_seqlenc              
   C   sd   |  }|j\}}}}	|d d d df |d|	}
t|
||d||ddd | ||| || _|S )N   r   FT)seqlen_offsetsr   r    interleavedinplace)
contiguousshapeviewr   save_for_backwardr    )ctxqkvcossinr   r    	total_nnz_three_nheadsheaddimqk r3   o/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/transformers/models/modernbert/modeling_modernbert.pyforward<   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!   r"   r   FT)r#   r   r    r$   r%   	conjugate)saved_tensorsr&   r'   r(   r   r    )
r*   dor,   r-   r   r.   r/   r0   r1   dqkr3   r3   r4   backward[   s    zApplyRotaryEmbUnpad.backwardNN)
__name__
__module____qualname__staticmethodr   torchTensorintr5   r:   r3   r3   r3   r4   r   ;   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    r3   r3   r4   apply_rotary_unpaddedr   s   rD   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.
         @Ndimbaser    devicedtypec                    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)rG   rH   rI   r$   NrI   rJ   )super__init__r    _update_cos_sin_cache)selfrG   rH   r    rI   rJ   	__class__r3   r4   rM      s
   z*ModernBertUnpaddedRotaryEmbedding.__init__r+   r   returnc                 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
        NrK   r   r    )rN   rI   rJ   rD   _cos_cached_sin_cached)rO   r+   r   r    r3   r3   r4   r5      s   z)ModernBertUnpaddedRotaryEmbedding.forwardc                 C   s   d| j  d| j d| j S )Nzdim=z, base=z, scale_base=)rG   rH   
scale_baserO   r3   r3   r4   
extra_repr   s   z,ModernBertUnpaddedRotaryEmbedding.extra_repr)rF   NNNN)r<   r=   r>   __doc__rB   floatr   r@   rI   rJ   rM   rA   r   tupler5   strrX   __classcell__r3   r3   rP   r4   rE      s8    
rE   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)rL   rM   r`   r   	Embedding
vocab_sizehidden_sizepad_token_idtok_embeddings	LayerNormnorm_eps	norm_biasnormDropoutembedding_dropoutdroprO   r`   rP   r3   r4   rM      s
   
zModernBertEmbeddings.__init__Tdynamic	input_idsrR   c                 C      |  | | |S rY   )rp   rm   ri   )rO   rt   r3   r3   r4   compiled_embeddings   s   z(ModernBertEmbeddings.compiled_embeddingsNinputs_embedsc                 C   sH   |d ur|  | |}|S | jjr| |n
|  | | |}|S rY   )rp   rm   r`   reference_compilerv   ri   )rO   rt   rw   hidden_statesr3   r3   r4   r5      s   zModernBertEmbeddings.forwardr;   )r<   r=   r>   rZ   r   rM   r@   compile
LongTensorrA   rv   r   r5   r^   r3   r3   rP   r4   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!   rd   )rL   rM   r`   r   Linearrg   rB   intermediate_sizemlp_biasWir
   hidden_activationactrn   mlp_dropoutrp   Worq   rP   r3   r4   rM      s   
 zModernBertMLP.__init__ry   rR   c                 C   s2   |  |jddd\}}| | | || S )Nr!   r"   rG   )r   chunkr   rp   r   )rO   ry   inputgater3   r3   r4   r5      s   zModernBertMLP.forward)
r<   r=   r>   rZ   r   rM   r@   rA   r5   r^   r3   r3   rP   r4   r|      s    r|   c                
       sJ   e Zd Zd
dedededeej f fddZ	e
 edd	 Z  ZS )ModernBertRotaryEmbeddingNr`   rG   rH   rI   c                    s   t    t|dr|jd ur|jd|jd| _nd| _|j| _|j| _|| _	t
| j | _| jd |||d\}| _| jd|dd | j| _d S )	Nrope_scaling	rope_typetypedefault)rG   rH   inv_freqF)
persistent)rL   rM   hasattrr   getr   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr`   r   rope_init_fnattention_scalingregister_bufferr   original_inv_freq)rO   r`   rG   rH   rI   r   rP   r3   r4   rM      s   
z"ModernBertRotaryEmbedding.__init__c           
      C   s   | j d d d d f  |jd dd|j}|d d d d d f  }t|jjtr6|jjdkr6|jjnd}t	j
|dd+ | |  dd}t	j||fdd	}| | j }| | j }	W d    n1 smw   Y  |j|jd
|	j|jd
fS )Nr   r"   r   mpscpuF)device_typeenabledr!   r   )rJ   )r   r[   expandr'   torI   
isinstancer   r]   r@   autocast	transposecatr,   r   r-   rJ   )
rO   xposition_idsinv_freq_expandedposition_ids_expandedr   freqsembr,   r-   r3   r3   r4   r5     s   0&z!ModernBertRotaryEmbedding.forwardrY   )r<   r=   r>   r   rB   r[   r   r@   rI   rM   no_gradr   r5   r^   r3   r3   rP   r4   r      s
    &r   c                 C   sH   | dd| j d d f }| d| j d d df }tj| |fddS )z*Rotates half the hidden dims of the input..Nr"   r!   r   )r'   r@   r   )r   x1x2r3   r3   r4   rotate_half  s   r   c                 C   sD   | |}| |}| | t| |  }|| t||  }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )	unsqueezer   )qkr,   r-   r   unsqueeze_dimq_embedk_embedr3   r3   r4   apply_rotary_pos_emb  s
   

r   FmoduleModernBertAttentionr+   attention_masksliding_window_maskr   local_attentionbsrG   output_attentionsrR   c	                 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r   r	   r   r!   r         ࿩r"   r"   r"   rG   rJ   )ptraining)
rotary_embr   unbindr   head_dimr@   matmulr   
functionalsoftmaxfloat32r   rJ   dropoutattention_dropoutr   r&   r(   )r   r+   r   r   r   r   r   rG   r   _kwargsr,   r-   querykeyvaluescaleattn_weightsattn_outputr3   r3   r4   eager_attention_forward6  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 )NrS           )r   r    	dropout_pdeterministicwindow_size)
rJ   r@   float16bfloat16r   r   r   r   deterministic_flash_attnr(   )r   r+   r   r   r    r   r   rG   r   r   convert_dtype
orig_dtypeattnr3   r3   r4   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	   r   r!   r   r   r   )r   	attn_maskr"   )
r   r   r   r   Fscaled_dot_product_attentionr   r   r&   r(   )r   r+   r   r   r   r   r   rG   r   r,   r-   r   r   r   r   r3   r3   r4   sdpa_attention_forward  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   )rG   r    rH   )r`   rG   rH   r   )rL   rM   r`   r   rg   num_attention_heads
ValueErrorr   r   	num_headsr   all_head_sizer   r~   attention_biasWqkvglobal_attn_every_n_layersr   global_rope_thetar   local_rope_theta_attn_implementationrE   r   r   r   rn   Identityout_dropsetpruned_heads)rO   r`   r   
rope_thetar   rP   r3   r4   rM     s<   




 zModernBertAttention.__init__Fry   r   rR   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   r"   r	   )r+   r   r   r   rG   r   r   )r   r'   r`   r   r(   r   r   MODERNBERT_ATTENTION_FUNCTIONr   r   r   r   r   )rO   ry   r   kwargsr+   r   attn_outputsr3   r3   r4   r5     s(   



zModernBertAttention.forwardrY   F)r<   r=   r>   rZ   r   r   rB   rM   r@   rA   boolr5   r^   r3   r3   rP   r4   r     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   rb   )r`   r   )rL   rM   r`   r   r   	attn_normrj   rg   rk   rl   r   r   mlp_normr|   mlp)rO   r`   r   rP   r3   r4   rM     s   
zModernBertEncoderLayer.__init__Trr   ry   rR   c                 C      |  | |S rY   )r   r   rO   ry   r3   r3   r4   compiled_mlp     z#ModernBertEncoderLayer.compiled_mlpFr   r   r   r   r    r   c           
   	   C   sf   | j | |||||||d}||d  }| jjr| |n| | |}	||	 }|f|dd   S )Nr   r   r   r   r    r   r   r   )r   r   r`   rx   r  r   r   )
rO   ry   r   r   r   r   r    r   r   
mlp_outputr3   r3   r4   r5     s    
	zModernBertEncoderLayer.forwardrY   )NNNNNF)r<   r=   r>   r   r   rB   rM   r@   rz   rA   r  r{   r   r5   r^   r3   r3   rP   r4   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 )Nr   )meanr  ab)r   inittrunc_normal_weightr   r~   rd   zeros_)r   r  cutoff_factorr3   r4   init_weight=  s   
z<ModernBertPreTrainedModel._init_weights.<locals>.init_weightg       @r   )inout	embedding	final_outr  r  r  r  g      ?) r`   initializer_cutoff_factorr   Moduler[   initializer_rangemathsqrtnum_hidden_layersrg   r   r_   ri   r|   r   r   r   r   ModernBertPredictionHeaddenseModernBertForMaskedLMdecoder#ModernBertForSequenceClassification ModernBertForTokenClassificationModernBertForQuestionAnswering
classifierrj   r  datafill_rd   zero_)rO   r   r  stdsr3   r  r4   _init_weights8  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)r*  r+  hard_check_onlyr,  )r*  r+  r,  )_attn_implementation_internal_check_and_enable_flash_attn_2r@   r   r   ImportErrorrL   _autoset_attn_implementation)clsr`   r*  r+  r,  rP   r3   r4   r1  g  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_mapr   zqIf `accelerate` split the model across devices, `torch.compile` will not work. Falling back to non-compiled mode.r   z|Compiling the model with `torch.compile` and using a `torch.mps` device is not supported. Falling back to non-compiled mode.r   z|Compiling the model with `torch.compile` and using a `torch.cpu` device is not supported. Falling back to non-compiled mode.)
r`   rx   r   lenr3  loggerwarning_oncerI   r   r   rW   r3   r3   r4   _maybe_set_compile  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)rL   resize_token_embeddingsr`   rx   r5  r6  )rO   argsr   model_embedsrP   r3   r4   r8    s   z1ModernBertPreTrainedModel.resize_token_embeddings)NNT)r<   r=   r>   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_supports_flash_attn_2_supports_sdpa_supports_flex_attnr   r  r)  classmethodr   r@   rJ   r   r]   dictrB   r   r1  r7  r8  r^   r3   r3   rP   r4   r  .  s,    /r  inputslabelsc                 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
    r"   r   F)as_tupler   )r   r   r!   N)sumr@   int32nonzeroflattenrB   maxitemr   r   padcumsumrG   r'   r(   )rD  r   r   rE  seqlens_in_batchindicesmax_seqlen_in_batchr   unpadded_inputsbatchseqlenrestr'   unpadded_position_idsunpadded_labelsr3   r3   r4   _unpad_modernbert_input  s   rX  rP  rS  rT  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)
    r   )rJ   rI   )rG   r@   zerosrJ   rI   r(   r'   )rD  rP  rS  rT  outputpadded_inputs_rU  r3   r3   r4   _pad_modernbert_output  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 r3   )r   ).0r   r`   r3   r4   
<listcomp>  s    z,ModernBertModel.__init__.<locals>.<listcomp>rb   F)rL   rM   r`   r_   
embeddingsr   
ModuleListranger  layersrj   rg   rk   rl   
final_normgradient_checkpointing	post_initrq   rP   r`  r4   rM     s   
zModernBertModel.__init__c                 C   s   | j jS rY   rb  ri   rW   r3   r3   r4   get_input_embeddings  s   z$ModernBertModel.get_input_embeddingsc                 C   s   || j _d S rY   ri  )rO   r   r3   r3   r4   set_input_embeddings
  s   z$ModernBertModel.set_input_embeddingsNrt   r   r   r   rw   rP  r   r    
batch_sizeseq_lenr   output_hidden_statesreturn_dictrR   .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_embedsr3   r!   rK   Fr   T)rD  r   )rI   r   )r   )rt   rw   r  r   rD  rP  rS  rT  c                 3   s     | ]}t | d V  qdS )rq  N)r]  )r_  hsrl  rP  rm  r3   r4   	<genexpr>{  s
    
z*ModernBertModel.forward.<locals>.<genexpr>c                 s   s    | ]	}|d ur|V  qd S rY   r3   )r_  vr3   r3   r4   rt    s    )last_hidden_statery   
attentions)r`   r   rn  use_return_dictr   r7  %warn_if_padding_and_no_attention_maskr'   rI   r@   onesr   r   r   rX  aranger   _update_attention_maskrb  re  r4  rf  r]  r\   r   )rO   rt   r   r   r   rw   rP  r   r    rl  rm  r   rn  ro  all_hidden_statesall_self_attentionsrI   repadr\  ry   encoder_layerlayer_outputsr3   rs  r4   r5     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   r5  r6  r   rJ   r@   r{  r'   r   absTr   r   rI   masked_filllogical_notfinfomin)rO   r   r   global_attention_maskrowsdistancewindow_maskr   r3   r3   r4   r|    s&   
"z&ModernBertModel._update_attention_maskNNNNNNNNNNNNN)r<   r=   r>   r   rM   rj  rk  r   r   r@   r{   rA   rB   r   r   r\   r   r5   r|  r^   r3   r3   rP   r4   r^    s`    	
"zr^  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 )Nrb   )rL   rM   r`   r   r~   rg   classifier_biasr  r
   classifier_activationr   rj   rk   rl   rm   rq   rP   r3   r4   rM     s
   
z!ModernBertPredictionHead.__init__ry   rR   c                 C   ru   rY   )rm   r   r  r  r3   r3   r4   r5     s   z ModernBertPredictionHead.forward)	r<   r=   r>   r   rM   r@   rA   r5   r^   r3   r3   rP   r4   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}   )rL   rM   r`   r^  r  r  headr   r~   rg   rf   decoder_biasr   sparse_predictionsparse_pred_ignore_indexrh  rq   rP   r3   r4   rM     s   



zModernBertForMaskedLM.__init__c                 C   s   | j S rY   r   rW   r3   r3   r4   get_output_embeddings  s   z+ModernBertForMaskedLM.get_output_embeddingsnew_embeddingsc                 C   s
   || _ d S rY   r  )rO   r  r3   r3   r4   set_output_embeddings  s   
z+ModernBertForMaskedLM.set_output_embeddingsTrr   rZ  rR   c                 C   r   rY   )r   r  )rO   rZ  r3   r3   r4   compiled_head  r  z#ModernBertForMaskedLM.compiled_headNrt   r   r   r   rw   rE  rP  r   r    rl  rm  r   rn  ro  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 )rp  Nr   r!   rK   )rD  r   r   rE  rt   r   r   r   rw   rP  r   r    rl  rm  r   rn  ro  r   r"   rf   rq  losslogitsry   rw  )r`   rx  r7  r   r'   rI   r@   rz  r   r   rX  r  r  r(   r  rx   r  r   r  loss_functionrf   repad_logits_with_gradr   r]  r   ry   rw  )rO   rt   r   r   r   rw   rE  rP  r   r    rl  rm  r   rn  ro  r   rI   outputsrv  mask_tokensr  r  rZ  r3   r3   r4   r5     s~   #


 zModernBertForMaskedLM.forwardNNNNNNNNNNNNNN)r<   r=   r>   _tied_weights_keysr   rM   r  r   r~   r  r@   rz   rA   r  r   r   r{   rB   r   r   r\   r   r5   r^   r3   r3   rP   r4   r    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 rY   )rL   rM   
num_labelsr`   r^  r  r  r  r@   r   rn   classifier_dropoutrp   r~   rg   r$  rh  rq   rP   r3   r4   rM   J  s   

z,ModernBertForSequenceClassification.__init__Nrt   r   r   r   rw   rE  rP  r   r    rl  rm  r   rn  ro  rR   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   r2  r	  r"   r   r   T)rG   keepdim
regressionsingle_label_classificationmulti_label_classificationr  )r`   rx  r7  r  classifier_poolingr   rG  r  rp   r$  problem_typer  rJ   r@   longrB   r   squeezer   r(   r   r   ry   rw  )rO   rt   r   r   r   rw   rE  rP  r   r    rl  rm  r   rn  ro  r   r  rv  pooled_outputr  r  loss_fctrZ  r3   r3   r4   r5   W  sn   '




"


z+ModernBertForSequenceClassification.forwardr  )r<   r=   r>   r   rM   r   r   r@   r{   rA   rB   r   r   r\   r   r5   r^   r3   r3   rP   r4   r!  D  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 rY   rL   rM   r  r^  r  r  r  r@   r   rn   r  rp   r~   rg   r$  rh  rq   rP   r3   r4   rM     s   

z)ModernBertForTokenClassification.__init__Nrt   r   r   r   rw   rE  rP  r   r    rl  rm  r   rn  ro  rR   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   r"   r   r  )r`   rx  r7  r  r  rp   r$  r   r(   r  r   ry   rw  )rO   rt   r   r   r   rw   rE  rP  r   r    rl  rm  r   rn  ro  r  rv  r  r  r  rZ  r3   r3   r4   r5     sD   $


z(ModernBertForTokenClassification.forwardr  )r<   r=   r>   r   rM   r   r   r@   r{   rA   rB   r   r   r\   r   r5   r^   r3   r3   rP   r4   r"    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                    r  rY   r  rq   rP   r3   r4   rM   !  s   

z'ModernBertForQuestionAnswering.__init__Nrt   r   r   r   start_positionsend_positionsrP  r   r    rl  rm  r   rn  ro  rR   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 )rp  N)r   r   r   rP  r   r    rl  rm  r   rn  ro  r   r   r"   r   )r  start_logits
end_logitsry   rw  )r`   rx  r7  r  r  rp   r$  splitr  r&   r  r   ry   rw  )rO   rt   r   r   r   r  r  rP  r   r    rl  rm  r   rn  ro  r   r  rv  r  r  r  r  rZ  r3   r3   r4   r5   ,  sH   #


z&ModernBertForQuestionAnswering.forwardr  )r<   r=   r>   r   rM   r   r   r@   rA   rB   r   r   r\   r   r5   r^   r3   r3   rP   r4   r#    s^    	
r#  )r^  r  r  r!  r"  r#  r;   )Nr   r   )Tr  
contextlibr   typingr   r   r@   torch.nn.functionalr   r   r   torch.nnr   r   r   activationsr
   modeling_attn_mask_utilsr   modeling_layersr   modeling_outputsr   r   r   r   r   modeling_rope_utilsr   r   modeling_utilsr   utilsr   r   r   utils.import_utilsr   configuration_modernbertr   flash_attn.flash_attn_interfacer   flash_attn.layers.rotaryr   flash_attn.ops.triton.rotaryr   object
get_loggerr<   r5  autogradFunctionr   rA   rB   rD   rE   r  r_   r|   r   r   r   r{   r\   r   r   r   rJ   r   r   r   r   r   r  rX  r]  r^  r  r  r!  r"  r#  __all__r3   r3   r3   r4   <module>   s0  
;
5!
$
	
.
	
+


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