
    g                    "   d dl Z d dlmZmZmZmZ d dlZd dlmc 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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'm(Z(m)Z)m*Z* ddl+m,Z,  e)j-        e.          Z/dZ0dZ1 G d dej2                  Z3 e#j4        e3            G d dej2                  Z5 G d de5          Z6 G d de5          Z7d Z8d>dZ9 G d dej2                  Z:dej;        d e<d!ej;        fd"Z= G d# d$ej2                  Z> G d% d&e>          Z? G d' d(e>          Z@e>e?e@d)ZA G d* d+ej2                  ZBd,ZC e&d-eC           G d. d/e!                      ZDd0ZE e&d-eC           G d1 d2eD                      ZF G d3 d4eDe          ZG e&d5eC           G d6 d7eD                      ZH e&d8eC           G d9 d:eD                      ZI e&d;eC           G d< d=eD                      ZJdS )?    N)ListOptionalTupleUnion)nn   )ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter)_flash_attention_forward)BaseModelOutputWithPastCausalLMOutputWithPastQuestionAnsweringModelOutput SequenceClassifierOutputWithPastTokenClassifierOutput)ROPE_INIT_FUNCTIONS)PreTrainedModel)ALL_LAYERNORM_LAYERS)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forward#is_flash_attn_greater_or_equal_2_10loggingreplace_return_docstrings   )LlamaConfigzmeta-llama/Llama-2-7b-hfr   c                   ,     e Zd Zd fd	Zd Zd Z xZS )LlamaRMSNormư>c                     t                                                       t          j        t	          j        |                    | _        || _        dS )z;
        LlamaRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parametertorchonesweightvariance_epsilon)selfhidden_sizeeps	__class__s      d/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/llama/modeling_llama.pyr%   zLlamaRMSNorm.__init__=   sD     	l5:k#:#:;; #    c                    |j         }|                    t          j                  }|                    d                              dd          }|t          j        || j        z             z  }| j        |                    |          z  S )N   T)keepdim)	dtypetor'   float32powmeanrsqrtr*   r)   )r+   hidden_statesinput_dtypevariances       r/   forwardzLlamaRMSNorm.forwardE   s|    #)%((77 $$Q'',,R,>>%Ht?T4T(U(UU{]--k::::r0   c                 H    t          | j        j                   d| j         S )Nz, eps=)tupler)   shaper*   r+   s    r/   
extra_reprzLlamaRMSNorm.extra_reprL   s&    )**II$2GIIIr0   )r"   )__name__
__module____qualname__r%   r>   rC   __classcell__r.   s   @r/   r!   r!   <   sb        $ $ $ $ $ $; ; ;J J J J J J Jr0   r!   c                   v     e Zd Z	 	 	 	 	 	 	 d
dee         f fdZd Z ej                    d	             Z	 xZ
S )LlamaRotaryEmbeddingN   '        ?defaultconfigc                 X   t                                                       i | _        |=t                              d           |||||d| _        || _        || _        || _        n_|j        9|j        	                    d|j        	                    d                    | _        nd| _        |j
        | _        |j
        | _        || _        t          | j                 | _         | j        | j        |fi | j        \  }| _        |                     d|d           | j        | _        d S )	Nz`LlamaRotaryEmbedding` can now be fully parameterized by passing the model config through the `config` argument. All other arguments will be removed in v4.46)	rope_typefactordimbasemax_position_embeddingsrQ   typerN   inv_freqF
persistent)r$   r%   rope_kwargsloggerwarning_oncerQ   max_seq_len_cachedoriginal_max_seq_lenrope_scalinggetrU   rO   r   rope_init_fnattention_scalingregister_bufferrW   original_inv_freq)
r+   rS   rU   rT   devicescaling_factorrQ   rO   rW   r.   s
            r/   r%   zLlamaRotaryEmbedding.__init__T   sC    	>R  
 '(+B   D 'DN&=D#(?D%% ".!'!4!8!8fFYF]F]^dFeFe!f!f!*&,&DD#(.(FD%/?+<4+<T[&+e+eTXTd+e+e($(ZeDDD!%r0   c                 ^   t          j        |          dz   }|| j        k    rB | j        | j        |fd|i| j        \  }| _        |                     d|d           || _        || j        k     r;| j        | j        k    r-|                     d| j	        d           | j        | _        dS dS dS )a  
        dynamic RoPE layers should recompute `inv_freq` in the following situations:
        1 - growing beyond the cached sequence length (allow scaling)
        2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
        r   seq_lenrW   FrX   N)
r'   maxr]   ra   rO   rZ   rb   rc   r^   rd   )r+   position_idsre   rh   rW   s        r/   _dynamic_frequency_updatez.LlamaRotaryEmbedding._dynamic_frequency_update   s     )L))A-T,,,/@t/@V0 0-408<8H0 0,Hd,   X% HHH&-D#T...43JTMf3f3f  T-CPU VVV&*&?D### /.3f3fr0   c                 V   d| j         v r|                     ||j                   | j        d d d d f                                                             |j        d         dd          }|d d d d d f                                         }|j        j        }t          |t                    r|dk    r|nd}t          j        |d	          5  |                                |                                z                      dd
          }t          j        ||fd          }|                                }|                                }	d d d            n# 1 swxY w Y   || j        z  }|	| j        z  }	|                    |j                  |	                    |j                  fS )Ndynamicre   r   r3   r   mpscpuF)device_typeenabledr2   rS   )r5   )rQ   rk   re   rW   floatexpandrA   rV   
isinstancestrr'   autocast	transposecatcossinrb   r6   r5   )
r+   xrj   inv_freq_expandedposition_ids_expandedrq   freqsembr{   r|   s
             r/   r>   zLlamaRotaryEmbedding.forward   s   &&**<*III !M$4-8>>@@GGHZ[\H]_acdee ,QQQaaaZ 8 > > @ @hm%/S%A%AekUZFZFZkk`e^UCCC 	 	&,,..1F1L1L1N1NNYYZ[]^__E)UEN333C''))C''))C		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 D**D**vvAGv$$cff17f&;&;;;s   A>EEE)NrK   rL   NrM   rN   N)rD   rE   rF   r   r   r%   rk   r'   no_gradr>   rG   rH   s   @r/   rJ   rJ   S   s          $(,*/ */ %*/ */ */ */ */ */X@ @ @$ U]__< < _< < < < <r0   rJ   c                   "     e Zd ZdZ fdZ xZS )!LlamaLinearScalingRotaryEmbeddingz[LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendevc                 x    t                               d           d|d<    t                      j        |i | d S )Nz`LlamaLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use `LlamaRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__).linearrQ   r[   r\   r$   r%   r+   argskwargsr.   s      r/   r%   z*LlamaLinearScalingRotaryEmbedding.__init__   sO    u	
 	
 	
 '{$)&)))))r0   rD   rE   rF   __doc__r%   rG   rH   s   @r/   r   r      s>        ee* * * * * * * * *r0   r   c                   "     e Zd ZdZ fdZ xZS )%LlamaDynamicNTKScalingRotaryEmbeddingzmLlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozillac                 x    t                               d           d|d<    t                      j        |i | d S )Nz`LlamaDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use `LlamaRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to __init__).rm   rQ   r   r   s      r/   r%   z.LlamaDynamicNTKScalingRotaryEmbedding.__init__   sN    	
 	
 	

 ({$)&)))))r0   r   rH   s   @r/   r   r      s>        ww* * * * * * * * *r0   r   c                     | dd| j         d         dz  f         }| d| j         d         dz  df         }t          j        | |fd          S )z*Rotates half the hidden dims of the input..Nr3   r2   rs   )rA   r'   rz   )r}   x1x2s      r/   rotate_halfr      s]    	
3"!'"+"""	#B	
3q """	#B9rc2YB''''r0   c                     |                     |          }|                     |          }| |z  t          |           |z  z   }||z  t          |          |z  z   }||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.
    )	unsqueezer   )qkr{   r|   rj   unsqueeze_dimq_embedk_embeds           r/   apply_rotary_pos_embr      sc    ( --
&
&C
--
&
&C3w;q>>C/0G3w;q>>C/0GGr0   c                   $     e Zd Z fdZd Z xZS )LlamaMLPc                    t                                                       || _        |j        | _        |j        | _        t          j        | j        | j        |j                  | _        t          j        | j        | j        |j                  | _	        t          j        | j        | j        |j                  | _
        t          |j                 | _        d S )Nbias)r$   r%   rO   r,   intermediate_sizer   Linearmlp_bias	gate_projup_proj	down_projr	   
hidden_actact_fnr+   rO   r.   s     r/   r%   zLlamaMLP.__init__   s    !-!'!94#3T5KRXRabbby!143IPVP_```4#94;KRXRabbbV./r0   c                 p  	 | j         j        dk    rN| j        | j         j        z  }| j        j                            |d          | j        j                            |d          	| j        j                            |d          t          j	        fdt          | j         j                  D             d          }t          j	        	fdt          | j         j                  D             d          }|                     |          |z                      |d          fdt          | j         j                  D             }t          |          }nQ|                     |                     |                                         |                               z            }|S )	Nr   r   rs   c                 F    g | ]}t          j        |                   S  Fr   ).0igate_proj_slicesr}   s     r/   
<listcomp>z$LlamaMLP.forward.<locals>.<listcomp>   s+    ]]]a!-a011]]]r0   r3   c                 F    g | ]}t          j        |                   S r   r   )r   r   up_proj_slicesr}   s     r/   r   z$LlamaMLP.forward.<locals>.<listcomp>   s*     k k kA!^A->!?!? k k kr0   r2   c                 R    g | ]#}t          j        |         |                   $S r   r   )r   r   down_proj_slicesintermediate_statess     r/   r   z$LlamaMLP.forward.<locals>.<listcomp>   s>       JK,Q/1A!1DEE  r0   )rO   pretraining_tpr   r   r)   splitr   r   r'   rz   ranger   sum)
r+   r}   slicer   r   r   r   r   r   r   s
    `    @@@@r/   r>   zLlamaMLP.forward   s   ;%))*dk.HHE#~4::5a:HH!\066u!6DDN#~4::5a:HH	]]]]]5A[;\;\]]]ce  I i k k k k kt{OiIjIj k k kqstttG#';;y#9#9G#C"J"J5VW"J"X"X    OTUYU`UoOpOp  I IIIt{{4>>!3D3D'E'EUV'WXXIr0   )rD   rE   rF   r%   r>   rG   rH   s   @r/   r   r      sG        0 0 0 0 0      r0   r   r;   n_repreturnc                     | j         \  }}}}|dk    r| S | dddddddddf                             |||||          } |                     |||z  ||          S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)rA   ru   reshape)r;   r   batchnum_key_value_headsslenhead_dims         r/   	repeat_kvr     s    
 2?1D.Ehzz!!!!QQQaaa"23::5BUW\^bdlmmM  (;e(CT8TTTr0   c                   R    e Zd ZdZddedee         f f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
                 deeej	        ej	        f                  deej	        eej	                 eeej	                          f         fdZ xZS )LlamaAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNrO   	layer_idxc                    t                                                       || _        || _        |(t                              d| j        j         d           |j        | _        |j	        | _	        |j
        | _        t          |d| j	        | j        z            | _        |j        | _        | j        | j        z  | _        |j        | _        |j        | _        d| _        t'          j        | j	        | j        | j        z  |j                  | _        t'          j        | j	        | j        | j        z  |j                  | _        t'          j        | j	        | j        | j        z  |j                  | _        t'          j        | j        | j        z  | j	        |j                  | _        t5          | j                  | _        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.r   Tr   rO   )r$   r%   rO   r   r[   r\   r.   rD   attention_dropoutr,   num_attention_heads	num_headsgetattrr   r   num_key_value_groupsrU   
rope_theta	is_causalr   r   attention_biasq_projk_projv_projo_projrJ   
rotary_embr+   rO   r   r.   s      r/   r%   zLlamaAttention.__init__  s   ",!8 , , ,   "(!9!-3
D4D4VWW#)#= $(Nd6N$N!'-'E$ +i 0$.4=2PW]Wlmmmi 0$2JT]2Zagavwwwi 0$2JT]2Zagavwwwi >@PW]Wlmmm /dkBBBr0   Fr;   attention_maskrj   past_key_valueoutput_attentions	use_cachecache_positionposition_embeddingsr   c	                 
                                    \  }
}}| j        j        dk    rN| j        | j        z  | j        j        z  }| j        j                            | j        | j        z  | j        j        z  d          | j	        j                            |d          | j
        j                            |d          fdt          | j        j                  D             }t          j        |d          }fdt          | j        j                  D             }t          j        |d          }fdt          | j        j                  D             }t          j        |d          }n?|                               }| 	                              }| 
                              }|                    |
|| j        | j                                      dd          }|                    |
|| j        | j                                      dd          }|                    |
|| j        | j                                      dd          }|4t                               d	           |                     ||          \  }}n|\  }}t'          ||||          \  }}|&|||d
}|                    ||| j        |          \  }}t-          || j                  }t-          || j                  }t          j        ||                    dd                    t3          j        | j                  z  }|$|d d d d d d d |j        d         f         }||z   }t8          j                            |dt          j                                       |j!                  }t8          j        "                    || j#        | j$                  }t          j        ||                                           |
| j        || j        fk    r5tK          d|
| j        || j        f d                                                                dd          &                                '                    |
|d          | j        j        dk    r                    | j(        | j        j        z  d          | j)        j                            | j(        | j        j        z  d          tU          fdt          | j        j                  D                       n| )                              |sd }||fS )Nr   r   rs   c                 F    g | ]}t          j        |                   S r   r   )r   r   r;   query_slicess     r/   r   z*LlamaAttention.forward.<locals>.<listcomp>I  )    pppAH]LODDpppr0   r3   c                 F    g | ]}t          j        |                   S r   r   )r   r   r;   
key_slicess     r/   r   z*LlamaAttention.forward.<locals>.<listcomp>L  s)    lllQ!(=*Q-@@lllr0   c                 F    g | ]}t          j        |                   S r   r   )r   r   r;   value_slicess     r/   r   z*LlamaAttention.forward.<locals>.<listcomp>O  r   r0   r2   Y  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|   r{   r   r   )rS   r5   )ptrainingz `attn_output` should be of size z	, but is c                 R    g | ]#}t          j        |         |                   $S r   r   )r   r   attn_outputo_proj_slicess     r/   r   z*LlamaAttention.forward.<locals>.<listcomp>  s.    uuuaqxAa8HIIuuur0   )+sizerO   r   r   r   r   r)   r   r   r   r   r   r'   rz   viewry   r[   r\   r   r   updater   r   r   matmulmathsqrtrA   r   
functionalsoftmaxr7   r6   r5   dropoutr   r   
ValueError
contiguousr   r,   r   r   )r+   r;   r   rj   r   r   r   r   r   r   bszq_len_key_value_slicingquery_states
key_statesvalue_statesr{   r|   cache_kwargsattn_weightscausal_maskr   r   r   r   r   s    `                    @@@@@r/   r>   zLlamaAttention.forward3  sE    &**,,UA;%))!%!9DM!IdkNh h;-33$-/DK4NNTU 4  L +112C1KKJ;-334E13MMLpppppeTXT_TnNoNopppL 9\r:::Llllll%PTP[PjJkJklllJ:2666JpppppeTXT_TnNoNopppL 9\r:::LL  ;;}55L]33J;;}55L#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm&G   |\BBHC*HC#7jRUWZ#[#[ j%#&snUUL'5'<'<ZW[Wegs't't$Jz4+DEE
 t/HII|L*2F2Fq!2L2LMMPTPYZ^ZgPhPhh%(AAAqqq2HJ4DR4H2H)HIK'+5L },,\r,WWZZ[g[mnn},,\T=S^b^k,lll<>>#t~udm!LLL)CPTP]3^ ) )$$&&) )  
 "++Aq11<<>>!))#ub99;%))%++D,<@Z,Z`a+bbK K.44T5EIc5cij4kkMuuuuuSXY]YdYsStStuuuvvKK++k22K  	 LL.88r0   NNNNFFNN)rD   rE   rF   r   r   r   intr%   r'   Tensor
LongTensorr
   boolr   r>   rG   rH   s   @r/   r   r     sO       GGC C{ Cx} C C C C C C@ 2637*."'59KOZ9 Z9|Z9 !.Z9 u/0	Z9
 !Z9  Z9 Z9 !!12Z9 &eEL%,,F&GHZ9 
u|Xel3XeEL>Q5RR	SZ9 Z9 Z9 Z9 Z9 Z9 Z9 Z9r0   r   c                   :    e Zd ZdZ f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                 deeej        ej        f                  deej        eej                 eeej                          f         fdZ x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                 b     t                      j        |i | t                       | _        d S r  )r$   r%   r   _flash_attn_uses_top_left_maskr   s      r/   r%   zLlamaFlashAttention2.__init__  s9    $)&)))
 3V2W2W.W+++r0   NFr;   r   rj   r   r   r   r   r   r   c	                 b   t          |t                    rt          d          d}|                                \  }	}
}|                     |          }|                     |          }|                     |          }|                    |	|
| j        | j	                  
                    dd          }|                    |	|
| j        | j	                  
                    dd          }|                    |	|
| j        | j	                  
                    dd          }|4t                              d           |                     ||          \  }}n|\  }}t          ||||          \  }}|&|||d}|                    ||| j        |          \  }}|
                    dd          }|
                    dd          }|
                    dd          }| j        r| j        nd}|j        }|t*          j        k    rt+          j                    rt+          j                    }n3t3          | j        d          r| j        j        }n| j        j        j        }t                              d	| d
           |                    |          }|                    |          }|                    |          }t=          |||||
||t?          | dd           | j         | j!        
  
        }|"                    |	|
d          #                                }| $                    |          }|s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/transformersFr   r2   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 .sliding_window)rj   r   r  use_top_left_maskr   r3   )%rv   r   r   r   r   r   r   r   r   r   ry   r   r[   r\   r   r   r   r   r   r   r5   r'   r7   is_autocast_enabledget_autocast_gpu_dtypehasattrrO   r  r)   r6   r   r   r  r   r   r   r   )r+   r;   r   rj   r   r   r   r   r   r   r   r   r   r   r   r{   r|   r  dropout_rater<   target_dtyper   r  s                          r/   r>   zLlamaFlashAttention2.forward  s\    nk22 	}  
 "%**,,UA{{=11[[//
{{=11
 $((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm&G   |\BBHC*HC#7jRUWZ#[#[ j%#&snUUL'5'<'<ZW[Wegs't't$J $--a33))!Q//
#--a3315Gt--C #(%-''(** 8$;==&?@@ 8#{B#{17$ $ $ $   (??<88L#|44J'??<88L.% "4)94@@"An
 
 
 "))#ub99DDFFkk+..  	 LL.88r0   r  )rD   rE   rF   r   r%   r'   r  r   r  r
   r	  r   r>   rG   rH   s   @r/   r  r    s3        X X X X X 6:37*."'59KOf9 f9|f9 !!12f9 u/0	f9
 !f9  f9 f9 !!12f9 &eEL%,,F&GHf9 
u|Xel3XeEL>Q5RR	Sf9 f9 f9 f9 f9 f9 f9 f9r0   r  c                   4    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                 dee
ej        ej        f                  de
ej        eej                 ee
ej                          f         f fdZ x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;   r   rj   r   r   r   r   r   r   c	           
         |rCt                               d           t                                          ||||||||          S |                                \  }
}}|                     |          }|                     |          }|                     |          }|                    |
|| j	        | j
                                      dd          }|                    |
|| j        | j
                                      dd          }|                    |
|| j        | j
                                      dd          }|4t                               d           |                     ||          \  }}n|\  }}t          ||||          \  }}|&|||d}|                    ||| j        |          \  }}t#          || j                  }t#          || j                  }|}||d d d d d d d |j        d         f         }|j        j        dk    r>|<|                                }|                                }|                                }||dk    rd	nd
}t.          j        j                            ||||| j        r| j        nd|          }|                    dd                                          }|                    |
|d          }|                     |          }|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;   r   rj   r   r   r   r   r   r   r2   r   r   r   cudaTFr  )	attn_mask	dropout_pr   r3   )r[   r\   r$   r>   r   r   r   r   r   r   r   ry   r   r   r   r   r   r   r   rA   re   rV   r   r'   r   r   scaled_dot_product_attentionr   r   r   )r+   r;   r   rj   r   r   r   r   r   r   r   r   r   r   r   r   r{   r|   r  r  r   r   r.   s                         r/   r>   zLlamaSdpaAttention.forward  s/     	[   77??+-)-"3#-$7 # 	 	 	 &**,,UA{{=11[[//
{{=11#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm&G   |\BBHC*HC#7jRUWZ#[#[ j%#&snUUL'5'<'<ZW[Wegs't't$Jz4+DEE
 t/HII$%%aaaAAA/E1A"1E/E&EFK #v--+2I'2244L#..00J'2244L (/EAIIDD5	h)FF!04Fd,,3 G 
 
 "++Aq11<<>>!&&sE266kk+..D.00r0   r  )rD   rE   rF   r   r'   r  r   r  r
   r	  r   r>   rG   rH   s   @r/   r  r    s          2637*."'59KOX1 X1|X1 !.X1 u/0	X1
 !X1  X1 X1 !!12X1 &eEL%,,F&GHX1 
u|Xel3XeEL>Q5RR	SX1 X1 X1 X1 X1 X1 X1 X1 X1 X1r0   r  )eagerflash_attention_2sdpac                   N    e Zd Zdedef f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j        eeej        ej        f                  f         fdZ xZS )LlamaDecoderLayerrO   r   c                 J   t                                                       |j        | _        t          |j                 ||          | _        t          |          | _        t          |j        |j	                  | _
        t          |j        |j	                  | _        d S )N)rO   r   r-   )r$   r%   r,   LLAMA_ATTENTION_CLASSES_attn_implementation	self_attnr   mlpr!   rms_norm_epsinput_layernormpost_attention_layernormr   s      r/   r%   zLlamaDecoderLayer.__init__s  s    !-01LMU[gpqqqF##+F,>FDWXXX(4V5GVM`(a(a(a%%%r0   NFr;   r   rj   r   r   r   r   r   r   c	                     |}
|                      |          } | j        d||||||||d|	\  }}}|
|z   }|}
|                     |          }|                     |          }|
|z   }|f}|r||fz  }|r||fz  }|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
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence
            position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
                Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
                with `head_dim` being the embedding dimension of each attention head.
            kwargs (`dict`, *optional*):
                Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
                into the model
        r  r   )r-  r*  r.  r+  )r+   r;   r   rj   r   r   r   r   r   r   residualself_attn_weightspresent_key_valueoutputss                 r/   r>   zLlamaDecoderLayer.forward}  s    D !,,];; ?Mdn 
?
')%)/) 3
?
 
?
 
?
 
?
;(*; !=0 !55mDD// =0 " 	,)++G 	,)++Gr0   r  )rD   rE   rF   r   r  r%   r'   r  r   r  r
   r	  r   FloatTensorr>   rG   rH   s   @r/   r%  r%  r  sG       b{ bs b b b b b b 2637*.,1$)59KOB B|B !.B u/0	B
 !B $D>B D>B !!12B &eEL%,,F&GHB 
u (51BEDU1U+V"WW	XB B B B B B B Br0   r%  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                   @    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S )LlamaPreTrainedModelmodelTr%  past_key_valuesc                    | j         j        }t          |t          j                  rJ|j        j                            d|           |j         |j        j        	                                 d S d S t          |t          j
                  rS|j        j                            d|           |j        -|j        j        |j                 	                                 d S d S d S )Nr  )r9   std)rO   initializer_rangerv   r   r   r)   datanormal_r   zero_	Embeddingpadding_idx)r+   moduler:  s      r/   _init_weightsz"LlamaPreTrainedModel._init_weights  s    k+fbi(( 	?M&&CS&999{& &&((((( '&-- 	?M&&CS&999!-"6#56<<>>>>>	? 	?--r0   N)rD   rE   rF   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_cache_class_supports_quantized_cache_supports_static_cacherB  r   r0   r/   r6  r6    se        
 L&*#,-#4"5!N  $!	? 	? 	? 	? 	?r0   r6  a  
    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, see our
            [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
            - 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.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
c                   
    e Zd ZdZdef fdZd Zd Z ee	          	 	 	 	 	 	 	 	 	 	 dde
j        dee
j                 d	ee
j                 d
eeeee
j                 f                  dee
j                 dee         dee         dee         dee         dee
j                 deeef         fd            Zde
j        de
j        de
j        d
edef
dZede
j        dedede
j        de
j        de
j        defd            Z xZS )
LlamaModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]

    Args:
        config: LlamaConfig
    rO   c                    t                                                     j        | _        j        | _        t          j        j        j        | j                  | _        t          j	        fdt          j                  D                       | _        t          j        j                  | _        t!                    | _        d| _        |                                  d S )Nc                 0    g | ]}t          |          S r   )r%  )r   r   rO   s     r/   r   z'LlamaModel.__init__.<locals>.<listcomp>M  s$    cccivy11cccr0   r'  r   F)r$   r%   pad_token_idr@  
vocab_sizer   r?  r,   embed_tokens
ModuleListr   num_hidden_layerslayersr!   r,  normrJ   r   gradient_checkpointing	post_initr   s    `r/   r%   zLlamaModel.__init__F  s       !. +L):F<NPTP`aamcccc5IaCbCbccc
 
 !!39LMMM	.f===&+# 	r0   c                     | j         S r  rS  rB   s    r/   get_input_embeddingszLlamaModel.get_input_embeddingsV  s      r0   c                     || _         d S r  r[  r+   values     r/   set_input_embeddingszLlamaModel.set_input_embeddingsY  s    !r0   N	input_idsr   rj   r8  inputs_embedsr   r   output_hidden_statesreturn_dictr   r   c                    ||n| j         j        }||n| j         j        }||n| j         j        }|	|	n| j         j        }	|d u |d uz  rt          d          | j        r%| j        r|rt          	                    d           d}|| 
                    |          }d}|rVt          |t                    sAd}|t                      }n.t          j        |          }t          	                    d           |
B||                                nd}t!          j        |||j        d         z   |j                  }
||
                    d          }|                     |||
||          }|}|                     ||          }|rd	nd }|rd	nd }d }| j        D ]r}|r||fz  }| j        r*| j        r#|                     |j        |||||||
|	  	        }n ||||||||
|
          }|d         }|r||rdnd         }|r||d         fz  }s|                     |          }|r||fz  }|r|nd }|r|                                }|	st9          d ||||fD                       S t;          ||||          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`.FTzWe detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class (https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)r   r   rn   r   )r   rj   r   r   r   r   r   r2   c              3      K   | ]}||V  	d S r  r   )r   vs     r/   	<genexpr>z%LlamaModel.forward.<locals>.<genexpr>  s(      ttqfgfsfsfsfsfsttr0   )last_hidden_stater8  r;   
attentions)rO   r   rc  r   use_return_dictr   rX  r   r[   r\   rS  rv   r
   r   from_legacy_cacheget_seq_lengthr'   arangerA   re   r   _update_causal_maskr   rV  _gradient_checkpointing_func__call__rW  to_legacy_cacher@   r   )r+   ra  r   rj   r8  rb  r   r   rc  rd  r   return_legacy_cachepast_seen_tokensr  r;   r   all_hidden_statesall_self_attnsnext_decoder_cachedecoder_layerlayer_outputs
next_caches                         r/   r>   zLlamaModel.forward\  s    2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]-t";< 	[YZZZ& 	4= 	Y 	j   I  --i88M $ 
	Z?? 
	"&&"..."."@"Q"Q##^   !CRC^==???de"\ "2]5H5K"KTaTh  N )33A66L..M>?L]
 
 & #oom\JJ #7@BBD0:d!![ "	6 "	6M# 6!m%55!* t}  $ A A!*! #%"'
! 
! !.!#.!-#2&7'#1(;	! 	! 	! *!,M R%28I3P11q%Q"  6=#3"55		-00   	2-!11+4>''$
 	6#3355J 	utt]J@QSa$btttttt&+&+%	
 
 
 	
r0   input_tensorc           
         | j         j        dk    r
|d|v r|S d S ||                                nd}t          |t                    }| j         j        dk    r#|s!|st          j        |||| j                  rd S |j        |j	        }	}|j
        d         }
|r|                                }n/t          |t          j                  r|j
        d         n||
z   dz   }|                     ||
|||	||j
        d                   }| j         j        dk    rB|@|j	        j        d	k    r0|s.t          j        |          j        }t          j        ||          }|S )
Nr"  r  r   r#  )rb  past_key_values_lengthis_trainingr   r3   )sequence_lengthtarget_lengthr5   re   r   
batch_sizer  )rO   r)  rm  rv   r   r   _ignore_causal_mask_sdpar   r5   re   rA   get_max_cache_shaper'   r  5_prepare_4d_causal_attention_mask_with_cache_positionrV   finfomin_unmask_unattended)r+   r   r{  r   r8  r   rt  using_static_cacher5   re   r  r  r  	min_dtypes                 r/   ro  zLlamaModel._update_causal_mask  s    ;+/BBB)c^.C.C%%4
 @O?Z?99;;;`a'EE ;+v55>P5Yj5%>*'7 M	    t$*L,?v&,Q/ 	+??AAMM nel;;<$R((%7!;  PP+')#)!, Q 
 
 K,66*%*f44% 5 E**.I0CKQZ[[Kr0   r  r  r5   re   r  c                    | |                                  dk    r| }n+t          j        |          j        }	t          j        ||f|	||          }|dk    rt          j        |d          }|t          j        ||          |                    dd          k    z  }|ddddddf                             |ddd          }| |	                                }| j
        d         }
|ddddddd|
f         | ddddddf         z   }|dk    }|ddddddd|
f                             ||	          |ddddddd|
f<   |S )	a  
        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.
            device (`torch.device`):
                The device to plcae the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )
fill_valuer5   re   r   )diagonalrn   r3   r   )rS   r'   r  r  fulltriurn  r   ru   clonerA   masked_fill)r   r  r  r5   re   r   r  r   r  r  mask_lengthpadding_masks               r/   r  z@LlamaModel._prepare_4d_causal_attention_mask_with_cache_position  s   B %.*<*<*>*>!*C*C(KKE**.I* -0Ye\b  K !###jqAAA5<fEEEH^H^_acdHeHeeeK%dD!!!QQQ&67>>z1bRTUUK))//11,226*111aaaL[L+@ANSTSTSTVZ\`bcbcbcScDdd+q05@AAAqqq,;,AV5W5c5c )6 6AAAqqq!!!\k\12 r0   
NNNNNNNNNN)rD   rE   rF   r   r   r%   r\  r`  r   LLAMA_INPUTS_DOCSTRINGr'   r  r   r  r   r
   r   r4  r	  r   r   r>   ro  staticmethodr  r5   re   r  rG   rH   s   @r/   rN  rN  :  sE       
 {       ! ! !" " " +*+ABB '+1537KO59$(,0/3&*59x
 x
#x
 !.x
 u/0	x

 "%tE4E/F(F"GHx
   12x
 D>x
 $D>x
 'tnx
 d^x
 !!12x
 
u--	.x
 x
 x
 CBx
t?? l? 	?
 ?  ? ? ? ?B 555 5 {	5
 5 5 5 5 5 \5 5 5 5 5r0   rN  c                       e Zd ZdgZ fdZd Zd Zd Zd Zd Z	d Z
 ee           eee	          	 	 	 	 	 	 	 	 	 	 	 	 ddej        deej                 deej                 deeeeej                 f                  deej                 deej                 dee         dee         dee         dee         deej                 dedeeef         fd                        Z xZS )LlamaForCausalLMzlm_head.weightc                     t                                          |           t          |          | _        |j        | _        t          j        |j        |j        d          | _        | 	                                 d S NFr   )
r$   r%   rN  r7  rR  r   r   r,   lm_headrY  r   s     r/   r%   zLlamaForCausalLM.__init__T  sj       ''
 +y!3V5FUSSS 	r0   c                     | j         j        S r  r7  rS  rB   s    r/   r\  z%LlamaForCausalLM.get_input_embeddings]      z&&r0   c                     || j         _        d S r  r  r^  s     r/   r`  z%LlamaForCausalLM.set_input_embeddings`      "'
r0   c                     | j         S r  r  rB   s    r/   get_output_embeddingsz&LlamaForCausalLM.get_output_embeddingsc  s
    |r0   c                     || _         d S r  r  )r+   new_embeddingss     r/   set_output_embeddingsz&LlamaForCausalLM.set_output_embeddingsf  s    %r0   c                     || _         d S r  r7  )r+   decoders     r/   set_decoderzLlamaForCausalLM.set_decoderi  s    


r0   c                     | j         S r  r  rB   s    r/   get_decoderzLlamaForCausalLM.get_decoderl  s
    zr0   )output_typerC  Nr   ra  r   rj   r8  rb  labelsr   r   rc  rd  r   num_logits_to_keepr   c                    ||n| j         j        }|	|	n| j         j        }	|
|
n| j         j        }
|                     ||||||||	|
|
  
        }|d         | j         j        dk    rp| j        j                            | j	        | j         j        z  d          fdt          | j         j                  D             }t          j        |d          }n%|                     dd| dddf                   }d}| | j        d
||| j         j	        d|}|
s|f|dd         z   }||f|z   n|S t          |||j        |j        |j        	          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]`.

            num_logits_to_keep (`int`, *optional*):
                Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
                `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
                token can save memory, which becomes pretty significant for long sequences or large vocabulary size.

        Returns:

        Example:

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

        >>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
        >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")

        >>> 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)
ra  r   rj   r8  rb  r   r   rc  rd  r   r   r   rs   c                 F    g | ]}t          j        |                   S r   r   )r   r   r;   lm_head_slicess     r/   r   z,LlamaForCausalLM.forward.<locals>.<listcomp>  s*    lllQah}nQ.?@@lllr0   r3   )logitsr  rR  lossr  r8  r;   rj  r   )rO   r   rc  rk  r7  r   r  r)   r   rR  r   r'   rz   loss_functionr   r8  r;   rj  )r+   ra  r   rj   r8  rb  r  r   r   rc  rd  r   r  loss_kwargsr3  r  r  outputr;   r  s                     @@r/   r>   zLlamaForCausalLM.forwardo  s   ` 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B] **)%+'/!5#)  
 
  
;%))!\066t$+Jd7djk6llNlllll%PTP[PjJkJklllFYv2...FF \\-4F3F3G3G0J"KLLF%4%uVFt{OeuuituuD 	DY,F'+'7D7V##VC%#3!/)
 
 
 	
r0   )NNNNNNNNNNNr   )rD   rE   rF   _tied_weights_keysr%   r\  r`  r  r  r  r  r   r  r   r   _CONFIG_FOR_DOCr'   r  r   r  r   r
   r   r4  r	  r  r   r>   rG   rH   s   @r/   r  r  Q  s       *+    ' ' '( ( (  & & &     +*+ABB+AP_``` '+1537KO59-1$(,0/3&*59"#Y
 Y
#Y
 !.Y
 u/0	Y

 "%tE4E/F(F"GHY
   12Y
 )*Y
 D>Y
 $D>Y
 'tnY
 d^Y
 !!12Y
  Y
 
u,,	-Y
 Y
 Y
 a` CBY
 Y
 Y
 Y
 Y
r0   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                   v    e Zd Z fdZd Zd Z ee          	 	 	 	 	 	 	 	 	 	 ddee	j
                 dee	j                 dee	j
                 deeeee	j                 f                  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            Z xZS )LlamaForSequenceClassificationc                     t                                          |           |j        | _        t          |          | _        t          j        |j        | j        d          | _        | 	                                 d S r  )
r$   r%   
num_labelsrN  r7  r   r   r,   scorerY  r   s     r/   r%   z'LlamaForSequenceClassification.__init__  si        +''
Yv14?OOO
 	r0   c                     | j         j        S r  r  rB   s    r/   r\  z3LlamaForSequenceClassification.get_input_embeddings  r  r0   c                     || j         _        d S r  r  r^  s     r/   r`  z3LlamaForSequenceClassification.set_input_embeddings  r  r0   Nra  r   rj   r8  rb  r  r   r   rc  rd  r   c                 "   |
|
n| j         j        }
|                     ||||||||	|
	  	        }|d         }|                     |          }||j        d         }n|j        d         }| j         j        |dk    rt          d          | j         j        d}nv|rt          j        || j         j                  	                                
                    d          dz
  }||j        d         z  }|                    |j                  }nd}|t          j        ||j                  |f         }d}||                     |||| j                   }|
s|f|dd         z   }||f|z   n|S t          |||j        |j        |j        	          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).
        Nr   rj   r8  rb  r   r   rc  rd  r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r3   rn   )r  r  pooled_logitsrO   r  )rO   rk  r7  r  rA   rQ  r   r'   eqr  argmaxr6   re   rn  r  r   r8  r;   rj  )r+   ra  r   rj   r8  rb  r  r   r   rc  rd  transformer_outputsr;   r  r  sequence_lengthsr  r  r  s                      r/   r>   z&LlamaForSequenceClassification.forward  s   ( &1%<kk$+B]"jj)%+'/!5# ) 

 

 ,A.M** "+JJ&,Q/J;#+
a\]]];#+!$#(8It{7O#P#P#T#T#V#V#]#]^`#a#ade#e #3iob6I#I #3#6#6v}#E#E  #% u|Jv}MMMO__`%%VFR_hlhs%ttD 	F#%(;ABB(??F)-)9TGf$$vE/ /?-;*5
 
 
 	
r0   r  )rD   rE   rF   r%   r\  r`  r   r  r   r'   r  r  r   r
   r   r4  r	  r   r   r>   rG   rH   s   @r/   r  r    s            ' ' '( ( ( +*+ABB 151537KO59-1$(,0/3&*E
 E
E,-E
 !.E
 u/0	E

 "%tE4E/F(F"GHE
   12E
 )*E
 D>E
 $D>E
 'tnE
 d^E
 
u66	7E
 E
 E
 CBE
 E
 E
 E
 E
r0   r  z
The Llama Model transformer with a span classification head on top for extractive question-answering tasks like
SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c                       e Zd ZdZ fdZd Zd Z ee          	 	 	 	 	 	 	 	 	 	 dde	e
j                 de	e
j                 de	e
j                 d	e	eeee
j                 f                  d
e	e
j                 de	e
j                 de	e
j                 de	e         de	e         de	e         deeef         fd            Z xZS )LlamaForQuestionAnsweringtransformerc                     t                                          |           t          |          | _        t	          j        |j        d          | _        |                                  d S )Nr2   )	r$   r%   rN  r  r   r   r,   
qa_outputsrY  r   s     r/   r%   z"LlamaForQuestionAnswering.__init__@  sY       %f--)F$6:: 	r0   c                     | j         j        S r  r  rS  rB   s    r/   r\  z.LlamaForQuestionAnswering.get_input_embeddingsH  s    ,,r0   c                     || j         _        d S r  r  r^  s     r/   r`  z.LlamaForQuestionAnswering.set_input_embeddingsK  s    (-%%%r0   Nra  r   rj   r8  rb  start_positionsend_positionsr   rc  rd  r   c           
         |
|
n| j         j        }
|                     |||||||	|
          }|d         }|                     |          }|                    dd          \  }}|                    d                                          }|                    d                                          }d}|| | j        ||||fi |}|
s||f|dd         z   }||f|z   n|S t          ||||j	        |j
                  S )	a  
        start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        N)r   rj   r8  rb  r   rc  rd  r   r   r3   rs   r2   )r  start_logits
end_logitsr;   rj  )rO   rk  r  r  r   squeezer   r  r   r;   rj  )r+   ra  r   rj   r8  rb  r  r  r   rc  rd  r   r3  sequence_outputr  r  r  r  r  s                      r/   r>   z!LlamaForQuestionAnswering.forwardN  sR   2 &1%<kk$+B]"")%+'/!5# # 	
 	
 "!*11#)<<r<#:#: j#++B//::<<''++6688
&=+D%4%lJQ^iibhiiD 	F"J/'!""+=F)-)9TGf$$vE+%!!/)
 
 
 	
r0   r  )rD   rE   rF   rD  r%   r\  r`  r   r  r   r'   r  r4  r   r
   r   r	  r   r   r>   rG   rH   s   @r/   r  r  5  s{        &    - - -. . . +*+ABB 156:37KO596:48,0/3&*:
 :
E,-:
 !!23:
 u/0	:

 "%tE4E/F(F"GH:
   12:
 "%"23:
   01:
 $D>:
 'tn:
 d^:
 
u22	3:
 :
 :
 CB:
 :
 :
 :
 :
r0   r  z
    The Llama Model transformer with a token classification head on top (a linear layer on top of the hidden-states
    output) e.g. for Named-Entity-Recognition (NER) tasks.
    c                       e Zd Z fdZd Zd Z ee           ee	e
e          	 	 	 	 	 	 	 	 	 	 dde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                        Z xZS )LlamaForTokenClassificationc                    t                                          |           |j        | _        t          |          | _        t          |dd           |j        }nt          |dd           |j        }nd}t          j	        |          | _
        t          j        |j        |j                  | _        |                                  d S )Nclassifier_dropouthidden_dropoutg?)r$   r%   r  rN  r7  r   r  r  r   Dropoutr   r   r,   r  rY  )r+   rO   r  r.   s      r/   r%   z$LlamaForTokenClassification.__init__  s        +''
6/66B!'!:V-t44@!'!6!$z"455Yv163DEE
 	r0   c                     | j         j        S r  r  rB   s    r/   r\  z0LlamaForTokenClassification.get_input_embeddings  r  r0   c                     || j         _        d S r  r  r^  s     r/   r`  z0LlamaForTokenClassification.set_input_embeddings  r  r0   )
checkpointr  rC  Nra  r   rj   r8  rb  r  r   r   rc  rd  r   c                 p   |
|
n| j         j        }
|                     ||||||||	|
	  	        }|d         }|                     |          }|                     |          }d}||                     ||| j                   }|
s|f|dd         z   }||f|z   n|S t          |||j        |j                  S )r  Nr  r   r2   )r  r  r;   rj  )	rO   rk  r7  r   r  r  r   r;   rj  )r+   ra  r   rj   r8  rb  r  r   r   rc  rd  r3  r  r  r  r  s                   r/   r>   z#LlamaForTokenClassification.forward  s    2 &1%<kk$+B]**)%+'/!5#  

 

 "!*,,77O,,%%ffdkBBD 	FY,F)-)9TGf$$vE$!/)	
 
 
 	
r0   r  )rD   rE   rF   r%   r\  r`  r   r  r   _CHECKPOINT_FOR_DOCr   r  r   r'   r  r  r   r4  r	  r   r   r>   rG   rH   s   @r/   r  r    s            ' ' '( ( ( +*+ABB&)$   151537=A59-1$(,0/3&*1
 1
E,-1
 !.1
 u/0	1

 "$u'8"9:1
   121
 )*1
 D>1
 $D>1
 'tn1
 d^1
 
u++	,1
 1
 1
  CB1
 1
 1
 1
 1
r0   r  )Nr   )Kr   typingr   r   r   r   r'   torch.nn.functionalr   r   r   torch.utils.checkpointactivationsr	   cache_utilsr
   r   r   
generationr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   modeling_outputsr   r   r   r   r   modeling_rope_utilsr   modeling_utilsr   pytorch_utilsr   utilsr   r   r   r   r   r   configuration_llamar   
get_loggerrD   r[   r  r  Moduler!   appendrJ   r   r   r   r   r   r  r  r   r   r  r  r(  r%  LLAMA_START_DOCSTRINGr6  r  rN  r  r  r  r  r   r0   r/   <module>r     s!  (  / / / / / / / / / / / /                     ! ! ! ! ! ! ; ; ; ; ; ; ; ; ; ; ) ) ) ) ) ) > > > > > > F F F F F F              7 6 6 6 6 6 - - - - - - 1 1 1 1 1 1                - , , , , , 
	H	%	%0 J J J J J29 J J J(   L ) ) )T< T< T< T< T<29 T< T< T<n	* 	* 	* 	* 	*(< 	* 	* 	*
* 
* 
* 
* 
*,@ 
* 
* 
*( ( (   6    ry   D	UU\ 	U# 	U%, 	U 	U 	U 	Uz9 z9 z9 z9 z9RY z9 z9 z9zu9 u9 u9 u9 u9> u9 u9 u9p`1 `1 `1 `1 `1 `1 `1 `1H -  M M M M M	 M M M` " Y ? ? ? ? ?? ? ?	 ?0H V Y P P P P P% P P	 Pfy
 y
 y
 y
 y
+_ y
 y
 y
x   V
 V
 V
 V
 V
%9 V
 V
 V
r   M
 M
 M
 M
 M
 4 M
 M
 M
`   N
 N
 N
 N
 N
"6 N
 N
 N
 N
 N
r0   