a
    hh                     @   sR  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Z5ej6e7ej6d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 d.d/ d/ej2ZAe&G d0d1 d1e@ZBe&G d2d3 d3e@eZCG d4d5 d5ee@ZDG d6d7 d7ee@ZEG d8d9 d9e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Zbias)super__init__confighidden_sizeZintermediate_sizer   Linear	gate_projup_proj	down_projr   Z
hidden_actact_fnselfr&   	__class__ l/var/www/html/assistant/venv/lib/python3.9/site-packages/transformers/models/diffllama/modeling_diffllama.pyr%   8   s    
zDiffLlamaMLP.__init__c                 C   s$   |  | | || | }|S N)r+   r,   r)   r*   )r.   xr+   r1   r1   r2   forwardB   s     zDiffLlamaMLP.forward)__name__
__module____qualname__r%   r5   __classcell__r1   r1   r/   r2   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)r4   x1Zx2r1   r1   r2   rotate_halfG   s    rB   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.
    )	unsqueezerB   )qkcossinposition_idsZunsqueeze_dimZq_embedZk_embedr1   r1   r2   apply_rotary_pos_embN   s
    

rI   )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)r>   expandreshape)rJ   rK   batchnum_key_value_headsslenhead_dimr1   r1   r2   	repeat_kvi   s
    0rS   c                 C   s   ddt d|    S )Ng?g333333?g333333ӿ)mathexp)	layer_idxr1   r1   r2   lambda_init_fnu   s    rW   c                       s   e Zd ZdZdeee d fddZedddd	de	j
ee	j
e	j
f ee	j
 ee	j ee eee	j ee	j
ee	j
 eee	j
  f dddZ  ZS )DiffLlamaAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNr&   rV   c                    s  t    || _|| _|d u r4t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.rR   Tr#   r   )sizer;   F)epsZelementwise_affine)'r$   r%   r&   rV   loggerwarning_oncer0   r6   attention_dropoutr'   Znum_attention_heads	num_headsgetattrrR   rP   num_key_value_groupsmax_position_embeddingsZ
rope_theta	is_causalr   r(   Zattention_biasq_projk_projv_projo_projrW   lambda_init	Parameterr?   normallambda_std_dev	lambda_q1	lambda_k1	lambda_q2	lambda_k2RMSNormrms_norm_eps	groupnormr.   r&   rV   r/   r1   r2   r%   |   s4    

zDiffLlamaAttention.__init__past_key_valuepast_key_values4.58new_nameversionFrJ   position_embeddingsattention_maskrH   ru   	use_cachecache_positionrL   c                 K   sb  |  \}	}
}|
}| |}| |}| |}||	|| j| jdd}||	|| j| jdd}||	|| j| jdd}|\}}t	||||\}}|d ur|||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rb|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;   rG   rF   r~   r<   r:   r   r=   dtype)ptraining)*rZ   rd   re   rf   viewr_   rR   	transposerP   rI   updaterV   rS   ra   r?   r@   chunkrepeatmatmulrT   sqrtr>   r   
functionalZsoftmaxfloat32tor   dropoutr^   r   rU   sumrl   rm   rn   ro   rh   rr   
contiguousrN   rg   )r.   rJ   r{   r|   rH   ru   r}   r~   kwargsbszZ
target_len_q_lenquery_states
key_statesvalue_statesrF   rG   cache_kwargsZattn_weightscausal_masklambda_1lambda_2lambda_fullattn_outputattn_output1attn_output2r1   r1   r2   r5      sL    


 
&  
zDiffLlamaAttention.forward)N)NNNFN)r6   r7   r8   __doc__r    r   intr%   r   r?   Tensortuple
LongTensorr   boolr5   r9   r1   r1   r/   r2   rX   y   s$   "     rX   c                       sz   e Zd ZdZ fddZedddddejeejejf e	ej
 e	ej
 e	e ee	ej
 eejdf d
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 r3   )r$   r%   r   _flash_attn_uses_top_left_mask)r.   argsr   r/   r1   r2   r%      s    z!DiffLlamaFlashAttention2.__init__rt   ru   rv   rw   NFrz   c                 C   s$  t |trtd| \}}	}
| |}| |}| |}|||	| j| j	
dd}|||	| j| j	
dd}|||	| j| j	
dd}|d u rtd | ||\}}n|\}}t||||\}}|d ur|||d}|||| j|\}}|
dd}|
dd}|
dd}| jr,| jnd}|j}|jjdkrL|jjnd}|tjkrt rttd	r|t|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)rH   r   r   Zuse_top_left_maskrc   r:   r   )3
isinstancer	   
ValueErrorrZ   rd   re   rf   r   r_   rR   r   rP   r\   r]   
rotary_embrI   r   rV   r   r^   r   devicetyper?   r   Zis_autocast_enabledhasattrr   Zget_autocast_gpu_dtyper&   r   weightr   r   r   r   r`   r   rc   r@   rU   r   rl   rm   rn   ro   rh   rr   rN   r   rg   )r.   rJ   r{   r|   rH   ru   r}   r~   r   r   r   r   r   r   rF   rG   r   Zdropout_rateinput_dtypedevice_typeZtarget_dtypeZvalue_states1Zvalue_states2r   r   r   r   r   r   r1   r1   r2   r5      s    











  
z DiffLlamaFlashAttention2.forward)NNNFN)r6   r7   r8   r   r%   r   r?   r   r   r   r   r   r   r5   r9   r1   r1   r/   r2   r      s$        r   c                   @   s|   e Zd ZdZedddddejeejejf eej eej	 ee
 eeej	 eejeej eeej  f d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.
    rt   ru   rv   rw   NFrz   c                 K   sf  |  \}	}
}| |}| |}| |}||	|
| j| jdd}||	|
| j| jdd}||	|
| j| jdd}|\}}t	||||\}}|d ur|||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rj|d urj| }| }| }|d u oz|
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   )Z	attn_maskZ	dropout_prc   r   )'rZ   rd   re   rf   r   r_   rR   r   rP   rI   r   rV   rS   ra   r?   r@   r   r   r>   r   r   r   r   r   Zscaled_dot_product_attentionr   r^   rU   r   rl   rm   r   r   r   rn   ro   rh   rr   rg   )r.   rJ   r{   r|   rH   ru   r}   r~   r   r   r   r   r   r   r   rF   rG   r   r   rc   r   r   r   r   r   r   r1   r1   r2   r5   {  s\    



&	  
zDiffLlamaSdpaAttention.forward)NNNFN)r6   r7   r8   r   r   r?   r   r   r   r   r   r   r5   r1   r1   r1   r2   r   s  s"        r   rp   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   ri   r?   Zonesr   variance_epsilon)r.   r'   r[   r/   r1   r2   r%     s    
zDiffLlamaRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )Nr;   r:   T)Zkeepdim)	r   r   r?   r   powmeanZrsqrtr   r   )r.   rJ   r   Zvariancer1   r1   r2   r5     s
    zDiffLlamaRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)r   r   r>   r   )r.   r1   r1   r2   
extra_repr  s    zDiffLlamaRMSNorm.extra_repr)r   )r6   r7   r8   r%   r5   r   r9   r1   r1   r/   r2   r     s   r   )eagerZflash_attention_2Zsdpac                       s   e Zd Zeed fddZedddddeje	ej e	ej
 e	e e	e e	ej
 e	eejejf  ee ejd
	ddZ  ZS )DiffLlamaDecoderLayerrY   c                    sX   t    |j| _t|j ||d| _t|| _t|j|j	d| _
t|j|j	d| _d S )NrY   r[   )r$   r%   r'   DIFFLLAMA_ATTENTION_CLASSESZ_attn_implementation	self_attnr!   mlpr   rq   input_layernormpost_attention_layernormrs   r/   r1   r2   r%     s    

zDiffLlamaDecoderLayer.__init__rt   ru   rv   rw   NF)	rJ   r|   rH   ru   r}   r~   r{   r   rL   c              
   K   s^   |}	|  |}| jf |||||||d|\}}
|	| }|}	| |}| |}|	| }|S )N)rJ   r|   rH   ru   r}   r~   r{   )r   r   r   r   )r.   rJ   r|   rH   ru   r}   r~   r{   r   Zresidualr   r1   r1   r2   r5     s&    




zDiffLlamaDecoderLayer.forward)NNNFNN)r6   r7   r8   r    r   r%   r   r?   r   r   r   r   r   r   r   r   r5   r9   r1   r1   r/   r2   r     s&   
      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   ru   F)rJ   
attentionsc                    sj   t  | t|trf|jjd| jj |j	jd| jj |j
jd| jj |jjd| jj d S )Nr   )r$   _init_weightsr   rX   rl   dataZnormal_r&   rk   rm   rn   ro   )r.   moduler/   r1   r2   r   $  s    
z&DiffLlamaPreTrainedModel._init_weights)r6   r7   r8   r    __annotations__base_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_skip_keys_device_placementZ_supports_flash_attnZ_supports_sdpaZ_supports_flex_attnZ_can_compile_fullgraphZ_supports_attention_backendr   rX   Z_can_record_outputsr   r9   r1   r1   r/   r2   r     s   
r   c                       sD   e Zd ZU ejed< ded fddZe e	dd Z
  ZS )	DiffLlamaRotaryEmbeddinginv_freqNr&   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   rb   Zmax_seq_len_cachedZoriginal_max_seq_lenr&   r   Zrope_init_fnattention_scalingZregister_bufferr   Zoriginal_inv_freq)r.   r&   r   r   r/   r1   r2   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rl|jjdkrl|jjnd}t	j
|ddV | |  dd}t	j||fdd	}| | j }| | j }	W d    n1 s0    Y  |j|jd
|	j|jd
fS )Nr   r:   r   r   r   F)r   Zenabledr;   r<   )r   )r   floatrM   r>   r   r   r   r   strr?   Zautocastr   r@   rF   r   rG   r   )
r.   r4   rH   Zinv_freq_expandedZposition_ids_expandedr   ZfreqsZembrF   rG   r1   r1   r2   r5   A  s    0&,z DiffLlamaRotaryEmbedding.forward)N)r6   r7   r8   r?   r   r   r    r%   Zno_gradr   r5   r9   r1   r1   r/   r2   r   -  s
   

r   c                       st   e Zd Zed fddZeedeej	 eej
 eej	 ee eej eej	 ee ee ed	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 r1   )r   ).0rV   r   r1   r2   
<listcomp>Z      z+DiffLlamaModel.__init__.<locals>.<listcomp>r   r   F)r$   r%   Zpad_token_idZpadding_idx
vocab_sizer   Z	Embeddingr'   embed_tokensZ
ModuleListrangenum_hidden_layerslayersr   rq   normr   r   Zgradient_checkpointing	post_initr-   r/   r   r2   r%   S  s    zDiffLlamaModel.__init__N)		input_idsr|   rH   ru   inputs_embedsr~   r}   r   rL   c              	   K   s   |d u |d uA rt d|d u r*| |}|rB|d u rBt| jd}|d u rz|d urZ| nd}	tj|	|	|jd  |jd}|d u r|	d}t
| j|||||d}
|}| ||}| jd | jj D ] }||f|
||||d|}q| |}t||dS )	Nz:You must specify exactly one of input_ids or inputs_embedsr   r   r   )r   )r&   Zinput_embedsr|   r~   ru   rH   )r|   rH   ru   r~   r{   )last_hidden_stateru   )r   r   r   r&   Zget_seq_lengthr?   Zaranger>   r   rC   r   r   r   r   r   r   )r.   r   r|   rH   ru   r   r~   r}   r   Zpast_seen_tokensr   rJ   r{   Zdecoder_layerr1   r1   r2   r5   c  sP    

	

zDiffLlamaModel.forward)NNNNNNN)r6   r7   r8   r    r%   r   r   r   r?   r   r   r   FloatTensorr   r   r   r   r5   r9   r1   r1   r/   r2   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e	e
j e	e
j e	e
j e	e e	e
j e	e
j e	e e	e
j eee
jf ee ed
ddZ  ZS )DiffLlamaForCausalLMzlm_head.weightlm_headZcolwise_reprJ   logitsc                    s@   t  | t|| _|j| _tj|j|jdd| _| 	  d S r"   )
r$   r%   r   r   r   r   r(   r'   r   r   r-   r/   r1   r2   r%     s
    
zDiffLlamaForCausalLM.__init__Nr   )r   r|   rH   ru   r   labelsr}   r~   logits_to_keepr   rL   c
              
   K   s   | j f |||||||d|
}|j}t|	tr<t|	 dn|	}| |dd|ddf }d}|dur| jf ||| 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|   rH   ru   r   r}   r~   N)r   r   r   )lossr   ru   rJ   r   )r   r   r   r   slicer   Zloss_functionr&   r   r   ru   rJ   r   )r.   r   r|   rH   ru   r   r   r}   r~   r   r   outputsrJ   Zslice_indicesr   r   r1   r1   r2   r5     s0     zDiffLlamaForCausalLM.forward)	NNNNNNNNr   )r6   r7   r8   Z_tied_weights_keysZ_tp_planZ_pp_planr%   r   r   r   r?   r   r   r   r   r   r   r   r   r   r   r5   r9   r1   r1   r/   r2   r     s8   	         r   c                   @   s   e Zd ZdS )"DiffLlamaForSequenceClassificationNr6   r7   r8   r1   r1   r1   r2   r     s   r   c                   @   s   e Zd ZdZdS )DiffLlamaForQuestionAnsweringZtransformerN)r6   r7   r8   r   r1   r1   r1   r2   r     s   r   c                   @   s   e Zd ZdS )DiffLlamaForTokenClassificationNr   r1   r1   r1   r2   r     s   r   )r   r   r   r   r   r   )Nr   )HrT   typingr   r   r?   r   Zactivationsr   Zcache_utilsr   r   r	   Z
generationr
   Zintegrationsr   Zmasking_utilsr   Zmodeling_flash_attention_utilsr   r   Zmodeling_layersr   r   r   r   Zmodeling_outputsr   r   Zmodeling_rope_utilsr   r   Zmodeling_utilsr   Zprocessing_utilsr   utilsr   r   r   r   Zutils.deprecationr   Zutils.genericr   Zconfiguration_diffllamar    Z
get_loggerr6   r\   Moduler!   rB   rI   r   r   rS   rW   rX   r   r   r   r   r   r   r   r   r   r   r   r   __all__r1   r1   r1   r2   <module>   s\   

e U.$NK