o
    h                  	   @   s  d Z ddlZddlZddlmZmZmZmZ ddlZddl	m
  mZ ddl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mZmZ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&m'Z'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/ e( rddl0m1Z1m2Z2 ddl3m4Z4m5Z5m6Z6 e- re$sddl7Zej89eZe*:e;Z<dZ=dd Z>dHdej?dej@deeA fddZB	dIdejCdej@dejDdeAfddZEG d d! d!e
jFZGe#HeG G d"d# d#e
jFZIG d$d% d%eIZJG d&d' d'eIZKd(d) ZLdJd*d+ZMG d,d- d-e
jFZNd.ej?d/eAd0ej?fd1d2ZOG d3d4 d4e
jFZPG d5d6 d6ePZQG d7d8 d8ePZRePeQeRd9ZSG d:d; d;e
jFZTd<ZUe&d=eUG d>d? d?e!ZVd@ZWe&d=eUG dAdB dBeVZXG dCdD dDeVZYe&dEeUG dFdG dGeVZZdS )Kz PyTorch LLaMA model.    N)ListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)CacheDynamicCache)AttentionMaskConverter_prepare_4d_attention_mask!_prepare_4d_causal_attention_mask*_prepare_4d_causal_attention_mask_for_sdpa)BaseModelOutputWithPastCausalLMOutputWithPast SequenceClassifierOutputWithPast)PreTrainedModel)ALL_LAYERNORM_LAYERS#is_torch_greater_or_equal_than_1_13)add_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_2_available#is_flash_attn_greater_or_equal_2_10loggingreplace_return_docstrings)is_torch_fx_available   )LlamaConfig)flash_attn_funcflash_attn_varlen_func)index_first_axis	pad_inputunpad_inputr    c                 C   sX   | j dtjd}tj|  dd }|  }ttj	|dtjjdd}|||fS )NdimdtypeF)as_tupler   )r   r   )
sumtorchint32nonzeroflattenmaxitemFpadcumsum)attention_maskseqlens_in_batchindicesmax_seqlen_in_batch
cu_seqlens r:   ^/var/www/html/ai/venv/lib/python3.10/site-packages/transformers/models/llama/modeling_llama.py_get_unpad_dataI   s   r<   maskr)   tgt_lenc                 C   s   t d t| ||dS )NzCalling `transformers.models.llama.modeling_llama._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_maskr=   r)   r>   )warningswarnr   r?   r:   r:   r;   _expand_maskU   s   rB   input_ids_shapedevicepast_key_values_lengthc                 C   s   t d tj| |||dS )NzCalling `transformers.models.llama.modeling_llama._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.llama.modeling_llama.AttentionMaskConverter._make_causal_maskrC   r)   rD   rE   )r@   rA   r   _make_causal_maskrF   r:   r:   r;   rG   \   s   rG   c                       s&   e Zd Zd fdd	Zdd Z  ZS )LlamaRMSNormư>c                    s&   t    tt|| _|| _dS )z;
        LlamaRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parameterr,   onesweightvariance_epsilon)selfhidden_sizeeps	__class__r:   r;   rK   h   s   

zLlamaRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )N   r&   T)keepdim)	r)   tor,   float32powmeanrsqrtrO   rN   )rP   hidden_statesinput_dtypevariancer:   r:   r;   forwardp   s
   zLlamaRMSNorm.forward)rI   __name__
__module____qualname__rK   r_   __classcell__r:   r:   rS   r;   rH   g   s    rH   c                       s0   e Zd Zd
 fdd	Zdd Zddd	Z  ZS )LlamaRotaryEmbedding   '  Nc                    sr   t    || _|| _|| _d| jtd| jd || j   }| j	d|dd | j
|| jjt d d S )N      ?r   rU   inv_freqF
persistentseq_lenrD   r)   )rJ   rK   r(   max_position_embeddingsbaser,   arangefloatrW   register_buffer_set_cos_sin_cacheri   rD   get_default_dtype)rP   r(   rn   ro   rD   ri   rS   r:   r;   rK   |   s   
*
zLlamaRotaryEmbedding.__init__c                 C   st   || _ tj| j || jjd}t|| j}tj||fdd}| jd| 	|dd | jd|
 	|dd d S NrD   r)   r&   r(   
cos_cachedFrj   
sin_cached)max_seq_len_cachedr,   rp   ri   r)   outercatrr   cosrW   sinrP   rm   rD   r)   tfreqsembr:   r:   r;   rs      s   z'LlamaRotaryEmbedding._set_cos_sin_cachec                 C   sN   || j kr| j||j|jd | jd | j|jd| jd | j|jdfS )Nrl   )r)   )rz   rs   rD   r)   rx   rW   ry   )rP   xrm   r:   r:   r;   r_      s
   
zLlamaRotaryEmbedding.forward)rf   rg   NN)ra   rb   rc   rK   rs   r_   rd   r:   r:   rS   r;   re   {   s    
re   c                       *   e Zd ZdZd
 fdd	Zdd	 Z  ZS )!LlamaLinearScalingRotaryEmbeddingz[LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendevrf   rg   Nrh   c                       || _ t |||| d S r   scaling_factorrJ   rK   rP   r(   rn   ro   rD   r   rS   r:   r;   rK         z*LlamaLinearScalingRotaryEmbedding.__init__c                 C   s~   || _ tj| j || jjd}|| j }t|| j}tj||fdd}| jd|	 
|dd | jd| 
|dd d S ru   )rz   r,   rp   ri   r)   r   r{   r|   rr   r}   rW   r~   r   r:   r:   r;   rs      s   
z4LlamaLinearScalingRotaryEmbedding._set_cos_sin_cacherf   rg   Nrh   ra   rb   rc   __doc__rK   rs   rd   r:   r:   rS   r;   r          r   c                       r   )%LlamaDynamicNTKScalingRotaryEmbeddingzmLlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozillarf   rg   Nrh   c                    r   r   r   r   rS   r:   r;   rK      r   z.LlamaDynamicNTKScalingRotaryEmbedding.__init__c           	      C   s   || _ || jkr<| j| j| | j | jd  | j| jd    }d|td| jd || j   }| j	d|dd tj| j || j
jd}t|| j
}tj||fd	d
}| j	d| |dd | j	d| |dd d S )Nr   rU   rh   r   ri   Frj   rv   r&   rw   rx   ry   )rz   rn   ro   r   r(   r,   rp   rq   rW   rr   ri   r)   r{   r|   r}   r~   )	rP   rm   rD   r)   ro   ri   r   r   r   r:   r:   r;   rs      s   
(z8LlamaDynamicNTKScalingRotaryEmbedding._set_cos_sin_cacher   r   r:   r:   rS   r;   r      r   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..Nr&   rU   rw   )shaper,   r|   )r   x1x2r:   r:   r;   rotate_half   s   r   c                 C   sL   ||  |}||  |}| | t| |  }|| t||  }||fS )an  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`):
            The position indices of the tokens corresponding to the query and key tensors. For example, this can be
            used to pass offsetted position ids when working with a KV-cache.
        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kr}   r~   position_idsunsqueeze_dimq_embedk_embedr:   r:   r;   apply_rotary_pos_emb   s
   r   c                       s$   e Zd Z fddZdd Z  ZS )LlamaMLPc                    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)rJ   rK   configrQ   intermediate_sizer   Linear	gate_projup_proj	down_projr   
hidden_actact_fnrP   r   rS   r:   r;   rK      s   
zLlamaMLP.__init__c                    s   | j jdkrn| j| j j }| jjj|dd| jjj|dd| jjj|dd tj	fddt
| j jD dd}tj	fddt
| j jD dd}| || j|dd fd	dt
| j jD }t|}|S | | | |  }|S )
Nr   r   rw   c                       g | ]
}t  | qS r:   r2   linear.0i)gate_proj_slicesr   r:   r;   
<listcomp>      z$LlamaMLP.forward.<locals>.<listcomp>r&   c                    r   r:   r   r   )up_proj_slicesr   r:   r;   r     r   rU   c                    s    g | ]}t |  | qS r:   r   r   )down_proj_slicesintermediate_statesr:   r;   r     s    )r   pretraining_tpr   r   rN   splitr   r   r,   r|   ranger   r+   )rP   r   slicer   r   r   r:   )r   r   r   r   r   r;   r_      s"   &
 zLlamaMLP.forwardr`   r:   r:   rS   r;   r      s    
r   r\   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)r\   r   batchnum_key_value_headsslenhead_dimr:   r:   r;   	repeat_kv  s
   0r   c                       s   e Zd ZdZddedee f fddZdd Zd	e	j
d
edefddZ					dde	j
dee	j
 dee	j dee dededee	j
ee	j
 eee	j
  f fddZ  ZS )LlamaAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNr   	layer_idxc                    s6  t    || _|| _|d u rtd| jj d |j| _|j	| _	|j
| _| j	| j | _|j| _| j| j | _|j| _|j| _d| _| j| j | j	krYtd| j	 d| j dtj| j	| j| j |jd| _tj| j	| j| j |jd| _tj| j	| j| j |jd| _tj| j| j | j	|jd| _|   d S )NzInstantiating z without passing `layer_idx` is not recommended and will to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` when creating this class.Tz?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).r   )rJ   rK   r   r   loggerwarning_oncerT   ra   attention_dropoutrQ   num_attention_heads	num_headsr   r   num_key_value_groupsrn   
rope_theta	is_causal
ValueErrorr   r   attention_biasq_projk_projv_projo_proj
_init_roperP   r   r   rS   r:   r;   rK      s6   

zLlamaAttention.__init__c                 C   s   | j jd u rt| j| j| jd| _d S | j jd }| j jd }|dkr1t| j| j|| jd| _d S |dkrCt| j| j|| jd| _d S t	d| )N)rn   ro   typefactorr   )rn   r   ro   dynamiczUnknown RoPE scaling type )
r   rope_scalingre   r   rn   r   
rotary_embr   r   r   )rP   scaling_typer   r:   r:   r;   r   A  s.   zLlamaAttention._init_ropetensorrm   bszc                 C   s    | ||| j| jdd S )Nr   rU   )viewr   r   	transpose
contiguous)rP   r   rm   r   r:   r:   r;   _shape\  s    zLlamaAttention._shapeFr\   r5   r   past_key_valueoutput_attentions	use_cacher   c                    s  d|v r	t d  \}}	}
| jjdkr| j| j | jj }| jjj	| j
| j | jj dd| jjj	|dd| jjj	|ddfddt| jjD }tj|dd}fd	dt| jjD }tj|dd}fd
dt| jjD }tj|dd}n| }| }| }|||	| j
| jdd}|||	| j| jdd}|||	| j| jdd}|jd }|d ur| jd u rtd| jj d|||| j7 }| j||d\}}t|||||\}}|d ur||d}|||| j|\}}t|| j}t|| j}t||ddt| j }| || j
|	|fkr>td|| j
|	|f d|  |d urb| |d|	|fkr^td|d|	|f d|  || }t j!j"|dtj#d$|j%}t j!j&|| j'| j(d}t||   || j
|	| jfkrtd|| j
|	| jf d    dd)   *||	| j+ | jjdkr j	| j+| jj dd | j,jj	| j+| jj ddt- fddt| jjD  n| ,  |sd } ||fS )Npadding_maskrPassing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`r   r   rw   c                       g | ]
}t  | qS r:   r   r   )r\   query_slicesr:   r;   r   x  r   z*LlamaAttention.forward.<locals>.<listcomp>r&   c                    r   r:   r   r   )r\   
key_slicesr:   r;   r   {  r   c                    r   r:   r   r   )r\   value_slicesr:   r;   r   ~  r   rU   zFThe cache structure has changed since version v4.36. If you are using zv for auto-regressive decoding with k/v caching, please make sure to initialize the attention class with a layer index.rm   r~   r}   r
   z$Attention weights should be of size 	, but is !Attention mask should be of size r'   )ptrainingz `attn_output` should be of size c                    s    g | ]}t  | | qS r:   r   r   )attn_outputo_proj_slicesr:   r;   r     s     ).r@   rA   sizer   r   r   r   r   rN   r   r   r   r   r   r,   r|   r   r   r   r   r   rT   ra   get_usable_lengthr   r   updater   r   matmulmathsqrtr   
functionalsoftmaxrX   rW   r)   dropoutr   r   r   r   rQ   r   r+   )rP   r\   r5   r   r   r   r   kwargsr   q_len_key_value_slicingquery_states
key_statesvalue_states
kv_seq_lenr}   r~   cache_kwargsattn_weightsr:   )r   r\   r   r   r   r   r;   r_   _  s   







 
"

zLlamaAttention.forwardr   NNNFF)ra   rb   rc   r   r    r   intrK   r   r,   Tensorr   
LongTensorr   boolr   r_   rd   r:   r:   rS   r;   r     s2    !	r   c                       s   e Zd ZdZ fddZ					ddejdeej deej d	ee	 d
e
de
deejeej eeej  f fddZ	dddZdd Z  ZS )LlamaFlashAttention2aF  
    Llama flash attention module. This module inherits from `LlamaAttention` 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 r   )rJ   rK   r   _flash_attn_uses_top_left_mask)rP   argsr   rS   r:   r;   rK     s   zLlamaFlashAttention2.__init__NFr\   r5   r   r   r   r   r   c                 K   s  d|v rt d |d}d}| \}}	}
| |}| |}| |}|||	| j| j	
dd}|||	| j| j	
dd}|||	| j| j	
dd}|jd }|d urb|||| j7 }| j||d\}}t|||||\}}|d ur||d}|||| j|\}}|
dd}|
dd}|
dd}| jr| jnd	}|j}|tjkrt| jd
r| jj}n| jjj}td| d ||}||}||}| j|||||	|d}|||	| j ! }| "|}|sd }|||fS )Nr   r   Fr   rU   r   r   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   )#r@   rA   popr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r)   r,   rX   hasattrr   r  rN   r   r   rW   _flash_attention_forwardr   rQ   r   r   )rP   r\   r5   r   r   r   r   r   r   r   r   r   r  r  r  r}   r~   r  dropout_rater]   target_dtyper   r  r:   r:   r;   r_     s\   













zLlamaFlashAttention2.forwardr  c                 C   s   | j s| j}n| jo|dk}|durE|jd }	| |||||\}}}}
}}|\}}|\}}t||||||||||d
}t||
|	|}|S t||||||d}|S )a  
        Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
        first unpad the input, then computes the attention scores and pad the final attention scores.

        Args:
            query_states (`torch.Tensor`):
                Input query states to be passed to Flash Attention API
            key_states (`torch.Tensor`):
                Input key states to be passed to Flash Attention API
            value_states (`torch.Tensor`):
                Input value states to be passed to Flash Attention API
            attention_mask (`torch.Tensor`):
                The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
                position of padding tokens and 1 for the position of non-padding tokens.
            dropout (`int`, *optional*):
                Attention dropout
            softmax_scale (`float`, *optional*):
                The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
        r   Nr   )cu_seqlens_qcu_seqlens_kmax_seqlen_qmax_seqlen_k	dropout_psoftmax_scalecausal)r  r  )r  r   r   _upad_inputr"   r$   r!   )rP   r   r  r  r5   query_lengthr   r  r  
batch_size	indices_qcu_seq_lensmax_seq_lensr  r  max_seqlen_in_batch_qmax_seqlen_in_batch_kattn_output_unpadr   r:   r:   r;   r  0  s8   

z-LlamaFlashAttention2._flash_attention_forwardc                 C   s   t |\}}}|j\}	}
}}t||	|
 |||}t||	|
 |||}||
kr>t||	|
 | j||}|}|}|}n2|dkr\d}tj|	d tj|jd}|d d }|	d}n|d d | d f }t
||\}}}}||||||f||ffS )Nr   r)   rD   r&   )r<   r   r#   r   r   r,   rp   r-   rD   squeezer%   )rP   query_layer	key_layervalue_layerr5   r  	indices_kr  r$  r  r  r   r   r  r#  r   r:   r:   r;   r  k  s>   z LlamaFlashAttention2._upad_inputr  )r  N)ra   rb   rc   r   rK   r,   r  r   r	  r   r
  r   r_   r  r  rd   r:   r:   rS   r;   r    s4    	
Z
;r  c                       sx   e Zd ZdZ					ddejdeej deej dee de	d	e	d
e
ejeej ee
ej  f f fddZ  ZS )LlamaSdpaAttentionz
    Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    NFr\   r5   r   r   r   r   r   c                    s  |rt d t j||||||dS | \}}}	| |}
| |}| |}|
||| j	| j
dd}
|||| j| j
dd}|||| j| j
dd}|jd }|d ure|||| j7 }| j||d\}}t|
||||\}
}|d ur||d}|||| j|\}}t|| j}t|| j}|d ur| |d||fkrtd|d||f d	|  tjjj|
|||| jr| jnd
| jo|d u o|dkd}|dd }|||| j}|  |}|d |fS )Na  LlamaModel is using LlamaSdpaAttention, 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.r\   r5   r   r   r   r   r   rU   r   r   r   r   r   r  )	attn_maskr  r   )!r   r   rJ   r_   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r,   r   r   scaled_dot_product_attentionr   r   r   r   r   rQ   r   )rP   r\   r5   r   r   r   r   r   r   r   r   r  r  r  r}   r~   r  r   rS   r:   r;   r_     s\   		







zLlamaSdpaAttention.forwardr  )ra   rb   rc   r   r,   r  r   r	  r   r
  r   r_   rd   r:   r:   rS   r;   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
ej  dee dee de
ejee
ejejf  f fddZ  ZS )LlamaDecoderLayerr   r   c                    sX   t    |j| _t|j ||d| _t|| _t|j|j	d| _
t|j|j	d| _d S )N)r   r   rR   )rJ   rK   rQ   LLAMA_ATTENTION_CLASSES_attn_implementation	self_attnr   mlprH   rms_norm_epsinput_layernormpost_attention_layernormr   rS   r:   r;   rK     s   

zLlamaDecoderLayer.__init__NFr\   r5   r   r   r   r   r   c              	   K   s   d|v r	t d |}| |}| jd||||||d|\}}	}
|| }|}| |}| |}|| }|f}|r@||	f7 }|rG||
f7 }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *optional*):
                attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
                query_sequence_length, key_sequence_length)` if default attention is used.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
            past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
        r   r   r-  Nr:   )r@   rA   r:  r7  r;  r8  )rP   r\   r5   r   r   r   r   r   residualself_attn_weightspresent_key_valueoutputsr:   r:   r;   r_     s6   
	



zLlamaDecoderLayer.forwardr  )ra   rb   rc   r    r  rK   r,   r  r   r	  r   r
  FloatTensorr_   rd   r:   r:   rS   r;   r3    s,    	r3  aJ  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`LlamaConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
zSThe bare LLaMA Model outputting raw hidden-states without any specific head on top.c                   @   s6   e Zd ZeZdZdZdgZdZdZ	dZ
dZdd ZdS )LlamaPreTrainedModelmodelTr3  past_key_valuesc                 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
rA|jjjd|d |jd urC|jj|j 	  d S d S d S )Nr  )rZ   std)r   initializer_range
isinstancer   r   rN   datanormal_r   zero_	Embeddingpadding_idx)rP   modulerD  r:   r:   r;   _init_weightsP  s   

z"LlamaPreTrainedModel._init_weightsN)ra   rb   rc   r    config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_cache_classrM  r:   r:   r:   r;   rA  B  s    rA  aD  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
            `past_key_values`).

            If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
            and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
            information on the default strategy.

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.n_positions - 1]`.

            [What are position IDs?](../glossary#position-ids)
        past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
            Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
            returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

            Two formats are allowed:
            - a [`~cache_utils.Cache`] instance;
            - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
            shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
            cache format.

            The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
            legacy cache format will be returned.

            If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
            have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
            of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
c                       s   e Zd ZdZdef fddZdd Zdd Zee																			dd
e
jdee
j dee
j deee
j  dee
j dee dee dee dee deeef fddZ  ZS )
LlamaModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]

    Args:
        config: LlamaConfig
    r   c                    s   t     j| _ j| _t j j| j| _t	 fddt
 jD | _ jdk| _ jdk| _t j jd| _d| _|   d S )Nc                    s   g | ]}t  |qS r:   )r3  )r   r   r   r:   r;   r     s    z'LlamaModel.__init__.<locals>.<listcomp>r2  r1  r4  F)rJ   rK   pad_token_idrK  
vocab_sizer   rJ  rQ   embed_tokens
ModuleListr   num_hidden_layerslayersr6  	_use_sdpa_use_flash_attention_2rH   r9  normgradient_checkpointing	post_initr   rS   rW  r;   rK     s   zLlamaModel.__init__c                 C      | j S r   rZ  rP   r:   r:   r;   get_input_embeddings     zLlamaModel.get_input_embeddingsc                 C   
   || _ d S r   rd  rP   valuer:   r:   r;   set_input_embeddings     
zLlamaModel.set_input_embeddingsN	input_idsr5   r   rC  inputs_embedsr   r   output_hidden_statesreturn_dictr   c
              
   C   s  |d ur|n| j j}|d ur|n| j j}|d ur|n| j j}|	d ur$|	n| j j}	|d ur4|d ur4td|d urB|jd d \}
}n|d urP|jd d \}
}ntdd}|rjt|t }|ret	
|}||}|d u r|d uru|jn|j}tj||| tj|d}|d}|d u r| |}| jr|d urd|v r|nd }n| jr|st||
|f||}n	t||
|f||}|}| jr| jr|rtd d}|rdnd }|rdnd }d }| jD ]@}|r||f7 }| jr| jr| |j||||||}n
|||||||d	}|d }|r||rdnd
 }|r||d
 f7 }q| |}|r*||f7 }d }|r8|r6| n|}|	sHtdd ||||fD S t ||||dS )NzDYou cannot specify both input_ids and inputs_embeds at the same timerU   z5You have to specify either input_ids or inputs_embedsr   r&  zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr:   )r5   r   r   r   r   r   c                 s   s    | ]	}|d ur|V  qd S r   r:   )r   vr:   r:   r;   	<genexpr>@  s    z%LlamaModel.forward.<locals>.<genexpr>)last_hidden_staterC  r\   
attentions)!r   r   ro  r   use_return_dictr   r   rF  r   r   from_legacy_cacher   rD   r,   rp   longr   rZ  r_  r^  r   r   ra  r   r   r   r]  _gradient_checkpointing_func__call__r`  to_legacy_cachetupler   )rP   rm  r5   r   rC  rn  r   r   ro  rp  r  
seq_lengthrE   use_legacy_cacherD   r\   all_hidden_statesall_self_attnsnext_decoder_cachedecoder_layerlayer_outputs
next_cacher:   r:   r;   r_     s   







	

zLlamaModel.forward)	NNNNNNNNN)ra   rb   rc   r   r    rK   rf  rk  r   LLAMA_INPUTS_DOCSTRINGr,   r	  r   r  r   r@  r
  r   r   r   r_   rd   r:   r:   rS   r;   rV    sH    	

rV  c                       s  e Zd Zdg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eeed										d#dejdeej deej deeej  deej deej dee dee dee dee deeef fddZ	d$dd Zed!d" Z  ZS )%LlamaForCausalLMzlm_head.weightc                    s@   t  | t|| _|j| _tj|j|jdd| _| 	  d S r   )
rJ   rK   rV  rB  rY  r   r   rQ   lm_headrb  r   rS   r:   r;   rK   L  s
   
zLlamaForCausalLM.__init__c                 C      | j jS r   rB  rZ  re  r:   r:   r;   rf  U     z%LlamaForCausalLM.get_input_embeddingsc                 C      || j _d S r   r  ri  r:   r:   r;   rk  X     z%LlamaForCausalLM.set_input_embeddingsc                 C   rc  r   r  re  r:   r:   r;   get_output_embeddings[  rg  z&LlamaForCausalLM.get_output_embeddingsc                 C   rh  r   r  )rP   new_embeddingsr:   r:   r;   set_output_embeddings^  rl  z&LlamaForCausalLM.set_output_embeddingsc                 C   rh  r   rB  )rP   decoderr:   r:   r;   set_decodera  rl  zLlamaForCausalLM.set_decoderc                 C   rc  r   r  re  r:   r:   r;   get_decoderd  rg  zLlamaForCausalLM.get_decoder)output_typerN  Nrm  r5   r   rC  rn  labelsr   r   ro  rp  r   c                    sz  |dur|n| j j}|	dur|	n| j j}	|
dur|
n| j j}
| j||||||||	|
d	}|d  | j jdkrZ| jjj| j	| j j dd fddt
| j jD }tj|dd}n|  }| }d}|dur|d	ddddf  }|d	ddf  }t }|d| j j	}|d}||j}|||}|
s|f|dd  }|dur|f| S |S t|||j|j|jd
S )a  
        Args:
            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]`.

        Returns:

        Example:

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

        >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
        >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)

        >>> prompt = "Hey, are you conscious? Can you talk to me?"
        >>> inputs = tokenizer(prompt, return_tensors="pt")

        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
        ```N)	rm  r5   r   rC  rn  r   r   ro  rp  r   r   rw   c                    r   r:   r   r   r\   lm_head_slicesr:   r;   r     r   z,LlamaForCausalLM.forward.<locals>.<listcomp>r&   .losslogitsrC  r\   rt  )r   r   ro  ru  rB  r   r  rN   r   rY  r   r,   r|   rq   r   r   r   rW   rD   r   rC  r\   rt  )rP   rm  r5   r   rC  rn  r  r   r   ro  rp  r?  r  r  shift_logitsshift_labelsloss_fctoutputr:   r  r;   r_   g  sR   (


zLlamaForCausalLM.forwardc                 K   sz  |d urnt |tr| }|j}| }n|d d jd  }}d }|d urA|jd |jd krA|d d |jd |  d f }n||jd k rR|d d |d f }|d urn|d urn||jd  |krn|d d | d f }|dd }	|d ur|	d u r| dd }	|		|dkd |r|	d d |jd  d f }	|d ur|d u rd|i}
nd|i}
|

|	||d|d	 |
S )
Nr   rU   r   r   r&   rn  rm  r   )r   rC  r   r5   )rF  r   get_seq_lengthseen_tokensget_max_lengthr   getrw  r4   masked_fill_r   )rP   rm  rC  r5   rn  r   cache_lengthpast_lengthmax_cache_lengthr   model_inputsr:   r:   r;   prepare_inputs_for_generation  s@   

"
z.LlamaForCausalLM.prepare_inputs_for_generationc                    s.   d}| D ]}|t  fdd|D f7 }q|S )Nr:   c                 3   s$    | ]}| d  |jV  qdS )r   N)index_selectrW   rD   )r   
past_statebeam_idxr:   r;   rr    s   " z2LlamaForCausalLM._reorder_cache.<locals>.<genexpr>)r{  )rC  r  reordered_past
layer_pastr:   r  r;   _reorder_cache  s   zLlamaForCausalLM._reorder_cache
NNNNNNNNNN)NNN)ra   rb   rc   _tied_weights_keysrK   rf  rk  r  r  r  r  r   r  r   r   _CONFIG_FOR_DOCr,   r	  r   r  r   r@  r
  r   r   r_   r  staticmethodr  rd   r:   r:   rS   r;   r  I  s`    	
	

\
8r  a  
    The LLaMa Model transformer with a sequence classification head on top (linear layer).

    [`LlamaForSequenceClassification`] 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).
    c                       s   e Zd Z fddZdd Zdd Zee										ddej	d	e
ej d
e
ej	 de
eej  de
ej de
ej	 de
e de
e de
e de
e deeef fddZ  ZS )LlamaForSequenceClassificationc                    s@   t  | |j| _t|| _tj|j| jdd| _| 	  d S r   )
rJ   rK   
num_labelsrV  rB  r   r   rQ   scorerb  r   rS   r:   r;   rK     s
   
z'LlamaForSequenceClassification.__init__c                 C   r  r   r  re  r:   r:   r;   rf    r  z3LlamaForSequenceClassification.get_input_embeddingsc                 C   r  r   r  ri  r:   r:   r;   rk  "  r  z3LlamaForSequenceClassification.set_input_embeddingsNrm  r5   r   rC  rn  r  r   r   ro  rp  r   c                 C   s  |
dur|
n| j j}
| j||||||||	|
d	}|d }| |}|dur+|jd }n|jd }| j jdu r>|dkr>td| j jdu rGd}n|dur_t|| j j	 
dd |j}nd}|tj||jd|f }d}|dur||j}| j jdu r| jdkrd| j _n| jdkr|jtjks|jtj	krd	| j _nd
| j _| j jdkrt }| jdkr|| | }n+|||}n%| j jd	krt }||d| j|d}n| j jd
krt }|||}|
s|f|dd  }|dur|f| S |S t|||j|j|jdS )a  
        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).
        N)r5   r   rC  rn  r   r   ro  rp  r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r&   )rD   
regressionsingle_label_classificationmulti_label_classificationr  )r   ru  rB  r  r   rX  r   r,   eqr  argmaxrW   rD   rp   problem_typer  r)   rw  r	   r'  r   r   r   r   rC  r\   rt  )rP   rm  r5   r   rC  rn  r  r   r   ro  rp  transformer_outputsr\   r  r  sequence_lengthspooled_logitsr  r  r  r:   r:   r;   r_   %  sr   



"


z&LlamaForSequenceClassification.forwardr  )ra   rb   rc   rK   rf  rk  r   r  r,   r	  r   r  r   r@  r
  r   r   r   r_   rd   r:   r:   rS   r;   r    sL    		

r  r   )r   )r   )[r   r   r@   typingr   r   r   r   r,   torch.nn.functionalr   r   r2   torch.utils.checkpointtorch.nnr   r   r	   activationsr   cache_utilsr   r   modeling_attn_mask_utilsr   r   r   r   modeling_outputsr   r   r   modeling_utilsr   pytorch_utilsr   r   utilsr   r   r   r   r   r   utils.import_utilsr   configuration_llamar    
flash_attnr!   r"   flash_attn.bert_paddingr#   r$   r%   torch.fxfxwrap
get_loggerra   r   r  r<   r  r)   r  rB   SizerD   rG   ModulerH   appendre   r   r   r   r   r   r   r   r  r,  r5  r3  LLAMA_START_DOCSTRINGrA  r  rV  r  r  r:   r:   r:   r;   <module>   s    
 

$
" , KPIF $ >