o
    	۷ij                     @   sV  d dl Z d dlmZ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 dd
lmZmZ ddlmZ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# ddl$m%Z%m&Z&m'Z'm(Z( ddl)m*Z* ddl+m,Z, ddl-m.Z. e(/e0Z1G dd dej2Z3dd Z4d=ddZ5dej6de7dej6fddZ8d d! Z9G d"d# d#ej2Z:G d$d% d%e:Z;G d&d' d'e:Z<ed(G d)d* d*ej2Z=e:e;e<d+Z>G d,d- d-eZ?e&G d.d/ d/e!Z@G d0d1 d1ej2ZAe&G d2d3 d3e@ZBe&G d4d5 d5e@eZCG d6d7 d7ee@ZDG d8d9 d9ee@ZEG d:d; d;ee@ZFg d<ZGdS )>    N)OptionalUnion)nn   )ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)use_kernel_forward_from_hub)create_causal_mask)_flash_attention_forward!flash_attn_supports_top_left_mask)GenericForQuestionAnswering GenericForSequenceClassificationGenericForTokenClassificationGradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)PreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuplelogging)deprecate_kwarg)check_model_inputs   )DiffLlamaConfigc                       s$   e Zd Z fddZdd Z  ZS )DiffLlamaMLPc                    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)super__init__confighidden_sizeintermediate_sizer   Linear	gate_projup_proj	down_projr   
hidden_actact_fnselfr'   	__class__ f/home/ubuntu/vllm_env/lib/python3.10/site-packages/transformers/models/diffllama/modeling_diffllama.pyr&   8   s   
zDiffLlamaMLP.__init__c                 C   s$   |  | | || | }|S N)r-   r/   r+   r,   )r1   xr-   r4   r4   r5   forwardB   s    zDiffLlamaMLP.forward)__name__
__module____qualname__r&   r8   __classcell__r4   r4   r2   r5   r!   7   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..N   dim)shapetorchcat)r7   x1x2r4   r4   r5   rotate_halfG   s   rF   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.
    )	unsqueezerF   )qkcossinposition_idsunsqueeze_dimq_embedk_embedr4   r4   r5   apply_rotary_pos_embN   s
   

rP   hidden_statesn_repreturnc                 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)rA   expandreshape)rQ   rR   batchnum_key_value_headsslenhead_dimr4   r4   r5   	repeat_kvi   s
   0rZ   c                 C   s   ddt d|    S )Ng?g333333?g333333ӿ)mathexp)	layer_idxr4   r4   r5   lambda_init_fnu   s   r^   c                       s   e Zd ZdZddedee f fddZeddd	d
					dde	j
dee	j
e	j
f dee	j
 dee	j dee dedee	j dee	j
ee	j
 eee	j
  f fddZ  ZS )DiffLlamaAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNr'   r]   c                    s  t    || _|| _|d u rtd| jj d |j| _|j	| _	|j
| _t|d| j	| j | _|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| _tj| j| j | j	|jd| _t|| _ttjd|j| jfd| _ ttjd|j| jfd| _!ttjd|j| jfd| _"ttjd|j| jfd| _#tj$d| j |j%d	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.rY   Tr#   r   )sizer>   F)epselementwise_affine)'r%   r&   r'   r]   loggerwarning_oncer3   r9   attention_dropoutr(   num_attention_heads	num_headsgetattrrY   rW   num_key_value_groupsmax_position_embeddings
rope_theta	is_causalr   r*   attention_biasq_projk_projv_projo_projr^   lambda_init	ParameterrB   normallambda_std_dev	lambda_q1	lambda_k1	lambda_q2	lambda_k2RMSNormrms_norm_eps	groupnormr1   r'   r]   r2   r4   r5   r&   |   s4   

zDiffLlamaAttention.__init__past_key_valuepast_key_values4.58new_nameversionFrQ   position_embeddingsattention_maskrL   	use_cachecache_positionrS   c                 K   s`  |  \}	}
}|
}| |}| |}| |}||	|| j| jdd}||	|| j| jdd}||	|| j| jdd}|\}}t	||||\}}|d urd|||d}|
||| j|\}}t|| j}t|| j}tjtj|ddddd}|dddd}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tj | j!| j" dtjd|j}ttj | j#| j$ dtjd|j}|| | j% }t||}tj|ddd\}}|||  }d| j% | &| }|dd' }|(|	|d}| )|}||fS )
Nr   r>   rK   rJ   r   r?   r=   r   r@   dtype)ptraining)*r`   rn   ro   rp   viewrg   rY   	transposerW   rP   updater]   rZ   ri   rB   rC   chunkrepeatmatmulr[   sqrtrA   r   
functionalsoftmaxfloat32tor   dropoutre   r   r\   sumrv   rw   rx   ry   rr   r|   
contiguousrU   rq   )r1   rQ   r   r   rL   r   r   r   kwargsbsz
target_len_q_lenquery_states
key_statesvalue_statesrJ   rK   cache_kwargsattn_weightscausal_masklambda_1lambda_2lambda_fullattn_outputattn_output1attn_output2r4   r4   r5   r8      sL   


 &  
zDiffLlamaAttention.forwardr6   NNNFN)r9   r:   r;   __doc__r    r   intr&   r   rB   Tensortuple
LongTensorr   boolr8   r<   r4   r4   r2   r5   r_   y   s4    "
r_   c                       s   e Zd ZdZ fddZedddd						dd
ejdeejejf de	ej
 de	ej
 de	e dede	ej
 deejdf fddZ  ZS )DiffLlamaFlashAttention2aN  
    DiffLlama flash attention module. This module inherits from `DiffLlamaAttention` 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 r6   )r%   r&   r   _flash_attn_uses_top_left_mask)r1   argsr   r2   r4   r5   r&      s   z!DiffLlamaFlashAttention2.__init__r~   r   r   r   NFrQ   r   r   rL   r   r   rS   c                 C   s  t |tr	td| \}}	}
| |}| |}| |}|||	| j| j	
dd}|||	| j| j	
dd}|||	| j| j	
dd}|d u r[td | ||\}}n|\}}t||||\}}|d ur}|||d}|||| j|\}}|
dd}|
dd}|
dd}| jr| jnd}|j}|jjdkr|jjnd}|tjkrt rttd	rt|nt }nt| jd
r| jj}n| jjj}td| d | |}| |}| |}tj!|ddd\}}|"dddd}|"dddd}t#|||||	||t$| dd | j%| j&d
}t#|||||	||t$| dd | j%| j&d
}tj'||gdd}tj!|ddd\}}t(tj)| j*| j+ dtjd |j}t(tj)| j,| j- dtjd |j}|| | j. }|||  }d| j. | /| }|0||	d1 }| 2|}|d fS )Nz`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformersr   r>   aY  The attention layers in this model are transitioning from computing the RoPE embeddings internally through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed `position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be removed and `position_embeddings` will be mandatory.r           mpscpuget_autocast_dtype_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?   sliding_window)rL   r   r   use_top_left_maskrl   r=   r   )3
isinstancer	   
ValueErrorr`   rn   ro   rp   r   rg   rY   r   rW   rc   rd   
rotary_embrP   r   r]   r   re   r   devicetyperB   r   is_autocast_enabledhasattrr   get_autocast_gpu_dtyper'   r   weightr   r   r   r   rh   r   rl   rC   r\   r   rv   rw   rx   ry   rr   r|   rU   r   rq   )r1   rQ   r   r   rL   r   r   r   r   r   r   r   r   r   rJ   rK   r   dropout_rateinput_dtypedevice_typetarget_dtypevalue_states1value_states2r   r   r   r   r   r   r4   r4   r5   r8      s   











  
z DiffLlamaFlashAttention2.forwardr   )r9   r:   r;   r   r&   r   rB   r   r   r   r   r   r   r8   r<   r4   r4   r2   r5   r      s4    	r   c                   @   s   e Zd ZdZedddd					ddejd	eejejf d
eej deej	 dee
 dedeej	 deejeej eeej  f fddZdS )DiffLlamaSdpaAttentiona   
    DiffLlama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `DiffLlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    r~   r   r   r   NFrQ   r   r   rL   r   r   rS   c                 K   s\  |  \}	}
}| |}| |}| |}||	|
| j| jdd}||	|
| j| jdd}||	|
| j| jdd}|\}}t	||||\}}|d urb|||d}|
||| j|\}}t|| j}t|| j}tjtj|ddddd}|dddd}|}|d ur|d d d d d d d |jd f }|jjdkr|d ur| }| }| }|d u o|
dk}tjjj||||| jr| jnd|d	}tj|ddd\}}ttj| j| j dtjd
 |j!}ttj| j"| j# dtjd
 |j!}|| | j$ }|||  }d| j$ | %| }|dd }||	|
d}| &|}|d fS )Nr   r>   r   r?   r=   r   cudar   )	attn_mask	dropout_prl   r   )'r`   rn   ro   rp   r   rg   rY   r   rW   rP   r   r]   rZ   ri   rB   rC   r   r   rA   r   r   r   r   r   scaled_dot_product_attentionr   re   r\   r   rv   rw   r   r   r   rx   ry   rr   r|   rq   )r1   rQ   r   r   rL   r   r   r   r   r   r   r   r   r   r   rJ   rK   r   r   rl   r   r   r   r   r   r   r4   r4   r5   r8   {  s\   


&	  
zDiffLlamaSdpaAttention.forwardr   )r9   r:   r;   r   r   rB   r   r   r   r   r   r   r8   r4   r4   r4   r5   r   s  s2    
r   rz   c                       s.   e Zd Zd fdd	Zdd Zdd Z  ZS )	DiffLlamaRMSNormư>c                    s&   t    tt|| _|| _dS )z?
        DiffLlamaRMSNorm is equivalent to T5LayerNorm
        N)r%   r&   r   rs   rB   onesr   variance_epsilon)r1   r(   ra   r2   r4   r5   r&     s   

zDiffLlamaRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )Nr>   r=   T)keepdim)	r   r   rB   r   powmeanrsqrtr   r   )r1   rQ   r   variancer4   r4   r5   r8     s
   zDiffLlamaRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)r   r   rA   r   )r1   r4   r4   r5   
extra_repr  s   zDiffLlamaRMSNorm.extra_repr)r   )r9   r:   r;   r&   r8   r   r<   r4   r4   r2   r5   r     s    r   )eagerflash_attention_2sdpac                       s   e Zd Zdedef fddZedddd							
				ddejde	ej de	ej
 de	e de	e de	ej
 de	eejejf  dee dejfddZ  ZS )DiffLlamaDecoderLayerr'   r]   c                    sX   t    |j| _t|j ||d| _t|| _t|j|j	d| _
t|j|j	d| _d S )N)r'   r]   ra   )r%   r&   r(   DIFFLLAMA_ATTENTION_CLASSES_attn_implementation	self_attnr!   mlpr   r{   input_layernormpost_attention_layernormr}   r2   r4   r5   r&     s   

zDiffLlamaDecoderLayer.__init__r~   r   r   r   NFrQ   r   rL   r   r   r   r   rS   c              
   K   s^   |}	|  |}| jd|||||||d|\}}
|	| }|}	| |}| |}|	| }|S )N)rQ   r   rL   r   r   r   r   r4   )r   r   r   r   )r1   rQ   r   rL   r   r   r   r   r   residualr   r4   r4   r5   r8     s&   




zDiffLlamaDecoderLayer.forward)NNNFNN)r9   r:   r;   r    r   r&   r   rB   r   r   r   r   r   r   r   r   r8   r<   r4   r4   r2   r5   r     s8    
	
r   c                       sX   e Zd ZU eed< dZdZdgZdgZdZ	dZ
dZdZdZeedZ fdd	Z  ZS )
DiffLlamaPreTrainedModelr'   modelTr   r   F)rQ   
attentionsc                    sn   t  | t|tr5|jjd| jj |j	jd| jj |j
jd| jj |jjd| jj d S d S )Nr   )r%   _init_weightsr   r_   rv   datanormal_r'   ru   rw   rx   ry   )r1   moduler2   r4   r5   r   $  s   
z&DiffLlamaPreTrainedModel._init_weights)r9   r:   r;   r    __annotations__base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraph_supports_attention_backendr   r_   _can_record_outputsr   r<   r4   r4   r2   r5   r     s   
 r   c                       sD   e Zd ZU ejed< ddef fddZe e	dd Z
  ZS )	DiffLlamaRotaryEmbeddinginv_freqNr'   c                    s   t    t|drt|jtr|jd|jd| _nd| _|j| _	|j| _
|| _t| j | _| | j|\}| _| jd|dd | j| _d S )Nrope_scaling	rope_typer   defaultr   F)
persistent)r%   r&   r   r   r   dictgetr   rj   max_seq_len_cachedoriginal_max_seq_lenr'   r   rope_init_fnattention_scalingregister_bufferr   original_inv_freq)r1   r'   r   r   r2   r4   r5   r&   0  s   
z!DiffLlamaRotaryEmbedding.__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   r   r   F)r   enabledr>   r?   )r   )r   floatrT   rA   r   r   r   r   strrB   autocastr   rC   rJ   r  rK   r   )
r1   r7   rL   inv_freq_expandedposition_ids_expandedr   freqsembrJ   rK   r4   r4   r5   r8   A  s   0&z DiffLlamaRotaryEmbedding.forwardr6   )r9   r:   r;   rB   r   r   r    r&   no_gradr   r8   r<   r4   r4   r2   r5   r   -  s   
 
r   c                       s   e Zd Zdef fddZe e							ddeej	 deej
 deej	 dee d	eej d
eej	 dee dee defddZ  ZS )DiffLlamaModelr'   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 r4   )r   ).0r]   r'   r4   r5   
<listcomp>Z  s    z+DiffLlamaModel.__init__.<locals>.<listcomp>r   r  F)r%   r&   pad_token_idpadding_idx
vocab_sizer   	Embeddingr(   embed_tokens
ModuleListrangenum_hidden_layerslayersr   r{   normr   r   gradient_checkpointing	post_initr0   r2   r  r5   r&   S  s   zDiffLlamaModel.__init__N	input_idsr   rL   r   inputs_embedsr   r   r   rS   c              	   K   s   |d u |d uA rt d|d u r| |}|r!|d u r!t| jd}|d u r=|d ur-| nd}	tj|	|	|jd  |jd}|d u rF|	d}t
| j|||||d}
|}| ||}| jd | jj D ]}||f|
||||d|}qb| |}t||dS )	Nz:You must specify exactly one of input_ids or inputs_embedsr  r   r   )r   )r'   input_embedsr   r   r   rL   )r   rL   r   r   r   )last_hidden_stater   )r   r  r   r'   get_seq_lengthrB   arangerA   r   rG   r   r   r  r  r  r   )r1   r"  r   rL   r   r#  r   r   r   past_seen_tokensr   rQ   r   decoder_layerr4   r4   r5   r8   c  sP   

	

zDiffLlamaModel.forward)NNNNNNN)r9   r:   r;   r    r&   r   r   r   rB   r   r   r   FloatTensorr   r   r   r   r8   r<   r4   r4   r2   r5   r  Q  s<    	
r  c                       s   e Zd ZdgZddiZddgdgfiZ fddZee										dd
e	e
j de	e
j de	e
j de	e de	e
j de	e
j de	e de	e
j deee
jf dee defddZ  ZS )DiffLlamaForCausalLMzlm_head.weightlm_headcolwise_reprQ   logitsc                    s@   t  | t|| _|j| _tj|j|jdd| _| 	  d S r"   )
r%   r&   r  r   r  r   r*   r(   r,  r!  r0   r2   r4   r5   r&     s
   
zDiffLlamaForCausalLM.__init__Nr   r"  r   rL   r   r#  labelsr   r   logits_to_keepr   rS   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, DiffLlamaForCausalLM

        >>> model = DiffLlamaForCausalLM.from_pretrained("google/diffllama-7b")
        >>> tokenizer = AutoTokenizer.from_pretrained("google/diffllama-7b")

        >>> prompt = "What is your favorite condiment?"
        >>> 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]
        "What is your favorite condiment?"
        ```)r"  r   rL   r   r#  r   r   N)r.  r/  r  )lossr.  r   rQ   r   r4   )r   r%  r   r   slicer,  loss_functionr'   r  r   r   rQ   r   )r1   r"  r   rL   r   r#  r/  r   r   r0  r   outputsrQ   slice_indicesr.  r1  r4   r4   r5   r8     s0    zDiffLlamaForCausalLM.forward)	NNNNNNNNr   )r9   r:   r;   _tied_weights_keys_tp_plan_pp_planr&   r   r   r   rB   r   r   r   r*  r   r   r   r   r   r   r8   r<   r4   r4   r2   r5   r+    sN    		
r+  c                   @      e Zd ZdS )"DiffLlamaForSequenceClassificationNr9   r:   r;   r4   r4   r4   r5   r:        r:  c                   @   s   e Zd ZdZdS )DiffLlamaForQuestionAnsweringtransformerN)r9   r:   r;   r   r4   r4   r4   r5   r=    s    r=  c                   @   r9  )DiffLlamaForTokenClassificationNr;  r4   r4   r4   r5   r?    r<  r?  )r   r  r+  r:  r=  r?  )Nr   )Hr[   typingr   r   rB   r   activationsr   cache_utilsr   r   r	   
generationr
   integrationsr   masking_utilsr   modeling_flash_attention_utilsr   r   modeling_layersr   r   r   r   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   processing_utilsr   utilsr   r   r   r   utils.deprecationr   utils.genericr   configuration_diffllamar    
get_loggerr9   rc   Moduler!   rF   rP   r   r   rZ   r^   r_   r   r   r   r   r   r   r   r  r+  r:  r=  r?  __all__r4   r4   r4   r5   <module>   s^   

e U.$NK