o
    Zh                     @   s  d dl Z d dlmZ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mZ ddlmZ ddlmZmZmZ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*m+Z+ ddl,m-Z- e* rd dl.m/Z/ ddl0m1Z1 e+2e3Z4G dd dej5Z6dd Z7dAddZ8dej9de:dej9fddZ;d d! Z<G d"d# d#ej5Z=G d$d% d%e=Z>G d&d' d'e=Z?ed(G d)d* d*ej5Z@e=e>e?d+ZAG d,d- d-eZBe(G d.d/ d/e#ZCG d0d1 d1ej5ZDe(G d2d3 d3eCZEG d4d5 d5ee'ZFe(G d6d7 d7eCeZGe(d8d9G d:d; d;eCZHe(G d<d= d=eCZIe(G d>d? d?eCZJg d@ZKdS )B    N)OptionalTupleUnion)nn   )ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)use_kernel_forward_from_hub)AttentionMaskConverter)FlashAttentionKwargs_flash_attention_forward!flash_attn_supports_top_left_mask)GradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPastQuestionAnsweringModelOutput SequenceClassifierOutputWithPastTokenClassifierOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)PreTrainedModel)Unpack)
LossKwargsauto_docstringcan_return_tupleis_torch_flex_attn_availablelogging   )DiffLlamaConfig)	BlockMask)make_flex_block_causal_maskc                       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_sizeZintermediate_sizer   Linear	gate_projup_proj	down_projr   Z
hidden_actact_fnselfr*   	__class__ _/var/www/auris/lib/python3.10/site-packages/transformers/models/diffllama/modeling_diffllama.pyr)   A   s   
zDiffLlamaMLP.__init__c                 C   s$   |  | | || | }|S N)r/   r0   r-   r.   )r2   xr/   r5   r5   r6   forwardK   s    zDiffLlamaMLP.forward)__name__
__module____qualname__r)   r9   __classcell__r5   r5   r3   r6   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..N   dim)shapetorchcat)r8   x1Zx2r5   r5   r6   rotate_halfP   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_idsZunsqueeze_dimZq_embedZk_embedr5   r5   r6   apply_rotary_pos_embW   s
   

rM   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)rB   expandreshape)rN   rO   batchnum_key_value_headsslenhead_dimr5   r5   r6   	repeat_kvr   s
   0rW   c                 C   s   ddt d|    S )Ng?g333333?g333333ӿ)mathexp)	layer_idxr5   r5   r6   lambda_init_fn~   s   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	ej	f d
eej	 deej dee d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*   rZ   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.rV   Tr&   r   )sizer?   F)epsZelementwise_affine)'r(   r)   r*   rZ   loggerwarning_oncer4   r:   attention_dropoutr+   Znum_attention_heads	num_headsgetattrrV   rT   num_key_value_groupsmax_position_embeddingsZ
rope_theta	is_causalr   r,   Zattention_biasq_projk_projv_projo_projr[   lambda_init	ParameterrC   normallambda_std_dev	lambda_q1	lambda_k1	lambda_q2	lambda_k2RMSNormrms_norm_eps	groupnormr2   r*   rZ   r3   r5   r6   r)      s4   

zDiffLlamaAttention.__init__FrN   position_embeddingsattention_maskrL   past_key_valueoutput_attentions	use_cachecache_positionrP   c	                 K   sj  |  \}
}}|}| |}| |}| |}||
|| 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}| )|}|s1d }||fS )
Nr    r?   rK   rJ   r|   r@   r>   r   rA   dtype)ptraining)*r]   rg   rh   ri   viewrb   rV   	transposerT   rM   updaterZ   rW   rd   rC   rD   chunkrepeatmatmulrX   sqrtrB   r   
functionalZsoftmaxfloat32tor   dropoutra   r   rY   sumro   rp   rq   rr   rk   ru   
contiguousrR   rj   )r2   rN   rw   rx   rL   ry   rz   r{   r|   kwargsbszZ
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_output2r5   r5   r6   r9      sP   


 &  
zDiffLlamaAttention.forwardr7   NNNFFN)r:   r;   r<   __doc__r!   r   intr)   rC   Tensorr   
LongTensorr   boolr9   r=   r5   r5   r3   r6   r\      s8    &	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ej	 d	eej	 d
ee
 d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 )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 r7   )r(   r)   r   _flash_attn_uses_top_left_mask)r2   argsr   r3   r5   r6   r)      s   z!DiffLlamaFlashAttention2.__init__NFrN   rw   rx   rL   ry   rz   r{   r|   rP   c	                 C   s  t |tr	td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}|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. }| /|}|syd }||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/transformersFr    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}           _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   Zuse_top_left_maskrf   r>   r   )0
isinstancer
   
ValueErrorr]   rg   rh   ri   r   rb   rV   r   rT   r_   r`   
rotary_embrM   r   rZ   r   ra   r   rC   r   Zis_autocast_enabledZget_autocast_gpu_dtypehasattrr*   r   weightr   r   r   r   rc   r   rf   rD   rY   r   ro   rp   rq   rr   rk   ru   rR   r   rj   )r2   rN   rw   rx   rL   ry   rz   r{   r|   r   r   r   r   r   r   rJ   rK   r   Zdropout_rateinput_dtypeZtarget_dtypeZvalue_states1Zvalue_states2r   r   r   r   r   r   r   r5   r5   r6   r9      s   












  
z DiffLlamaFlashAttention2.forwardr   )r:   r;   r<   r   r)   rC   r   r   r   r   r   r   r9   r=   r5   r5   r3   r6   r      s8    	
r   c                       s   e Zd ZdZ						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
deej deejeej eeej  f f fddZ  Z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.
    NFrN   rw   rx   rL   ry   rz   r{   r|   rP   c	              
      s  |rt d t j||||||||dS | \}
}}| |}| |}| |}||
|| j	| j
dd}||
|| j| j
dd}||
|| j| j
dd}|\}}t||||\}}|d urw|||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 r|dkrd
nd}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 )Na  DiffLlamaModel is using DiffLlamaSdpaAttention, 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.rN   rx   rL   ry   rz   r{   r|   rw   r    r?   r}   r@   r>   r~   cudaTFr   )Z	attn_maskZ	dropout_prf   r   )+r_   r`   r(   r9   r]   rg   rh   ri   r   rb   rV   r   rT   rM   r   rZ   rW   rd   rC   rD   r   r   rB   devicetyper   r   r   Zscaled_dot_product_attentionr   ra   rY   r   ro   rp   r   r   r   rq   rr   rk   ru   rj   )r2   rN   rw   rx   rL   ry   rz   r{   r|   r   r   r   r   r   r   r   rJ   rK   r   r   rf   r   r   r   r   r   r   r3   r5   r6   r9     sx   


&	  
zDiffLlamaSdpaAttention.forwardr   )r:   r;   r<   r   rC   r   r   r   r   r   r   r9   r=   r5   r5   r3   r6   r     s6    	r   rs   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   rl   rC   Zonesr   variance_epsilon)r2   r+   r^   r3   r5   r6   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   rC   r   powmeanZrsqrtr   r   )r2   rN   r   Zvariancer5   r5   r6   r9     s
   zDiffLlamaRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)tupler   rB   r   r2   r5   r5   r6   
extra_repr  s   zDiffLlamaRMSNorm.extra_repr)r   )r:   r;   r<   r)   r9   r   r=   r5   r5   r3   r6   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ej d	eej	 d
ee
 dee dee deej	 deeejejf  dee deejeeejejf  f fddZ  ZS )DiffLlamaDecoderLayerr*   rZ   c                    sX   t    |j| _t|j ||d| _t|| _t|j|j	d| _
t|j|j	d| _d S )N)r*   rZ   r^   )r(   r)   r+   DIFFLLAMA_ATTENTION_CLASSES_attn_implementation	self_attnr$   mlpr   rt   input_layernormpost_attention_layernormrv   r3   r5   r6   r)     s   

zDiffLlamaDecoderLayer.__init__NFrN   rx   rL   ry   rz   r{   r|   rw   r   rP   c	                 K   st   |}
|  |}| jd||||||||d|	\}}|
| }|}
| |}| |}|
| }|f}|r8||f7 }|S )Nr   r5   )r   r   r   r   )r2   rN   rx   rL   ry   rz   r{   r|   rw   r   ZresidualZself_attn_weightsoutputsr5   r5   r6   r9     s.   
	



zDiffLlamaDecoderLayer.forward)NNNFFNN)r:   r;   r<   r!   r   r)   rC   r   r   r   r   r   r   r   r   FloatTensorr9   r=   r5   r5   r3   r6   r     s<    	
r   c                   @   sH   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ZdZdd ZdS )	DiffLlamaPreTrainedModel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j
rC|jjjd|d |jd urA|jj|j 	  d S d S t|trQ|jjd d S t|tr|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   stdg      ?r   )r*   Zinitializer_ranger   r   r,   r   dataZnormal_r'   Zzero_	Embeddingpadding_idxr   Zfill_r\   ro   rn   rp   rq   rr   )r2   moduler   r5   r5   r6   _init_weightsI  s&   



z&DiffLlamaPreTrainedModel._init_weightsN)r:   r;   r<   r!   Zconfig_classbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_skip_keys_device_placementZ_supports_flash_attn_2Z_supports_sdpaZ_supports_flex_attnZ_supports_cache_classZ_supports_quantized_cacheZ_supports_static_cacheZ_supports_attention_backendr   r5   r5   r5   r6   r   :  s    r   c                       s8   e Zd Zddef fddZe edd Z  Z	S )DiffLlamaRotaryEmbeddingNr*   c                    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_typer   defaultinv_freqF)
persistent)r(   r)   r   r   getr   re   Zmax_seq_len_cachedZoriginal_max_seq_lenr*   r   Zrope_init_fnattention_scalingZregister_bufferr   Zoriginal_inv_freq)r2   r*   r   r   r3   r5   r6   r)   ]  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    ZmpscpuF)device_typeenabledr?   r@   )r   )r   floatrQ   rB   r   r   r   r   strrC   Zautocastr   rD   rJ   r   rK   r   )
r2   r8   rL   Zinv_freq_expandedZposition_ids_expandedr   ZfreqsZembrJ   rK   r5   r5   r6   r9   n  s   0&z DiffLlamaRotaryEmbedding.forwardr7   )
r:   r;   r<   r!   r)   rC   Zno_gradr   r9   r=   r5   r5   r3   r6   r   \  s
    r   c                       s  e Zd Zdef fddZdd Z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 de	e de	e de	e
j dee defddZ	d"d
ee
jdf 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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 r5   )r   ).0rZ   r*   r5   r6   
<listcomp>  s    z+DiffLlamaModel.__init__.<locals>.<listcomp>r   r   F)r(   r)   pad_token_idr   
vocab_sizer   r   r+   embed_tokensZ
ModuleListrangenum_hidden_layerslayersr   rt   normr   r   gradient_checkpointing	post_initr1   r3   r   r6   r)     s   zDiffLlamaModel.__init__c                 C      | j S r7   r   r   r5   r5   r6   get_input_embeddings     z#DiffLlamaModel.get_input_embeddingsc                 C   
   || _ d S r7   r   r2   valuer5   r5   r6   set_input_embeddings     
z#DiffLlamaModel.set_input_embeddingsN	input_idsrx   rL   r   inputs_embedsr{   rz   output_hidden_statesr|   flash_attn_kwargsrP   c
                 K   s  |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r9| jr9|r9td d}t	|t
d tfsFtd|d u rO| |}|rX|d u rXt }|	d u rt|d urd| nd}tj|||jd  |jd}	|d u r}|	d}| |||	||}|}| ||}|rdnd }|rdnd }| jd | j j D ]&}|r||f7 }||f||||||	|d	|
}|d }|r||d f7 }q| |}|r||f7 }t||r|nd ||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`.FzBThe `past_key_values` should be either a `Cache` object or `None`.r   r    r   r5   )rx   rL   ry   rz   r{   r|   rw   )last_hidden_stater   rN   
attentions)r*   rz   r   r{   r   r   r   r_   r`   r   r   r   r   r	   get_seq_lengthrC   arangerB   r   rG   _update_causal_maskr   r   r   r   r   )r2   r   rx   rL   r   r   r{   rz   r   r|   r   past_seen_tokensr   rN   rw   Zall_hidden_statesZall_self_attnsZdecoder_layerZlayer_outputsr5   r5   r6   r9     sx   



	


zDiffLlamaModel.forwardFr"   input_tensorc                 C   s:  | j jdkr|d ur|dk r|S d S | j jdkr&t|tjr$t|}|S |d ur.| nd}|d ur7|jnd}| j jdkrO|sO|sOt	j
|||| jdrOd S |j}|jd }	|r^| }
nt|tjri|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   Zflex_attentionr   Fr   )r   Zpast_key_values_lengthZis_trainingr    r>   )sequence_lengthtarget_lengthr   r|   
batch_size)r   ZxpuZnpu)r*   r   anyr   rC   r   r#   r  Zis_compileabler   Z_ignore_causal_mask_sdpar   r   rB   Zget_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr   r   finfominZ_unmask_unattended)r2   rx   r  r|   r   rz   r  Zusing_compilable_cacher   r  r  r   	min_dtyper5   r5   r6   r    sT   




z"DiffLlamaModel._update_causal_maskr  r  r   r  c                 K   sD  | dur|   dkr| }|S t|j}tj||f|||jd}|dkr+tj|dd}|tj||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 |j }
|
dk}
|ddddddd|	f |
||ddddddd|	f< |S )	aM  
        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.
            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_valuer   r   r    )Zdiagonalr   r>   r   )rA   rC   r  r  fullr   Ztriur  rR   rQ   clonerB   r   Zmasked_fill)rx   r  r  r   r|   r  r   r   r  Zmask_lengthZpadding_maskr5   r5   r6   r
  :  s,    $
6  zDDiffLlamaModel._prepare_4d_causal_attention_mask_with_cache_position	NNNNNNNNN)F)r:   r;   r<   r!   r)   r   r   r   r   r   rC   r   r   r   r   r   r   r   r   r9   r   r  staticmethodr   r   r
  r=   r5   r5   r3   r6   r   ~  s    	
d
Dr   c                   @   s   e Zd ZdS )KwargsForCausalLMN)r:   r;   r<   r5   r5   r5   r6   r  r  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dd	 Zd
d Zdd Z	dd Z
dd Z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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_headZcolwise_reprN   logitsc                    s@   t  | t|| _|j| _tj|j|jdd| _| 	  d S r%   )
r(   r)   r   r   r   r   r,   r+   r  r   r1   r3   r5   r6   r)   {  s
   
zDiffLlamaForCausalLM.__init__c                 C      | j jS r7   r   r   r   r5   r5   r6   r        z)DiffLlamaForCausalLM.get_input_embeddingsc                 C      || j _d S r7   r  r   r5   r5   r6   r        z)DiffLlamaForCausalLM.set_input_embeddingsc                 C   r   r7   r  r   r5   r5   r6   get_output_embeddings  r   z*DiffLlamaForCausalLM.get_output_embeddingsc                 C   r   r7   r  )r2   Znew_embeddingsr5   r5   r6   set_output_embeddings  r   z*DiffLlamaForCausalLM.set_output_embeddingsc                 C   r   r7   r   )r2   decoderr5   r5   r6   set_decoder  r   z DiffLlamaForCausalLM.set_decoderc                 C   r   r7   r  r   r5   r5   r6   get_decoder  r   z DiffLlamaForCausalLM.get_decoderNr   r   rx   rL   r   r   labelsr{   rz   r   r|   logits_to_keepr   rP   c                 K   s   |dur|n| j j}|	dur|	n| j j}	| jd||||||||	|
d	|}|j}t|tr4t| dn|}| |dd|ddf }d}|durX| j	d||| j j
d|}t|||j|j|jdS )a1  
        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, 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?"
        ```N)	r   rx   rL   r   r   r{   rz   r   r|   )r  r#  r   lossr  r   rN   r   r5   )r*   rz   r   r   r   r   r   slicer  loss_functionr   r   r   rN   r   )r2   r   rx   rL   r   r   r#  r{   rz   r   r|   r$  r   r   rN   Zslice_indicesr  r&  r5   r5   r6   r9     s:   '
zDiffLlamaForCausalLM.forward)NNNNNNNNNNr   )r:   r;   r<   Z_tied_weights_keysZ_tp_planZ_pp_planr)   r   r   r  r  r!  r"  r   r   r   rC   r   r   r   r   r   r   r   r   r  r   r9   r=   r5   r5   r3   r6   r  u  sf    		
r  a  
    The DiffLlama Model transformer with a sequence classification head on top (linear layer).

    [`DiffLlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT-2) do.

    Since it does classification on the last token, it requires to know the position of the last token. If a
    `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
    no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
    padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
    each row of the batch).
    )Zcustom_introc                          e Zd Z fddZdd Z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e defddZ  ZS )"DiffLlamaForSequenceClassificationc                    s@   t  | |j| _t|| _tj|j| jdd| _| 	  d S r%   )
r(   r)   
num_labelsr   r   r   r,   r+   scorer   r1   r3   r5   r6   r)     s
   
z+DiffLlamaForSequenceClassification.__init__c                 C   r  r7   r  r   r5   r5   r6   r     r  z7DiffLlamaForSequenceClassification.get_input_embeddingsc                 C   r  r7   r  r   r5   r5   r6   r     r  z7DiffLlamaForSequenceClassification.set_input_embeddingsNr   rx   rL   r   r   r#  r{   rz   r   rP   c
              
   C   s(  | j ||||||||	d}
|
j}| |}|dur|jd }n|jd }| jjdu r2|dkr2td| jjdu r;d}n1|dur`|| jjk|jt	j
}t	j|jd |jt	j
d}|| d}nd}t| jj d |t	j||jd	|f }d}|dur| j|||| jd
}t|||
j|
j|
jdS )  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        rx   rL   r   r   r{   rz   r   Nr   r    z=Cannot handle batch sizes > 1 if no padding token is defined.r>   )r   r   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`r   )r  r#  pooled_logitsr*   r%  )r   r   r,  rB   r*   r   r   r   r   rC   Zint32r  Zargmaxr_   r`   r4   r:   r(  r   r   rN   r   )r2   r   rx   rL   r   r   r#  r{   rz   r   Ztransformer_outputsrN   r  r  Zlast_non_pad_tokenZnon_pad_maskZtoken_indicesr/  r&  r5   r5   r6   r9      sL   


z*DiffLlamaForSequenceClassification.forwardr  )r:   r;   r<   r)   r   r   r   r   r   rC   r   r   r   r   r   r   r9   r=   r5   r5   r3   r6   r*    sH    		
r*  c                       s   e Zd ZdZ fddZdd Z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
j de	e de	e defddZ  ZS )DiffLlamaForQuestionAnsweringtransformerc                    s2   t  | t|| _t|jd| _|   d S )Nr?   )	r(   r)   r   r1  r   r,   r+   
qa_outputsr   r1   r3   r5   r6   r)   J  s   
z&DiffLlamaForQuestionAnswering.__init__c                 C   r  r7   r1  r   r   r5   r5   r6   r   R  r  z2DiffLlamaForQuestionAnswering.get_input_embeddingsc                 C   r  r7   r3  r   r5   r5   r6   r   U  r  z2DiffLlamaForQuestionAnswering.set_input_embeddingsNr   rx   rL   r   r   start_positionsend_positionsrz   r   rP   c
              	   K   s   | j |||||||	d}|j}| |}|jddd\}}|d }|d }d }|d urA|d urA| j||||fi |
}t||||j|j	dS )N)rx   rL   r   r   rz   r   r    r>   r@   )r&  start_logits
end_logitsrN   r   )
r1  r   r2  splitZsqueezer   r(  r   rN   r   )r2   r   rx   rL   r   r   r4  r5  rz   r   r   r   sequence_outputr  r6  r7  r&  r5   r5   r6   r9   X  s0   

z%DiffLlamaForQuestionAnswering.forwardr  )r:   r;   r<   r   r)   r   r   r   r   r   rC   r   r   r   r   r   r   r9   r=   r5   r5   r3   r6   r0  F  sJ    	
r0  c                       r)  )DiffLlamaForTokenClassificationc                    s|   t  | |j| _t|| _t|dd d ur|j}nt|dd d ur'|j}nd}t	|| _
t|j|j| _|   d S )Nclassifier_dropouthidden_dropoutg?)r(   r)   r+  r   r   rc   r;  r<  r   ZDropoutr   r,   r+   r,  r   )r2   r*   r;  r3   r5   r6   r)     s   
z(DiffLlamaForTokenClassification.__init__c                 C   r  r7   r  r   r5   r5   r6   r     r  z4DiffLlamaForTokenClassification.get_input_embeddingsc                 C   r  r7   r  r   r5   r5   r6   r     r  z4DiffLlamaForTokenClassification.set_input_embeddingsNr   rx   rL   r   r   r#  r{   rz   r   rP   c
              
   C   sd   | j ||||||||	d}
|
j}| |}| |}d}|dur(| ||| j}t|||
j|
jdS )r-  r.  N)r&  r  rN   r   )	r   r   r   r,  r(  r*   r   rN   r   )r2   r   rx   rL   r   r   r#  r{   rz   r   r   r9  r  r&  r5   r5   r6   r9     s,   


z'DiffLlamaForTokenClassification.forwardr  )r:   r;   r<   r)   r   r   r   r   r   rC   r   r   r   r   r   r   r9   r=   r5   r5   r3   r6   r:    sH    	
r:  )r   r   r  r*  r0  r:  )Nr    )LrX   typingr   r   r   rC   r   Zactivationsr   Zcache_utilsr   r	   r
   Z
generationr   Zintegrationsr   Zmodeling_attn_mask_utilsr   Zmodeling_flash_attention_utilsr   r   r   Zmodeling_layersr   Zmodeling_outputsr   r   r   r   r   Zmodeling_rope_utilsr   r   Zmodeling_utilsr   Zprocessing_utilsr   utilsr   r   r   r   r   Zconfiguration_diffllamar!   Z!torch.nn.attention.flex_attentionr"   Zintegrations.flex_attentionr#   Z
get_loggerr:   r_   Moduler$   rF   rM   r   r   rW   r[   r\   r   r   r   r   r   r   r   r   r  r  r*  r0  r:  __all__r5   r5   r5   r6   <module>   sn   

j g5!" tlV>F