o
    eiv                     @   sd  d dl mZ d dlmZ d dlZd dlmZ ddlmZ ddl	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mZ ddlmZ ddlmZ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&m'Z'm(Z( ddl)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/ G dd dej0Z1edG dd dej0Z2G dd dej0Z3G dd dej0Z4G dd  d ej5Z6G d!d" d"ej0Z7d#d$ Z8ed%dCd&d'Z9d(ej:d)e;d*ej:fd+d,Z<	-dDd.ej0d/ej:d0ej:d1ej:d2ej:dB d3e=d4e=d5e$e& fd6d7Z>ee9G d8d9 d9ej0Z?G d:d; d;eZ@G d<d= d=e"ZAe'G d>d? d?eAZBe'G d@dA dAeAeZCg dBZDdS )E    )Callable)OptionalN)nn   )initialization)ACT2FN)CacheDynamicCache)GenerationMixin)use_kernel_forward_from_hubuse_kernel_func_from_hubuse_kernelized_func)create_causal_mask!create_sliding_window_causal_mask)GradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPastMoeModelOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuple)maybe_autocastmerge_with_config_defaults)capture_outputs   )AfmoeConfigc                       s~   e Zd ZU ejed< ddef fddZe			ddedB de	d de
dB d	ed
ef fddZe edd Z  ZS )AfmoeRotaryEmbeddinginv_freqNconfigc                    s   t    |j| _|j| _|| _| jjd | _| j}| jdkr$t	| j }|| j|\}| _
| jd|dd | jd| dd d S )N	rope_typedefaultr"   F)
persistentoriginal_inv_freq)super__init__max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr#   rope_parametersr$   compute_default_rope_parametersr   attention_scalingregister_bufferclone)selfr#   devicerope_init_fnr"   	__class__ f/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/transformers/models/afmoe/modeling_afmoe.pyr)   /   s   


zAfmoeRotaryEmbedding.__init__r3   ztorch.deviceseq_lenreturnztorch.Tensorc                 C   sZ   | j d }t| ddp| j| j }d}d|tjd|dtjdj|tjd|   }||fS )	a  
        Computes the inverse frequencies according to the original RoPE implementation
        Args:
            config ([`~transformers.PreTrainedConfig`]):
                The model configuration.
            device (`torch.device`):
                The device to use for initialization of the inverse frequencies.
            seq_len (`int`, *optional*):
                The current sequence length. Unused for this type of RoPE.
        Returns:
            Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
            post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
        
rope_thetahead_dimNg      ?r      dtyper3   r?   )	r-   getattrhidden_sizenum_attention_headstorcharangeint64tofloat)r#   r3   r9   basedimattention_factorr"   r7   r7   r8   r.   ?   s   
&z4AfmoeRotaryEmbedding.compute_default_rope_parametersc           
      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	|dd+ | |  
dd}tj||fdd	}| | j }| | j }	W d    n1 slw   Y  |j|jd
|	j|jd
fS )Nr   r   mpscpuF)device_typeenabledr=   rJ   r>   )r"   rH   expandshaperG   r3   
isinstancetypestrr   	transposerD   catcosr/   sinr?   )
r2   xposition_idsinv_freq_expandedposition_ids_expandedrO   freqsembrY   rZ   r7   r7   r8   forward]   s   0&zAfmoeRotaryEmbedding.forwardN)NNN)__name__
__module____qualname__rD   Tensor__annotations__r    r)   staticmethodr   inttuplerH   r.   no_gradr   ra   __classcell__r7   r7   r5   r8   r!   ,   s&   
 

r!   RMSNormc                       s@   e Zd Zddeddf fddZdejfddZd	d
 Z  Z	S )AfmoeRMSNormư>epsr:   Nc                    s&   t    tt|| _|| _dS )z;
        AfmoeRMSNorm is equivalent to T5LayerNorm
        N)r(   r)   r   	ParameterrD   onesweightvariance_epsilon)r2   rB   rp   r5   r7   r8   r)   o   s   

zAfmoeRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j| |S )Nr=   rL   T)keepdim)	r?   rG   rD   float32powmeanrsqrtrt   rs   )r2   hidden_statesinput_dtypevariancer7   r7   r8   ra   w   s
   zAfmoeRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)rj   rs   rS   rt   )r2   r7   r7   r8   
extra_repr~   s   zAfmoeRMSNorm.extra_repr)ro   )
rc   rd   re   rH   r)   rD   rf   ra   r}   rl   r7   r7   r5   r8   rn   m   s    rn   c                       s&   e Zd Zd fdd	Zdd Z  ZS )AfmoeMLPNc                    s~   t    || _|j| _|d u r|jn|| _tj| j| jdd| _tj| j| jdd| _tj| j| jdd| _	t
|j | _d S NFbias)r(   r)   r#   rB   intermediate_sizer   Linear	gate_projup_proj	down_projr   
hidden_actact_fn)r2   r#   r   r5   r7   r8   r)      s   
zAfmoeMLP.__init__c                 C   s$   |  | | || | }|S rb   )r   r   r   r   )r2   r[   r   r7   r7   r8   ra      s    zAfmoeMLP.forwardrb   )rc   rd   re   r)   ra   rl   r7   r7   r5   r8   r~      s    
r~   c                       s6   e Zd ZdZ fddZdejdejfddZ  ZS )AfmoeTokenChoiceRouterz
    Token-choice top-K router for MoE routing.

    This router assigns each token to the top-K experts based on sigmoid scores, matching the released checkpoints.
    c                    sB   t    || _|j| _|j| _|j| _tj|j	|jdd| _
d S r   )r(   r)   r#   num_experts_per_toktop_knum_expertsroute_scaler   r   rB   gater2   r#   r5   r7   r8   r)      s   
zAfmoeTokenChoiceRouter.__init__rz   expert_biasc           	      C   s   |j \}}}|d|}t| |tj}tj|| | jdd\}}|j	d|d}|j
dddd }|| }|| j }||fS )NrL   r   )krJ   )rJ   indexT)rJ   ru   g#B;)rS   viewrD   sigmoidr   rG   rv   topkr   gathersumr   )	r2   rz   r   _
hidden_dimscoresselected_experts
top_scoresdenominatorr7   r7   r8   ra      s   
zAfmoeTokenChoiceRouter.forward)	rc   rd   re   __doc__r)   rD   rf   ra   rl   r7   r7   r5   r8   r      s    r   c                       sH   e Zd ZdZdef fddZdejdejdejdejfd	d
Z  Z	S )AfmoeExpertsz
    Container holding the routed experts.

    This mirrors the Experts pattern used across other MoE models to ease checkpoint conversion.
    r#   c                    sB   t    |j| _|j| _t| jD ]}| t||jd qd S )N)r   )	r(   r)   r   r   r   rangeappendr~   moe_intermediate_size)r2   r#   r   r5   r7   r8   r)      s   
zAfmoeExperts.__init__rz   r   routing_weightsr:   c                 C   sh  |j \}}}|dkr||d|S |d|}|j d }tj|j d |jtjd|}	|d}
|d}tj	|
dd}|	| }	|
| }
|| }|
d|	}t|}tj|
dd\}}d}t| | D ]!\}}|dkrqqh|| }||| }| | |}||||< |}qh|tj|d |j}t|}|	d|}|d|| ||||S )z
        Args:
            hidden_states: (batch, seq, hidden)
            selected_experts: (batch, seq, top_k)
            routing_weights: (batch, seq, top_k)
        r   rL   r@   T)stable)return_counts)rS   	new_zerosr   rD   rE   r3   longrepeat_interleavereshapeargsortindex_select
zeros_likeunique_consecutiveziptolistrG   rv   	unsqueezer?   	expand_asscatter_add_)r2   rz   r   r   
batch_sizer9   r   hidden_states_flatr   token_indicesexpert_indicessortingdispatched_tokensexpert_outputsunique_expertscountsstart	expert_idcountendexpert_inputexpert_outputweighted_outputs
aggregatedscatter_indicesr7   r7   r8   ra      sB   	




zAfmoeExperts.forward)
rc   rd   re   r   r    r)   rD   rf   ra   rl   r7   r7   r5   r8   r      s    r   c                       s(   e Zd ZdZ fddZdd Z  ZS )AfmoeMoEz
    Mixture of Experts (MoE) module for AFMoE.

    This module implements a sparse MoE layer with both shared experts (always active) and
    routed experts (activated based on token-choice routing).
    c                    sT   t    || _t|| _t||j|j | _t	|| _
tjt|jdd| _d S )NF)requires_grad)r(   r)   r#   r   routerr~   r   num_shared_expertsshared_expertsr   expertsr   rq   rD   zerosr   r   r   r5   r7   r8   r)      s   


zAfmoeMoE.__init__c           
      C   sx   |j \}}}|d|}| || j\}}|||| jj}|||| jj}| ||||}| |||}	||	 S )NrL   )rS   r   r   r   r#   r   r   r   )
r2   rz   r   r9   r   r   r   r   shared_outputrouted_outputr7   r7   r8   ra      s   zAfmoeMoE.forward)rc   rd   re   r   r)   ra   rl   r7   r7   r5   r8   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..NrL   r=   rQ   )rS   rD   rX   )r[   x1x2r7   r7   r8   rotate_half  s   r   rotary_pos_embc                 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.
        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.
    )r   r   )qr   rY   rZ   unsqueeze_dimq_embedk_embedr7   r7   r8   apply_rotary_pos_emb  s
   

r   rz   n_repr:   c                 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)rS   rR   r   )rz   r   batchnum_key_value_headsslenr<   r7   r7   r8   	repeat_kv-  s
   0r           modulequerykeyvalueattention_maskscalingdropoutkwargsc                 K   s   t || j}t || j}	t||dd| }
|d ur |
| }
tjj|
dtjd	|j
}
tjj|
|| jd}
t|
|	}|dd }||
fS )Nr=   r   rL   )rJ   r?   )ptrainingr   )r   num_key_value_groupsrD   matmulrW   r   
functionalsoftmaxrv   rG   r?   r   r   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightsattn_outputr7   r7   r8   eager_attention_forward9  s   
r   c                       s   e Zd ZdZdedef fddZ		ddejde	ejejf d	ejdB d
e
dB dejdB dee de	ejejf fddZ  ZS )AfmoeAttentionaJ  
    Multi-headed attention module with optional sliding window and gating.

    This attention mechanism supports both full attention and sliding window attention,
    and includes Q/K normalization and gating of the output. It inherits from [`LlamaAttention`] to minimize the amount
    of custom logic we need to maintain.
    r#   	layer_idxc                    s2  t    || _|| _t|d|j|j | _|j|j | _	| 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|jd| _|j| dk| _| jrt|jnd | _t| j|jd| _t| j|jd| _tj|j|j| j dd| _d S )Nr<   g      Tr   sliding_attentionrp   F)r(   r)   r#   r   rA   rB   rC   r<   r   r   r   attention_dropout	is_causalr   r   attention_biasq_projk_projv_projo_projlayer_typesis_local_attentionsliding_windowrn   rms_norm_epsq_normk_normr   r2   r#   r   r5   r7   r8   r)   \  s2   
 zAfmoeAttention.__init__Nrz   position_embeddingsr   past_key_valuecache_positionr   r:   c                 K   sN  |j d d }g |d| jR }| ||}	| ||}
| ||}| |}| |	dd}	| 	|
dd}
|dd}| j
rV|\}}t|	|
||\}	}
|d urid|i}||
|| j|\}
}t| jjt}|| |	|
|f|| js}dn| j| j| jd|\}}|jg |dR   }|t| }| |}||fS )NrL   r   r=   r  r   )r   r   r   r   )rS   r<   r   r   r   r   r   r   rW   r  r   r   updater   r   get_interfacer#   _attn_implementationr   r   r   r   r   r   rD   r   r   )r2   rz   r  r   r  r  r   input_shapehidden_shapequery_statesr   r   gate_statesrY   rZ   cache_kwargsattention_interfaceoutputr   r   r7   r7   r8   ra   {  sF   	
	

zAfmoeAttention.forward)NN)rc   rd   re   r   r    ri   r)   rD   rf   rj   r   
LongTensorr   r   ra   rl   r7   r7   r5   r8   r   R  s(    $r   c                       s   e Zd ZdZdedef fddZ						ddejdejdB d	ej	dB d
e
dB dedB dej	dB deejejf dB dee dejfddZ  ZS )AfmoeDecoderLayerz
    AFMoE decoder layer with dual normalization.

    This layer applies self-attention followed by either a dense MLP or MoE block,
    with dual normalization (pre and post) around each component.
    r#   r   c                    s   t    |j| _|| _t||d| _|j| | _t|j|j	d| _
t|j|j	d| _t|j|j	d| _t|j|j	d| _||jk| _| jrMt|| _d S t|| _d S )N)r#   r   r   )r(   r)   rB   r   r   	self_attnr   attention_typern   r   input_layernormpost_attention_layernormpre_mlp_layernormpost_mlp_layernormnum_dense_layersmoe_enabledr   mlpr~   r  r5   r7   r8   r)     s   
zAfmoeDecoderLayer.__init__Nrz   r   r\   r  	use_cacher  r  r   r:   c              
   K   sr   |}	|  |}| jd|||||||d|\}}
| |}|	| }|}	| |}| |}| |}|	| }|S )N)rz   r   r\   r  r  r  r  r7   )r  r  r  r  r  r  )r2   rz   r   r\   r  r  r  r  r   residualr   r7   r7   r8   ra     s*   






zAfmoeDecoderLayer.forward)NNNNNN)rc   rd   re   r   r    ri   r)   rD   rf   r  r   boolrj   r   r   FloatTensorra   rl   r7   r7   r5   r8   r    s8    	
r  c                       s`   e Zd ZU dZeed< dZdgZdgZe	e
dZg dZdZdZdZdZdZ fd	d
Z  ZS )AfmoePreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    r#   modelr  past_key_values)rz   
attentions)r  r  r  r  r   r  normr   Tc                    sF   t  | t|trt|jj dS t|tr!t|j	 dS dS )zInitialize the weightsN)
r(   _init_weightsrT   r   initzeros_r   rs   r   r   )r2   r   r5   r7   r8   r$    s   

z"AfmoePreTrainedModel._init_weights)rc   rd   re   r   r    rg   base_model_prefix_no_split_modules_skip_keys_device_placementr  r   _can_record_outputs_keep_in_fp32_modules_supports_sdpa_supports_flash_attn_supports_flex_attn_supports_attention_backendsupports_gradient_checkpointingr$  rl   r7   r7   r5   r8   r    s    
 
r  c                       s   e Zd ZdZdef fddZeee							dde	j
dB de	jdB de	jdB d	e	j
dB d
edB de	j
dB dedB dee deeB fddZ  ZS )
AfmoeModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`AfmoeDecoderLayer`]

    Args:
        config: AfmoeConfig
    r#   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 r7   )r  ).0r   r#   r7   r8   
<listcomp>*  s    z'AfmoeModel.__init__.<locals>.<listcomp>r   r3  F)r(   r)   pad_token_idpadding_idx
vocab_sizer   	EmbeddingrB   embed_tokens
ModuleListr   num_hidden_layerslayersrn   r   r#  r!   
rotary_embgradient_checkpointing	post_initr   r5   r3  r8   r)   #  s   zAfmoeModel.__init__N	input_idsr   inputs_embedsr\   r!  r  r  r   r:   c              
   K   sD  |d u |d uA rt d|r|d u rt| jd}|d u r!| |}|d u r=|d ur-| nd}	tj|	|	|jd  |jd}|d u rF|	d}t
| }
tse| j||||d}tdi |tdi |d}
|}| jjrs|| jjd  }| ||}| jD ]}||f|
|j |||||d	|}q|| |}t||r|d
S d d
S )Nz:You must specify exactly one of input_ids or inputs_embedsr3  r   r   )r3   )r#   rA  r   r  r!  )full_attentionr   g      ?)r   r\   r  r  r  r  )last_hidden_stater!  r7   )
ValueErrorr	   r#   r9  get_seq_lengthrD   rE   rS   r3   r   rT   dictr   r   mup_enabledrB   r=  r<  r  r#  r   )r2   r@  r   rA  r\   r!  r  r  r   past_seen_tokenscausal_mask_mappingmask_kwargsrz   r  decoder_layerr7   r7   r8   ra   2  sb   



zAfmoeModel.forward)NNNNNNN)rc   rd   re   r   r    r)   r   r   r   rD   r  rf   r  r   r  r   r   rj   r   ra   rl   r7   r7   r5   r8   r1    s@    	
r1  c                       s   e Zd ZddiZddiZddgdgfiZ fddZee																	
dde	j
d	B de	jd	B de	j
d	B ded	B de	jd	B de	j
d	B ded	B de	j
d	B dee	jB dee defddZ  ZS )AfmoeForCausalLMzlm_head.weightzmodel.embed_tokens.weightlm_headcolwise_gather_outputrz   logitsc                    s@   t  | t|| _|j| _tj|j|jdd| _| 	  d S r   )
r(   r)   r1  r   r7  r   r   rB   rM  r?  r   r5   r7   r8   r)     s
   
zAfmoeForCausalLM.__init__Nr   r@  r   r\   r!  rA  labelsr  r  logits_to_keepr   r:   c
              
   K   s   | j d|||||||d|
}|j}t|	trt|	 dn|	}| |dd|ddf }d}|durB| jd||| jjd|
}t	|||j
|j|jdS )a  
        Example:

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

        >>> model = AfmoeForCausalLM.from_pretrained("meta-afmoe/Afmoe-2-7b-hf")
        >>> tokenizer = AutoTokenizer.from_pretrained("meta-afmoe/Afmoe-2-7b-hf")

        >>> 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 conscious, but I can talk to you."
        ```)r@  r   r\   r!  rA  r  r  N)rO  rP  r7  )lossrO  r!  rz   r"  r7   )r   rC  rT   ri   slicerM  loss_functionr#   r7  r   r!  rz   r"  )r2   r@  r   r\   r!  rA  rP  r  r  rQ  r   outputsrz   slice_indicesrO  rR  r7   r7   r8   ra     s0    zAfmoeForCausalLM.forward)	NNNNNNNNr   )rc   rd   re   _tied_weights_keys_tp_plan_pp_planr)   r   r   rD   r  rf   r   r  r  ri   r   r   r   ra   rl   r7   r7   r5   r8   rL  |  sN    	
rL  )rL  r1  r  )r   )r   )Ecollections.abcr   typingr   rD   r    r   r%  activationsr   cache_utilsr   r	   
generationr
   integrationsr   r   r   masking_utilsr   r   modeling_layersr   modeling_outputsr   r   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   utils.genericr   r   utils.output_capturingr   configuration_afmoer    Moduler!   rn   r~   r   r:  r   r   r   r   rf   ri   r   rH   r   r   r  r  r1  rL  __all__r7   r7   r7   r8   <module>   sr   A>
[E'aI