o
    ei$                     @   sz  d dl Z 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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 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/m0Z0 ddl1m2Z2 ddl3m4Z4 e-5e6Z7G dd dej8Z9G dd dej8Z:dd Z;edd@ddZ<d ej=d!e>d"ej=fd#d$Z?d%d& Z@G d'd( d(ej8ZAG d)d* d*eAZBG d+d, d,eAZCed-G d.d/ d/ej8ZDeAeBeCd0ZEG d1d2 d2eZFe+G d3d4 d4e&ZGe+G d5d6 d6eGZHe+G d7d8 d8eGeZIG d9d: d:eeGZJG d;d< d<eeGZKG d=d> d>eeGZLg d?ZMdS )A    N)Callable)Optional)nn   )initialization)ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)use_kernel_forward_from_hubuse_kernel_func_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)maybe_autocastmerge_with_config_defaults)capture_outputs   )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__ n/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/transformers/models/diffllama/modeling_diffllama.pyr)   9   s   
zDiffLlamaMLP.__init__c                 C   s$   |  | | || | }|S N)r0   r2   r.   r/   )r4   xr0   r7   r7   r8   forwardC   s    zDiffLlamaMLP.forward)__name__
__module____qualname__r)   r;   __classcell__r7   r7   r5   r8   r$   8   s    
r$   c                       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 )DiffLlamaRotaryEmbeddinginv_freqNr*   c                    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defaultrA   F)
persistentoriginal_inv_freq)r(   r)   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr*   rope_parametersrB   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r4   r*   devicerope_init_fnrA   r5   r7   r8   r)   K   s   


z!DiffLlamaRotaryEmbedding.__init__rN   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)rN   rV   )	rI   getattrr+   num_attention_headstorcharangeint64tofloat)r*   rN   rP   basedimattention_factorrA   r7   r7   r8   rJ   [   s   
&z8DiffLlamaRotaryEmbedding.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enabledrT   r_   rU   )rA   r]   expandshaper\   rN   
isinstancetypestrr   	transposerY   catcosrK   sinrV   )
r4   r:   position_idsinv_freq_expandedposition_ids_expandedrd   freqsembrn   ro   r7   r7   r8   r;   y   s   0&z DiffLlamaRotaryEmbedding.forwardr9   )NNN)r<   r=   r>   rY   Tensor__annotations__r#   r)   staticmethodr   inttupler]   rJ   no_gradr   r;   r?   r7   r7   r5   r8   r@   H   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..Nra   rT   rf   )rh   rY   rm   )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.
    )	unsqueezer}   )qkrn   ro   unsqueeze_dimq_embedk_embedr7   r7   r8   apply_rotary_pos_emb   s
   

r   hidden_statesn_reprQ   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)rh   rg   reshape)r   r   batchnum_key_value_headsslenrS   r7   r7   r8   	repeat_kv   s
   0r   c                 C   s   ddt d|    S )Ng?g333333?g333333ӿ)mathexp)	layer_idxr7   r7   r8   lambda_init_fn   s   r   c                       s   e Zd ZdZddededB f fddZ					ddejd	e	ejejf d
ejdB dej
dB dedB dedej
dB de	ejejdB e	ej dB 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| _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.rS   Tr&   r   )sizerT   F)epselementwise_affine)&r(   r)   r*   r   loggerwarning_oncer6   r<   attention_dropoutr+   rX   	num_headsrW   rS   r   num_key_value_groupsrF   	is_causalr   r-   attention_biasq_projk_projv_projo_projr   lambda_init	ParameterrY   normallambda_std_dev	lambda_q1	lambda_k1	lambda_q2	lambda_k2RMSNormrms_norm_eps	groupnormr4   r*   r   r5   r7   r8   r)      s2   

zDiffLlamaAttention.__init__Fr   position_embeddingsattention_maskrp   past_key_values	use_cachecache_positionrQ   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|| }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"   rT   ro   rn   r   rf   ra   r   r_   rV   )ptraining))r   r   r   r   viewr   rS   rl   r   r   updater   r   r   rY   rm   chunkrepeatmatmulr   sqrtr   
functionalsoftmaxfloat32r\   rV   dropoutr   r   r   sumr   r   r   r   r   r   
contiguousr   r   )r4   r   r   r   rp   r   r   r   kwargsbsz
target_len_q_lenquery_states
key_statesvalue_statesrn   ro   cache_kwargsattn_weightslambda_1lambda_2lambda_fullattn_outputattn_output1attn_output2r7   r7   r8   r;      sJ   


   
zDiffLlamaAttention.forwardr9   NNNFN)r<   r=   r>   __doc__r#   rx   r)   rY   ru   ry   
LongTensorr   boolr;   r?   r7   r7   r5   r8   r      s2    %
r   c                       s   e Zd ZdZ fddZ					ddejdeejejf dejdB d	ejdB d
e	dB de
dejdB 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 r9   )r(   r)   r   _flash_attn_uses_top_left_mask)r4   argsr   r5   r7   r8   r)   #  s   z!DiffLlamaFlashAttention2.__init__NFr   r   r   rp   r   r   r   rQ   c                 C   s  t |tr	td| \}}	}
| |}| |}| |}|||	| j| j	
dd}|||	| j| j	
dd}|||	| j| j	
dd}|\}}t||||\}}|d urk|||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|}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+ | ,| }|-||	d. }| /|}|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"   rT   r           rb   rc   _is_quantizedzThe 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 .rf   sliding_window)rp   r   r   use_top_left_maskr   ra   r   )0ri   r
   
ValueErrorr   r   r   r   r   r   rS   rl   r   r   r   r   r   r   rV   rN   rj   rY   r   is_autocast_enabledget_autocast_dtypehasattrr*   weightr   r   r\   r   r   r   rW   r   r   rm   r   r   r   r   r   r   r   r   r   r   r   )r4   r   r   r   rp   r   r   r   r   r   r   r   r   r   rn   ro   r   dropout_rateinput_dtyperd   target_dtypevalue_states1value_states2r   r   r   r   r   r   r7   r7   r8   r;   +  s   













  
z DiffLlamaFlashAttention2.forwardr   )r<   r=   r>   r   r)   rY   ru   ry   r   r   r   r;   r?   r7   r7   r5   r8   r     s2    	r   c                   @   s   e Zd ZdZ					ddejdeejejf dejdB dejdB dedB d	e	d
ejdB deejejdB eej dB 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.
    NFr   r   r   rp   r   r   r   rQ   c                 K   s0  |  \}	}
}| |}| |}| |}||	|
| 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 }|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"   rT   r   rf   ra   r   )	attn_mask	dropout_pr   r   )%r   r   r   r   r   r   rS   rl   r   r   r   r   r   r   rY   rm   r   r   rh   r   r   scaled_dot_product_attentionr   r   r   r   r   r   r   r\   rV   r   r   r   r   r   r   )r4   r   r   r   rp   r   r   r   r   r   r   r   r   r   r   rn   ro   r   causal_maskr   r   r   r   r   r   r   r7   r7   r8   r;     sT   


&	  
zDiffLlamaSdpaAttention.forwardr   )r<   r=   r>   r   rY   ru   ry   r   r   r   r;   r7   r7   r7   r8   r     s0    
r   r   c                       sF   e Zd Zddeddf fddZdejdejfdd	Zd
d Z  Z	S )DiffLlamaRMSNormư>r   rQ   Nc                    s&   t    tt|| _|| _dS )z?
        DiffLlamaRMSNorm is equivalent to T5LayerNorm
        N)r(   r)   r   r   rY   onesr   variance_epsilon)r4   r+   r   r5   r7   r8   r)     s   

zDiffLlamaRMSNorm.__init__r   c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )NrT   ra   T)keepdim)	rV   r\   rY   r   powmeanrsqrtr   r   )r4   r   r   variancer7   r7   r8   r;     s
   zDiffLlamaRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)ry   r   rh   r   )r4   r7   r7   r8   
extra_repr  s   zDiffLlamaRMSNorm.extra_repr)r   )
r<   r=   r>   r]   r)   rY   ru   r;   r   r?   r7   r7   r5   r8   r     s    r   )eagerflash_attention_2sdpac                       s   e 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 )DiffLlamaDecoderLayerr*   r   c                    sX   t    |j| _t|j ||d| _t|| _t|j|j	d| _
t|j|j	d| _d S )N)r*   r   r   )r(   r)   r+   DIFFLLAMA_ATTENTION_CLASSES_attn_implementation	self_attnr$   mlpr   r   input_layernormpost_attention_layernormr   r5   r7   r8   r)     s   

zDiffLlamaDecoderLayer.__init__NFr   r   rp   r   r   r   r   r   rQ   c              
   K   s^   |}	|  |}| jd|||||||d|\}}
|	| }|}	| |}| |}|	| }|S )N)r   r   rp   r   r   r   r   r7   )r   r   r  r   )r4   r   r   rp   r   r   r   r   r   residualr   r7   r7   r8   r;     s&   




zDiffLlamaDecoderLayer.forward)NNNFNN)r<   r=   r>   r#   rx   r)   rY   ru   r   r   r   ry   r   r   r;   r?   r7   r7   r5   r8   r     s6    	
r   c                       s`   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e  fdd	Z  ZS )
DiffLlamaPreTrainedModelr*   modelTr   r   F)r   
attentionsc                    sn   t  | t|tr5t|jd| jj t|j	d| jj t|j
d| jj t|jd| jj d S d S )Nr   )r(   _init_weightsri   r   initnormal_r   r*   r   r   r   r   )r4   moduler5   r7   r8   r  K  s   
z&DiffLlamaPreTrainedModel._init_weights)r<   r=   r>   r#   rv   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_outputsrY   rz   r  r?   r7   r7   r5   r8   r  9  s    
 r  c                       s   e 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dB d	ejdB d
ej	dB dedB 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 r7   )r   ).0r   r*   r7   r8   
<listcomp>^  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@   
rotary_embgradient_checkpointing	post_initr3   r5   r  r8   r)   W  s   zDiffLlamaModel.__init__N	input_idsr   rp   r   inputs_embedsr   r   r   rQ   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 rE|	d}t
| j|||||d}
|}| 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"   )rN   )r*   r&  r   r   r   rp   )rp   )r   r   rp   r   r   r   )last_hidden_stater   )r   r  r	   r*   get_seq_lengthrY   rZ   rh   rN   r   r   r"  r   r  r!  r   )r4   r%  r   rp   r   r&  r   r   r   past_seen_tokensr   r   r   decoder_layerr7   r7   r8   r;   g  sP   

	
zDiffLlamaModel.forward)NNNNNNN)r<   r=   r>   r#   r)   r    r!   r   rY   r   ru   r   FloatTensorr   r   r   r   r;   r?   r7   r7   r5   r8   r  U  s>    	
r  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 )DiffLlamaForCausalLMzlm_head.weightzmodel.embed_tokens.weightlm_headcolwise_gather_outputr   logitsc                    s@   t  | t|| _|j| _tj|j|jdd| _| 	  d S r%   )
r(   r)   r  r  r  r   r-   r+   r-  r$  r3   r5   r7   r8   r)     s
   
zDiffLlamaForCausalLM.__init__Nr   r%  r   rp   r   r&  labelsr   r   logits_to_keepr   rQ   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   rp   r   r&  r   r   N)r/  r0  r  )lossr/  r   r   r  r7   )r  r'  ri   rx   slicer-  loss_functionr*   r  r   r   r   r  )r4   r%  r   rp   r   r&  r0  r   r   r1  r   outputsr   slice_indicesr/  r2  r7   r7   r8   r;     s0    zDiffLlamaForCausalLM.forward)	NNNNNNNNr   )r<   r=   r>   _tied_weights_keys_tp_plan_pp_planr)   r   r   rY   r   ru   r   r+  r   rx   r   r   r   r;   r?   r7   r7   r5   r8   r,    sN    		
r,  c                   @      e Zd ZdS )"DiffLlamaForSequenceClassificationNr<   r=   r>   r7   r7   r7   r8   r;        r;  c                   @   s   e Zd ZdZdS )DiffLlamaForQuestionAnsweringtransformerN)r<   r=   r>   r
  r7   r7   r7   r8   r>    s    r>  c                   @   r:  )DiffLlamaForTokenClassificationNr<  r7   r7   r7   r8   r@    r=  r@  )r  r  r,  r;  r>  r@  )r"   )Nr   collections.abcr   typingr   rY   r    r   r  activationsr   cache_utilsr   r	   r
   
generationr   integrationsr   r   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.genericr   r    utils.output_capturingr!   configuration_diffllamar#   
get_loggerr<   r   Moduler$   r@   r}   r   ru   rx   r   r   r   r   r   r   r   r   r  r  r,  r;  r>  r@  __all__r7   r7   r7   r8   <module>   sd   
Ab M-PK