o
    Zh                     @   sf  d Z ddlZddl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 ddlmZmZmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZmZ ddlmZmZ ddl m!Z! ddl"m#Z# ddl$m%Z%m&Z& ddl'm(Z( e rddlm)Z) e&*e+Z,			d:deej-eej- df dee. deej- deej-e.f fddZ/G dd de	j0Z1e#2e1 G dd de	j0Z3dd Z4d;d d!Z5G d"d# d#e	j0Z6d$ej-d%e.dej-fd&d'Z7G d(d) d)e	j0Z8G d*d+ d+e8Z9G d,d- d-e8Z:e8e9e:d.Z;G d/d0 d0e	j0Z<G d1d2 d2e	j0Z=e%G d3d4 d4e!Z>e%G d5d6 d6e>Z?G d7d8 d8e>eZ@g d9ZAdS )<zPyTorch OLMoE model.    N)ListOptionalTupleUnion)nn   )ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter)!flash_attn_supports_top_left_maskis_flash_attn_available)MoeCausalLMOutputWithPastMoeModelOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)PreTrainedModel)ALL_LAYERNORM_LAYERS)auto_docstringlogging   )OlmoeConfig)_flash_attention_forward   gate_logitsnum_expertsattention_maskreturnc                    s  | du s	t | tsdS t | tr#| d j tj fdd| D dd}tjjj|dd}tj||dd\}}tjj	||}|du rStj
| dd}	tj
|dd}
ng|j\}}|jd ||  }|dddddddf |||||fd|| }tj| | ddtj|dd }	|ddddddf ||||fd| }tj|| ddtj|dd }
t|	|
d }|| S )a  
    Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.

    See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
    function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
    experts is too unbalanced.

    Args:
        gate_logits:
            Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
            shape [batch_size X sequence_length, num_experts].
        num_experts:
            Number of experts
        top_k:
            The number of experts to route per-token, can be also interpreted as the `top-k` routing
            parameter.
        attention_mask (`torch.Tensor`, *optional*):
            The attention_mask used in forward function
            shape [batch_size X sequence_length] if not None.

    Returns:
        The auxiliary loss.
    Nr   c                    s   g | ]}|  qS  )to).0Z
layer_gateZcompute_devicer    W/var/www/auris/lib/python3.10/site-packages/transformers/models/olmoe/modeling_olmoe.py
<listcomp>M       z,load_balancing_loss_func.<locals>.<listcomp>dim)
isinstancetupledevicetorchcatr   
functionalsoftmaxtopkone_hotmeanfloatshapeexpandreshaper!   sum	unsqueeze)r   r   top_kr   Zconcatenated_gate_logitsrouting_weights_selected_expertsexpert_maskZtokens_per_expertZrouter_prob_per_expert
batch_sizesequence_lengthnum_hidden_layersZexpert_attention_maskZ router_per_expert_attention_maskZoverall_lossr    r#   r$   load_balancing_loss_func+   s>   



rB   c                       s.   e Zd Zd fdd	Zdd Zdd Z  ZS )	OlmoeRMSNormh㈵>c                    s&   t    tt|| _|| _dS )z;
        OlmoeRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parameterr-   Zonesweightvariance_epsilon)selfhidden_sizeeps	__class__r    r$   rF   ~   s   

zOlmoeRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )Nr   r)   T)keepdim)	dtyper!   r-   float32powr3   ZrsqrtrI   rH   )rJ   hidden_statesinput_dtypeZvariancer    r    r$   forward   s
   zOlmoeRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)r+   rH   r5   rI   rJ   r    r    r$   
extra_repr   s   zOlmoeRMSNorm.extra_repr)rD   )__name__
__module____qualname__rF   rU   rW   __classcell__r    r    rM   r$   rC   }   s    rC   c                       s8   e Zd Zddef fddZe edd Z  Z	S )OlmoeRotaryEmbeddingNconfigc                    s   t    t|dr|jd ur|jd|jd| _nd| _|j| _|j| _|| _	t
| j | _| | j	|\}| _| jd|dd | j| _d S )Nrope_scaling	rope_typetypedefaultinv_freqF)
persistent)rE   rF   hasattrr^   getr_   max_position_embeddingsZmax_seq_len_cachedZoriginal_max_seq_lenr]   r   Zrope_init_fnattention_scalingZregister_bufferrb   Zoriginal_inv_freq)rJ   r]   r,   rb   rM   r    r$   rF      s   
zOlmoeRotaryEmbedding.__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   ZmpscpuF)device_typeenabledr   r'   )rP   )rb   r4   r6   r5   r!   r,   r*   r`   strr-   Zautocast	transposer.   cosrg   sinrP   )
rJ   xposition_idsZinv_freq_expandedZposition_ids_expandedri   ZfreqsZembrm   rn   r    r    r$   rU      s   0&zOlmoeRotaryEmbedding.forwardN)
rX   rY   rZ   r   rF   r-   Zno_gradr   rU   r[   r    r    rM   r$   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'   )r5   r-   r.   )ro   x1Zx2r    r    r$   rotate_half   s   rs   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.
    )r9   rs   )qkrm   rn   rp   Zunsqueeze_dimZq_embedZk_embedr    r    r$   apply_rotary_pos_emb   s
   

rv   c                       s$   e Zd Z fddZdd Z  ZS )OlmoeMLPc                    sr   t    || _|j| _|j| _tj| j| jdd| _tj| j| jdd| _tj| j| jdd| _	t
|j | _d S NFbias)rE   rF   r]   rK   Zintermediate_sizer   Linear	gate_projup_proj	down_projr   Z
hidden_actact_fnrJ   r]   rM   r    r$   rF      s   
zOlmoeMLP.__init__c                 C   s$   |  | | || | }|S rq   )r~   r   r|   r}   )rJ   ro   r~   r    r    r$   rU      s    zOlmoeMLP.forward)rX   rY   rZ   rF   rU   r[   r    r    rM   r$   rw      s    
rw   rS   n_repc                 C   s^   | j \}}}}|dkr| S | dddddddddf |||||} | ||| ||S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)r5   r6   r7   )rS   r   batchnum_key_value_headsslenhead_dimr    r    r$   	repeat_kv   s
   0r   c                       s   e Zd ZdZddedee f fddZ							ddej	d	eej	 d
eej
 dee dededeej
 deeej	ej	f  deej	eej	 eeej	  f fddZ  ZS )OlmoeAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNr]   	layer_idxc                    sX  t    || _|| _|d u rtd| jj d |j| _|j	| _	|j
| _| j	| j | _|j| _| j| j | _|j| _|j| _d| _| j| j | j	krYtd| j	 d| j dtj| j	| j| j |jd| _tj| j	| j| j |jd| _tj| j	| j| j |jd| _tj| j	| j	|jd| _t| j	|jd| _t| j	| j | j |jd| _d S )	NzInstantiating z without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.Tz?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).ry   rL   )rE   rF   r]   r   loggerwarning_oncerN   rX   attention_dropoutrK   Znum_attention_heads	num_headsr   r   num_key_value_groupsrf   Z
rope_theta	is_causal
ValueErrorr   r{   Zattention_biasq_projk_projv_projo_projrC   rms_norm_epsq_normk_normrJ   r]   r   rM   r    r$   rF      s<   

zOlmoeAttention.__init__FrS   r   rp   past_key_valueoutput_attentions	use_cachecache_positionposition_embeddingsr   c	                 K   sL  |  \}
}}| | |}| | |}| |}| jjd urF|j| jj | jjd |j| jj | jjd |j| jj | jjd |	|
|| j
| jdd}|	|
|| j| jdd}|	|
|| j| jdd}|\}}t||||\}}|d ur|||d}|||| j|\}}t|| j}t|| j}t||ddt| j }|d ur|d d d d d d d |jd f }|| }tjj|dtjd|j}tjj|| j| j d	}t||}|  |
| j
|| jfkrt!d
|
| j
|| jf d|   |dd" }|#|
|| j$}| %|}|s!d }|||fS )Nminmaxr   r   rn   rm   r   r   r)   r(   rP   )ptrainingz `attn_output` should be of size z	, but is )&sizer   r   r   r   r   r]   clip_qkvclamp_viewr   r   rl   r   rv   updater   r   r   r-   matmulmathsqrtr5   r   r/   r0   rQ   r!   rP   dropoutr   r   r   
contiguousr7   rK   r   )rJ   rS   r   rp   r   r   r   r   r   kwargsbszq_lenr<   query_states
key_statesvalue_statesrm   rn   cache_kwargsattn_weightscausal_maskattn_outputr    r    r$   rU      sJ   
 &

zOlmoeAttention.forwardrq   NNNFFNN)rX   rY   rZ   __doc__r   r   intrF   r-   Tensor
LongTensorr	   boolr   rU   r[   r    r    rM   r$   r      s:    '	r   c                       s   e Zd ZdZ fddZ							ddejdeej deej d	ee	 d
e
de
deej deeejejf  deejeej eeej  f fddZ  ZS )OlmoeFlashAttention2aF  
    OLMoE flash attention module. This module inherits from `OlmoeAttention` as the weights of the module stays
    untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
    flash attention and deal with padding tokens in case the input contains any of them.
    c                    s   t  j|i | t | _d S rq   )rE   rF   r   _flash_attn_uses_top_left_mask)rJ   argsr   rM   r    r$   rF   j  s   zOlmoeFlashAttention2.__init__NFrS   r   rp   r   r   r   r   r   r   c	              
   K   s  d}|  \}
}}| | |}| | |}| |}| jjd urH|j| jj | jjd |j| jj | jjd |j| jj | jjd |	|
|| j
| jdd}|	|
|| j| jdd}|	|
|| j| jdd}|\}}t||||\}}|d ur|||d}|||| j|\}}|dd}|dd}|dd}| jr| jnd}|j}|tjkrt rt }nt| jdr| jj}n| jjj}td| d	 ||}||}||}t||||||| j| j d
}|!|
|| j"# }| $|}|s	d }|||fS )NFr   r   r   r           _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .)r   Zuse_top_left_maskr   )%r   r   r   r   r   r   r]   r   r   r   r   r   rl   r   rv   r   r   r   r   rP   r-   rQ   Zis_autocast_enabledZget_autocast_gpu_dtyperd   r   rH   r   r   r!   r   r   r   r7   rK   r   r   )rJ   rS   r   rp   r   r   r   r   r   r   r   r   r<   r   r   r   rm   rn   r   Zdropout_raterT   Ztarget_dtyper   r   r    r    r$   rU   r  sf   









zOlmoeFlashAttention2.forwardr   )rX   rY   rZ   r   rF   r-   r   r   r   r	   r   r   rU   r[   r    r    rM   r$   r   c  s:    	r   c                       s   e Zd ZdZ							ddejdeej deej dee de	d	e	d
eej dee
ejejf  de
ejeej ee
ej  f f fddZ  ZS )OlmoeSdpaAttentionz
    OLMoE attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `OlmoeAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    NFrS   r   rp   r   r   r   r   r   r   c	              
      s6  |rt d t j||||||||dS | \}	}
}| | |}| | |}| 	|}| j
jd ur[|j| j
j | j
jd |j| j
j | j
jd |j| j
j | j
jd ||	|
| j| jdd}||	|
| j| jdd}||	|
| j| jdd}|\}}t||||\}}|d ur|||d}|||| j|\}}t|| j}t|| j}|}|d ur|d d d d d d d |jd f }|jjdkr|d ur| }| }| }|d u r|
dkrd	nd
}tjjj||||| jr| j nd|d}|dd }||	|
| j!}| "|}|d |fS )Na  OlmoeModel is using OlmoeSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.rS   r   rp   r   r   r   r   r   r   r   r   r   r   cudaTFr   )Z	attn_maskZ	dropout_pr   )#r   r   rE   rU   r   r   r   r   r   r   r]   r   r   r   r   r   rl   r   rv   r   r   r   r   r5   r,   r`   r   r-   r   r/   Zscaled_dot_product_attentionr   r   rK   r   )rJ   rS   r   rp   r   r   r   r   r   r   r   r<   r   r   r   rm   rn   r   r   r   r   rM   r    r$   rU     sh   
&	

zOlmoeSdpaAttention.forwardr   )rX   rY   rZ   r   r-   r   r   r   r	   r   r   rU   r[   r    r    rM   r$   r     s8    
	
r   )eagerflash_attention_2sdpac                       s2   e Zd Z fddZdejdejfddZ  ZS )OlmoeSparseMoeBlockc                    s\   t     j| _ j| _ j| _tj j| jdd| _	t
 fddt| jD | _d S )NFry   c                    s   g | ]}t  qS r    )rw   )r"   r<   r]   r    r$   r%   <  s    z0OlmoeSparseMoeBlock.__init__.<locals>.<listcomp>)rE   rF   r   num_experts_per_tokr:   norm_topk_probr   r{   rK   gate
ModuleListrangeexpertsr   rM   r   r$   rF   6  s   
$zOlmoeSparseMoeBlock.__init__rS   r   c                 C   s*  |j \}}}|d|}| |}tj|dtjd}tj|| jdd\}}| j	r1||j
ddd }||j}tj|| |f|j|jd}tjjj|| jdd	dd
}	t| jD ]0}
| j|
 }t|	|
 \}}|d |f d|}|||||d f  }|d
|||j qY||||}||fS )Nr)   r   r   r'   T)r(   rO   )rP   r,   )Znum_classesr   r   )r5   r   r   Fr0   r-   r4   r1   r:   r   r8   r!   rP   Zzerosr,   r   r/   r2   r   Zpermuter   r   wherer7   Z
index_add_)rJ   rS   r?   r@   Z
hidden_dimrouter_logitsr;   r=   Zfinal_hidden_statesr>   Z
expert_idxZexpert_layeridxZtop_xZcurrent_stateZcurrent_hidden_statesr    r    r$   rU   >  s(   

zOlmoeSparseMoeBlock.forward)rX   rY   rZ   rF   r-   r   rU   r[   r    r    rM   r$   r   5  s    r   c                       s   e Zd Zdedef fddZ								dd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j	 deeejejf  deejeeejejf  f fddZ  ZS )OlmoeDecoderLayerr]   r   c                    sX   t    |j| _t|j ||d| _t|| _t|j|j	d| _
t|j|j	d| _d S )N)r]   r   r   )rE   rF   rK   OLMOE_ATTENTION_CLASSES_attn_implementation	self_attnr   mlprC   r   input_layernormpost_attention_layernormr   rM   r    r$   rF   f  s   

zOlmoeDecoderLayer.__init__NFrS   r   rp   r   r   output_router_logitsr   r   r   r   c
                 K   s   |}|  |}| jd||||||||	d|
\}}}|| }|}| |}| |\}}|| }|f}|r;||f7 }|rB||f7 }|rI||f7 }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *optional*):
                attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
                query_sequence_length, key_sequence_length)` if default attention is used.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_router_logits (`bool`, *optional*):
                Whether or not to return the logits of all the routers. They are useful for computing the router loss,
                and should not be returned during inference.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
            past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence
            position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
                Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
                with `head_dim` being the embedding dimension of each attention head.
            kwargs (`dict`, *optional*):
                Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
                into the model
        r   Nr    )r   r   r   r   )rJ   rS   r   rp   r   r   r   r   r   r   r   ZresidualZself_attn_weightsZpresent_key_valuer   outputsr    r    r$   rU   p  s6   &
	



zOlmoeDecoderLayer.forward)NNNFFFNN)rX   rY   rZ   r   r   rF   r-   r   r   r   r	   r   r   FloatTensorrU   r[   r    r    rM   r$   r   e  s>    	
r   c                   @   s@   e Zd ZeZdZdZdgZdgZdZ	dZ
dZdZdZdd ZdS )	OlmoePreTrainedModelmodelTr   past_key_valuesFc                 C   s   | j j}t|tjr"|jjjd|d |jd ur |jj	  d S d S t|t
r0|jjd d S t|tjrO|jjjd|d |jd urQ|jj|j 	  d S d S d S )Nr   )r3   stdg      ?)r]   Zinitializer_ranger*   r   r{   rH   dataZnormal_rz   Zzero_rC   Zfill_	Embeddingpadding_idx)rJ   moduler   r    r    r$   _init_weights  s   


z"OlmoePreTrainedModel._init_weightsN)rX   rY   rZ   r   Zconfig_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_skip_keys_device_placementZ_supports_flash_attn_2Z_supports_sdpaZ_supports_cache_classZ_supports_quantized_cacheZ_supports_static_cacher   r    r    r    r$   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eee	j f  dee	j dee dee dee dee dee dee	j
 deeef fddZd
e	jde	jde	jdedef
ddZed
e	jdedede	jde	jde	jdefdd Z  ZS )"
OlmoeModelr]   c                    s   t     j| _ j| _t j j| j| _t	 fddt
 jD | _t j jd| _t d| _d| _|   d S )Nc                    s   g | ]}t  |qS r    )r   )r"   r   r   r    r$   r%     r&   z'OlmoeModel.__init__.<locals>.<listcomp>r   r   F)rE   rF   Zpad_token_idr   
vocab_sizer   r   rK   embed_tokensr   r   rA   layersrC   r   normr\   
rotary_embgradient_checkpointing	post_initr   rM   r   r$   rF     s   zOlmoeModel.__init__c                 C      | j S rq   r   rV   r    r    r$   get_input_embeddings     zOlmoeModel.get_input_embeddingsc                 C   
   || _ d S rq   r   rJ   valuer    r    r$   set_input_embeddings     
zOlmoeModel.set_input_embeddingsN	input_idsr   rp   r   inputs_embedsr   r   output_hidden_statesr   return_dictr   r   c                 C   s  |d ur|n| j j}|	d ur|	n| j j}	|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| jrM| jrM|rMt	
d d}|d u rV| |}d}|rst|tssd}|d u rit }n
t|}t	
d |d u r|d ur| nd}tj|||jd  |jd}|d u r|d}| |||||}|}| ||}|rd	nd }|rd	nd }|	rd	nd }d }| jd | j j D ]V}|r||f7 }| jr| jr| |j||||||	|||
}n|||||||	|||d
	}|d }|r||rdnd }|r||d f7 }|	r|d d ur||d f7 }q| |}|r*||f7 }|r/|nd }|r8| }|
sHtdd ||||fD S t|||||dS )Nz:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.FTzWe detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class (https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)r   r   r,   r    )r   rp   r   r   r   r   r   r   r   r)   c                 s   s    | ]	}|d ur|V  qd S rq   r    )r"   vr    r    r$   	<genexpr>n  s    z%OlmoeModel.forward.<locals>.<genexpr>)Zlast_hidden_stater   rS   
attentionsr   ) r]   r   r   r   r   use_return_dictr   r   r   r   r   r   r*   r	   r
   Zfrom_legacy_cacheget_seq_lengthr-   aranger5   r,   r9   _update_causal_maskr   r   rA   Z_gradient_checkpointing_func__call__r   Zto_legacy_cacher+   r   )rJ   r   r   rp   r   r   r   r   r   r   r   r   Zreturn_legacy_cachepast_seen_tokensr   rS   r   Zall_hidden_statesZall_self_attnsZall_router_logitsZnext_decoder_cacheZdecoder_layerZlayer_outputsZ
next_cacher    r    r$   rU     s   






zOlmoeModel.forwardinput_tensorc              	   C   s  | j jdkr|d urd|v r|S d S |d ur| nd}t|t}| j jdkr7|s7|s7tj|||| jdr7d S |j|j	}}	|j
d }
|rJ| }nt|tjrU|j
d n||
 d }| j||
|||	||j
d d}| j jdkr|d ur|j	jd	v r|st|j}t||}|S )
Nr   r   r   r   )r   Zpast_key_values_lengthZis_trainingr   r)   )r@   target_lengthrP   r,   r   r?   )r   ZxpuZnpu)r]   r   r  r*   r   r   Z_ignore_causal_mask_sdpar   rP   r,   r5   Zget_max_cache_shaper-   r   5_prepare_4d_causal_attention_mask_with_cache_positionr`   finfor   Z_unmask_unattended)rJ   r   r
  r   r   r   r	  Zusing_static_cacherP   r,   r@   r  r   	min_dtyper    r    r$   r  w  sN   




zOlmoeModel._update_causal_maskr@   r  rP   r,   r?   c                 K   s8  | dur|   dkr| }|S t|j}	tj||f|	||d}|dkr*tj|dd}|tj||d|ddk9 }|ddddddf |ddd}| dur|	 }| j
d }
|ddddddd|
f | ddddddf  }|dk}|ddddddd|
f ||	|ddddddd|
f< |S )	a  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            device (`torch.device`):
                The device to place the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )Z
fill_valuerP   r,   r   )Zdiagonalr   r)   r   )r(   r-   r  r   fullZtriur  r7   r6   cloner5   Zmasked_fill)r   r@   r  rP   r,   r   r?   r   r   r  Zmask_lengthZpadding_maskr    r    r$   r    s(   !$
8  z@OlmoeModel._prepare_4d_causal_attention_mask_with_cache_position)NNNNNNNNNNN)rX   rY   rZ   r   rF   r   r   r   r   r-   r   r   r   r	   r   r   r   r   r   rU   r  staticmethodr   rP   r,   r  r[   r    r    rM   r$   r     s    	

 
Ar   c                        s  e Zd ZdgZ fddZdd Zdd Zdd	 Z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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j deeejf deeef fd d!Z  ZS )#OlmoeForCausalLMzlm_head.weightc                    sX   t  | t|| _|j| _tj|j|jdd| _|j	| _	|j
| _
|j| _|   d S rx   )rE   rF   r   r   r   r   r{   rK   lm_headrouter_aux_loss_coefr   r   r   r   rM   r    r$   rF     s   
zOlmoeForCausalLM.__init__c                 C   s   | j jS rq   r   r   rV   r    r    r$   r      s   z%OlmoeForCausalLM.get_input_embeddingsc                 C   s   || j _d S rq   r  r   r    r    r$   r     s   z%OlmoeForCausalLM.set_input_embeddingsc                 C   r   rq   r  rV   r    r    r$   get_output_embeddings  r   z&OlmoeForCausalLM.get_output_embeddingsc                 C   r   rq   r  )rJ   Znew_embeddingsr    r    r$   set_output_embeddings	  r   z&OlmoeForCausalLM.set_output_embeddingsc                 C   r   rq   r   )rJ   decoderr    r    r$   set_decoder  r   zOlmoeForCausalLM.set_decoderc                 C   r   rq   r  rV   r    r    r$   get_decoder  r   zOlmoeForCausalLM.get_decoderNr   r   r   rp   r   r   labelsr   r   r   r   r   r   logits_to_keepr   c                 K   sp  |dur|n| j j}|
dur|
n| j j}
|	dur|	n| j j}	|dur$|n| j j}| j||||||||	|
||d}|d }t|trGt| dn|}| 	|dd|ddf }d}|duri| j
||| jfi |}d}|
rt|rs|jn|d | j| j|}|dur|| j||j 7 }|s|f|dd  }|
r|f| }|dur|f| S |S t||||j|j|j|jdS )u  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Example:

        ```python
        >>> from transformers import AutoTokenizer, OlmoeForCausalLM

        >>> model = OlmoeForCausalLM.from_pretrained("allenai/OLMoE-1B-7B-0924")
        >>> tokenizer = AutoTokenizer.from_pretrained("allenai/OLMoE-1B-7B-0924")

        >>> prompt = "Hey, are you conscious? Can you talk to me?"
        >>> inputs = tokenizer(prompt, return_tensors="pt")

        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        'Hey, are you conscious? Can you talk to me?\nI’m not sure if you’re conscious of this, but I’m'
        ```
        N)r   r   rp   r   r   r   r   r   r   r   r   r   r)   r   )lossaux_losslogitsr   rS   r  r   )r]   r   r   r   r  r   r*   r   slicer  Zloss_functionr   rB   r   r   r   r  r!   r,   r   r   rS   r  )rJ   r   r   rp   r   r   r  r   r   r   r   r   r   r  Zloss_kwargsr   rS   Zslice_indicesr"  r   r!  outputr    r    r$   rU     sb   )
zOlmoeForCausalLM.forward)NNNNNNNNNNNNr   )rX   rY   rZ   Z_tied_weights_keysrF   r   r   r  r  r  r  r   r   r-   r   r   r   r   r   r   r   r   r   rU   r[   r    r    rM   r$   r    sh    	

r  )r  r   r   )Nr   N)Nr   )Br   r   typingr   r   r   r   r-   Ztorch.nn.functionalr   r/   r   Ztorch.utils.checkpointZactivationsr   Zcache_utilsr	   r
   r   Z
generationr   Zmodeling_attn_mask_utilsr   Zmodeling_flash_attention_utilsr   r   Zmodeling_outputsr   r   Zmodeling_rope_utilsr   r   Zmodeling_utilsr   Zpytorch_utilsr   utilsr   r   Zconfiguration_olmoer   r   Z
get_loggerrX   r   r   r   rB   ModulerC   appendr\   rs   rv   rw   r   r   r   r   r   r   r   r   r   r  __all__r    r    r    r$   <module>   st   

R
#
jl`0W   