U
    ,-er                     @   sb  d 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mZ dd	lmZ dd
lmZ ddlmZmZmZmZm Z  ddl!m"Z" e rddl#m$Z$m%Z% ddl&m'Z'm(Z(m)Z) e*e+Z,dZ-dd Z.d<ej/ej0ej1e2dddZ3d=ej4ej0ee2 dddZ5G dd de	j6Z7e8e7 G dd de	j6Z9G dd de9Z:G dd  d e9Z;d!d" Z<d#d$ Z=G d%d& d&e	j6Z>ej4e2ej4d'd(d)Z?G d*d+ d+e	j6Z@G d,d- d-e@ZAG d.d/ d/e	j6ZBd0ZCed1eCG d2d3 d3eZDd4ZEed1eCG d5d6 d6eDZFG d7d8 d8eDZGed9eCG d:d; d;eDZHdS )>z PyTorch LLaMA model.    N)ListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)BaseModelOutputWithPastCausalLMOutputWithPast SequenceClassifierOutputWithPast)PreTrainedModel)ALL_LAYERNORM_LAYERS)add_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_availableloggingreplace_return_docstrings   )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int32ZnonzeroflattenmaxitemFpadcumsum)padding_maskZseqlens_in_batchindicesZmax_seqlen_in_batchZ
cu_seqlens r-   i/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/llama/modeling_llama.py_get_unpad_data6   s    r/   )input_ids_shaper    devicepast_key_values_lengthc                 C   s   | \}}t j||ft |j|d}t j|d|d}|||d |ddk d ||}|dkrt j	t j
||||d|gdd}|ddddddf |d||| S )zB
    Make causal mask used for bi-directional self-attention.
    r1   r   r   r   r    r1   r   N)r#   fullfinfominarangesizemasked_fill_viewtocatZzerosexpand)r0   r    r1   r2   bsztgt_lenmaskZ	mask_condr-   r-   r.   _make_causal_maskC   s    "
 rC   )rB   r    rA   c                 C   sj   |   \}}|dk	r|n|}| ddddddf |d|||}d| }||tjt|jS )z_
    Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
    Nr         ?)r:   r?   r=   Zmasked_fillr#   boolr7   r8   )rB   r    rA   r@   Zsrc_lenZexpanded_maskZinverted_maskr-   r-   r.   _expand_maskU   s
    *rF   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.   rJ   d   s    
zLlamaRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )N   r   T)Zkeepdim)	r    r=   r#   float32powmeanZrsqrtrN   rM   )rO   hidden_statesinput_dtypeZvariancer-   r-   r.   forwardl   s
    zLlamaRMSNorm.forward)rH   __name__
__module____qualname__rJ   rZ   __classcell__r-   r-   rR   r.   rG   c   s   rG   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 )NrD   r   rT   inv_freqF
persistentseq_lenr1   r    )rI   rJ   r   max_position_embeddingsbaser#   r9   floatr=   register_buffer_set_cos_sin_cacherc   r1   Zget_default_dtype)rO   r   rh   ri   r1   rc   rR   r-   r.   rJ   x   s    
*  zLlamaRotaryEmbedding.__init__c                 C   s   || _ tj| j || jjd}td|| j}tj||fdd}| jd| d d d d d d f 	|dd | jd|
 d d d d d d f 	|dd d S 	Nr1   r    i,j->ijr   r5   
cos_cachedFrd   
sin_cached)max_seq_len_cachedr#   r9   rc   r    einsumr>   rk   cosr=   sinrO   rg   r1   r    tfreqsembr-   r-   r.   rl      s    .z'LlamaRotaryEmbedding._set_cos_sin_cachec                 C   sn   || j kr| j||j|jd | jd d d d d |df j|jd| jd d d d d |df j|jdfS )Nrf   .)r    )rr   rl   r1   r    rp   r=   rq   )rO   xrg   r-   r-   r.   rZ      s
    
&&zLlamaRotaryEmbedding.forward)ra   rb   N)N)r\   r]   r^   rJ   rl   rZ   r_   r-   r-   rR   r.   r`   w   s   
r`   c                       s*   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/kaiokendevra   rb   NrD   c                    s   || _ t |||| d S Nscaling_factorrI   rJ   rO   r   rh   ri   r1   r~   rR   r-   r.   rJ      s    z*LlamaLinearScalingRotaryEmbedding.__init__c                 C   s   || _ tj| j || jjd}|| j }td|| j}tj||fdd}| jd|	 d d d d d d f 
|dd | jd| d d d d d d f 
|dd d S rm   )rr   r#   r9   rc   r    r~   rs   r>   rk   rt   r=   ru   rv   r-   r-   r.   rl      s    
.z4LlamaLinearScalingRotaryEmbedding._set_cos_sin_cache)ra   rb   NrD   r\   r]   r^   __doc__rJ   rl   r_   r-   r-   rR   r.   r{      s   r{   c                       s*   e Zd ZdZd
 fdd	Zdd	 Z  ZS )%LlamaDynamicNTKScalingRotaryEmbeddingzmLlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozillara   rb   NrD   c                    s   || _ t |||| d S r|   r}   r   rR   r-   r.   rJ      s    z.LlamaDynamicNTKScalingRotaryEmbedding.__init__c           	      C   s  || _ || jkrx| 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d	|| j
}tj||fd
d}| j	d| d d d d d d f |dd | j	d| d d d d d d f |dd d S )Nr   rT   rD   r   rc   Frd   rn   ro   r   r5   rp   rq   )rr   rh   ri   r~   r   r#   r9   rj   r=   rk   rc   r    rs   r>   rt   ru   )	rO   rg   r1   r    ri   rc   rw   rx   ry   r-   r-   r.   rl      s    
(.z8LlamaDynamicNTKScalingRotaryEmbedding._set_cos_sin_cache)ra   rb   NrD   r   r-   r-   rR   r.   r      s   r   c                 C   sH   | dd| j d d f }| d| j d d df }tj| |fddS )z*Rotates half the hidden dims of the input..Nr   rT   r5   )shaper#   r>   )rz   x1Zx2r-   r-   r.   rotate_half   s    r   c                 C   sl   | d d}| d d}|| d}|| d}| | t| |  }|| t||  }||fS )Nr   r   )squeeze	unsqueezer   )qkrt   ru   position_idsZq_embedZ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)rI   rJ   configrP   intermediate_sizer   Linear	gate_projup_proj	down_projr   Z
hidden_actact_fnrO   r   rR   r-   r.   rJ      s    
zLlamaMLP.__init__c                    s   | j jdkr| 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|}n | | | |  }|S )
Nr   r   r5   c                    s   g | ]}t  | qS r-   r(   linear.0i)gate_proj_slicesrz   r-   r.   
<listcomp>   s     z$LlamaMLP.forward.<locals>.<listcomp>r   c                    s   g | ]}t  | qS r-   r   r   )up_proj_slicesrz   r-   r.   r      s     rT   c                    s    g | ]}t |  | qS r-   r   r   )down_proj_slicesintermediate_statesr-   r.   r      s    )r   pretraining_tpr   r   rM   splitr   r   r#   r>   ranger   r"   )rO   rz   slicer   r   r   r-   )r   r   r   r   rz   r.   rZ      s"     &

 zLlamaMLP.forwardr[   r-   r-   rR   r.   r      s   
r   )rX   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   r?   reshape)rX   r   batchnum_key_value_headsslenhead_dimr-   r-   r.   	repeat_kv   s
    0r   c                       s   e Zd ZdZed fddZdd Zeje	e	ddd	Z
dejeej eej eeej  eeeej eejeej eeej  f dddZ  ZS )LlamaAttentionz=Multi-headed attention from 'Attention Is All You Need' paperr   c                    s  t    || _|j| _|j| _| j| j | _|j| _| j| j | _|j	| _	|j
| _
| j| j | jkrt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?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).r   )rI   rJ   r   rP   Znum_attention_heads	num_headsr   r   num_key_value_groupsrh   
rope_theta
ValueErrorr   r   Zattention_biasq_projk_projv_projo_proj
_init_roper   rR   r-   r.   rJ     s$    
zLlamaAttention.__init__c                 C   s   | j jd kr$t| j| j| jd| _nj| j jd }| j jd }|dkr^t| j| j|| jd| _n0|dkrt| j| j|| jd| _nt	d| d S )N)rh   ri   typefactorr   )rh   r~   ri   ZdynamiczUnknown RoPE scaling type )
r   Zrope_scalingr`   r   rh   r   
rotary_embr{   r   r   )rO   Zscaling_typer~   r-   r-   r.   r   !  s.    


zLlamaAttention._init_rope)tensorrg   r@   c                 C   s    | ||| j| jdd S )Nr   rT   )r<   r   r   	transpose
contiguous)rO   r   rg   r@   r-   r-   r.   _shape<  s    zLlamaAttention._shapeNFrX   attention_maskr   past_key_valueoutput_attentions	use_cacher+   r   c                    s    \}}	}
| 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 k	r||d jd
 7 }| j||d\}}t|||||\}}|d k	rtj|d |gd	d}tj|d |gd	d}|r||fnd }t|| j}t|| j}t||d	dt| j }|  || j|	|fkrltd|| j|	|f d|   |d k	r|  |d|	|fkrtd|d|	|f d|   || }tjj|dtjd|j}t||    || j|	| jfkrt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 )Nr   r   r5   c                    s   g | ]}t  | qS r-   r   r   )rX   query_slicesr-   r.   r   S  s     z*LlamaAttention.forward.<locals>.<listcomp>r   c                    s   g | ]}t  | qS r-   r   r   )rX   
key_slicesr-   r.   r   V  s     c                    s   g | ]}t  | qS r-   r   r   )rX   value_slicesr-   r.   r   Y  s     rT   rg   r
   z$Attention weights should be of size z	, but is z!Attention mask should be of size r   z `attn_output` should be of size c                    s    g | ]}t  | | qS r-   r   r   )attn_outputo_proj_slicesr-   r.   r     s     )$r:   r   r   r   r   r   rM   r   r   r   r   r   r#   r>   r<   r   r   r   r   r   r   matmulmathsqrtr   r   
functionalZsoftmaxrU   r=   r    r   r   rP   r   r"   )rO   rX   r   r   r   r   r   r+   r@   q_len_Zkey_value_slicingquery_states
key_statesvalue_states
kv_seq_lenrt   ru   attn_weightsr-   )r   rX   r   r   r   r   r.   rZ   ?  sv    
 





 
"
zLlamaAttention.forward)NNNFFN)r\   r]   r^   r   r   rJ   r   r#   Tensorintr   r   
LongTensorr   rE   rZ   r_   r-   r-   rR   r.   r     s(         r   c                   @   sz   e Zd ZdZdejeej eej eeej  e	e	eej eejeej eeej  f dddZ
ddd	Zd
d Zd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.
    NFr   c                 C   s  d}|  \}}	}
| |}| |}| |}|||	| j| jdd}|||	| j| jdd}|||	| j| jdd}|j	d }|d k	r||d j	d 7 }| j
||d\}}t|||||\}}|d k	rtj|d |gdd}tj|d |gdd}|r||fnd }|dd}|dd}|dd}d}|j}|tjkr~td	 |tj}|tj}|tj}| j|||||	|d
}|||	| j }| |}|sd }|||fS )NFr   rT   r   r   r   r5           zThe 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 float16.)dropout)r:   r   r   r   r<   r   r   r   r   r   r   r   r#   r>   r    rU   loggerwarning_oncer=   Zfloat16_flash_attention_forwardr   rP   r   r   )rO   rX   r   r   r   r   r   r+   r@   r   r   r   r   r   r   rt   ru   Zdropout_raterY   r   r   r-   r-   r.   rZ     sT    




     
zLlamaFlashAttention2.forwardr   c                 C   s   |dk	rl|j d }| |||||\}}}}	}
}|
\}}|\}}t|||||||||dd
}t||	||}nt|||||d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
            padding_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)
        Nr   T)cu_seqlens_qcu_seqlens_kZmax_seqlen_qZmax_seqlen_kZ	dropout_psoftmax_scalecausal)r   r   )r   _upad_inputr   r   r   )rO   r   r   r   r+   query_lengthr   r   
batch_size	indices_qZcu_seq_lensZmax_seq_lensr   r   max_seqlen_in_batch_qmax_seqlen_in_batch_kZattn_output_unpadr   r-   r-   r.   r     sB    
         z-LlamaFlashAttention2._flash_attention_forwardc                 C   s   t |\}}}|j\}	}
}}t||	|
 |||}t||	|
 |||}||
kr|t||	|
 | j||}|}|}|}nd|dkrd}tj|	d tj|jd}|d d }|	d}n(|d d | d f }t
||\}}}}||||||f||ffS )Nr   r4   r   )r/   r   r   r   r   r#   r9   r$   r1   r   r   )rO   Zquery_layerZ	key_layerZvalue_layerr+   r   Z	indices_kr   r   r   r   r   r   r   r   r   r-   r-   r.   r   *  sH         z LlamaFlashAttention2._upad_input)NNNFFN)r   N)r\   r]   r^   r   r#   r   r   r   r   rE   rZ   r   r   r-   r-   r-   r.   r     s*   	      P   
5r   c                       s   e Zd Zed fddZd	ejeej eej ee	ej  ee
 ee
 eej e	ejee	ejejf  f dddZ  ZS )
LlamaDecoderLayerr   c                    sf   t    |j| _t|dds(t|dnt|d| _t|| _t	|j|j
d| _t	|j|j
d| _d S )NZ_flash_attn_2_enabledFr   rQ   )rI   rJ   rP   getattrr   r   	self_attnr   mlprG   rms_norm_epsinput_layernormpost_attention_layernormr   rR   r-   r.   rJ   R  s    


zLlamaDecoderLayer.__init__NFr   c              	   C   sz   |}|  |}| j|||||||d\}}	}
|| }|}| |}| |}|| }|f}|rh||	f7 }|rv||
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, 1, tgt_len, src_len)` where padding elements are indicated by very large negative 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.
            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
        )rX   r   r   r   r   r   r+   )r   r   r   r   )rO   rX   r   r   r   r   r   r+   ZresidualZself_attn_weightsZpresent_key_valueoutputsr-   r-   r.   rZ   ^  s,    
	



zLlamaDecoderLayer.forward)NNNFFN)r\   r]   r^   r   rJ   r#   r   r   r   r   rE   FloatTensorrZ   r_   r-   r-   rR   r.   r   Q  s"         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                   @   s8   e Zd ZeZdZdZdgZdZdZ	dd Z
ddd	Zd
S )LlamaPreTrainedModelmodelTr   past_key_valuesc                 C   s|   | j j}t|tjr>|jjjd|d |jd k	rx|jj	  n:t|tj
rx|jjjd|d |jd k	rx|jj|j 	  d S )Nr   )rW   std)r   Zinitializer_range
isinstancer   r   rM   dataZnormal_r   Zzero_	Embeddingpadding_idx)rO   moduler   r-   r-   r.   _init_weights  s    

z"LlamaPreTrainedModel._init_weightsFc                 C   s   t |tr||_d S r|   )r   
LlamaModelgradient_checkpointing)rO   r   valuer-   r-   r.   _set_gradient_checkpointing  s    
z0LlamaPreTrainedModel._set_gradient_checkpointingN)F)r\   r]   r^   r   config_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_skip_keys_device_placementZ_supports_flash_attn_2r   r  r-   r-   r-   r.   r     s   r   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 (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            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)`) and 2 additional tensors of shape
            `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

            Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.

            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ed fddZdd Zdd Zd	d
 Ze	e
dejeej eej eeej  eej ee ee ee ee eeef d
ddZ  ZS )r   z
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]

    Args:
        config: LlamaConfig
    r   c                    sv   t     j| _ j| _t j j| j| _t	 fddt
 jD | _t j jd| _d| _|   d S )Nc                    s   g | ]}t  qS r-   )r   )r   r   r   r-   r.   r     s     z'LlamaModel.__init__.<locals>.<listcomp>r   F)rI   rJ   pad_token_idr   
vocab_sizer   r   rP   embed_tokensZ
ModuleListr   Znum_hidden_layerslayersrG   r   normr   	post_initr   rR   r   r.   rJ     s     zLlamaModel.__init__c                 C   s   | j S r|   r  rO   r-   r-   r.   get_input_embeddings  s    zLlamaModel.get_input_embeddingsc                 C   s
   || _ d S r|   r	  rO   r   r-   r-   r.   set_input_embeddings   s    zLlamaModel.set_input_embeddingsc                 C   s`   d }|d dkr$t ||j|j|d}|d k	r\t||j|d d|j}|d krT|n|| }|S )Nr   r   )r1   r2   )rA   )rC   r    r1   rF   r=   )rO   r   Zinput_shapeinputs_embedsr2   Zcombined_attention_maskZexpanded_attn_maskr-   r-   r.   _prepare_decoder_attention_mask$  s    z*LlamaModel._prepare_decoder_attention_maskN)
	input_idsr   r   r   r  r   r   output_hidden_statesreturn_dictr   c
              
      s   d k	r n| j j |d k	r |n| j j}|d k	r4|n| j j}|	d k	rH|	n| j j}	|d k	rj|d k	rjtdn2|d k	r~|j\}
}n|d k	r|j\}
}}ntd|}d}|d k	r|d d jd }|| }|d kr|d k	r|jn|j}tj	||| tj
|d}|dd|}n|d|
 }|d kr4| |}|d kr\tj|
|ftj|jd}d nd|krl|nd | ||
|f||}|}| jr| jr|rtd d}|rd	nd } rd	nd }|rd	nd }t| jD ]\}}|r||f7 }|d k	r
|| nd | jrH| jrH fd
d}tjj|||||}n|||| |d}|d }|r|| rzdnd f7 } r||d f7 }q| |}|r||f7 }|r|nd }|	stdd ||||fD S t||||dS )NzDYou cannot specify both input_ids and inputs_embeds at the same timez5You have to specify either input_ids or inputs_embedsr   rT   r4   r   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr-   c                    s    fdd}|S )Nc                     s    | fdiS )Nr+   r-   )inputs)r   r   r+   r   r-   r.   custom_forward  s    zILlamaModel.forward.<locals>.create_custom_forward.<locals>.custom_forwardr-   )r   r  r   r+   r   )r   r.   create_custom_forward  s    z1LlamaModel.forward.<locals>.create_custom_forward)r   r   r   r   r   r+   r   c                 s   s   | ]}|d k	r|V  qd S r|   r-   )r   vr-   r-   r.   	<genexpr>  s      z%LlamaModel.forward.<locals>.<genexpr>)Zlast_hidden_stater   rX   
attentions)r   r   r  r   use_return_dictr   r   r1   r#   r9   longr   r<   r  rL   rE   r  r   Ztrainingr   r   	enumerater  utils
checkpointr  tupler   )rO   r  r   r   r   r  r   r   r  r  r   Z
seq_lengthr   Zseq_length_with_pastr2   r1   rX   Zall_hidden_statesZall_self_attnsZnext_decoder_cacheidxZdecoder_layerr  Zlayer_outputsZ
next_cacher-   r  r.   rZ   ;  s    

   


  
   
   


zLlamaModel.forward)	NNNNNNNNN)r\   r]   r^   r   r   rJ   r  r  r  r   LLAMA_INPUTS_DOCSTRINGr#   r   r   r   r   r   rE   r   r   r   rZ   r_   r-   r-   rR   r.   r     s6            
r   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ejeej eej eeej  eej eej ee ee ee ee eeef d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   )
rI   rJ   r   r   r  r   r   rP   lm_headr  r   rR   r-   r.   rJ     s
    
zLlamaForCausalLM.__init__c                 C   s   | j jS r|   r   r  r
  r-   r-   r.   r    s    z%LlamaForCausalLM.get_input_embeddingsc                 C   s   || j _d S r|   r$  r  r-   r-   r.   r    s    z%LlamaForCausalLM.set_input_embeddingsc                 C   s   | j S r|   r#  r
  r-   r-   r.   get_output_embeddings  s    z&LlamaForCausalLM.get_output_embeddingsc                 C   s
   || _ d S r|   r%  )rO   Znew_embeddingsr-   r-   r.   set_output_embeddings  s    z&LlamaForCausalLM.set_output_embeddingsc                 C   s
   || _ d S r|   r   )rO   decoderr-   r-   r.   set_decoder  s    zLlamaForCausalLM.set_decoderc                 C   s   | j S r|   r(  r
  r-   r-   r.   get_decoder  s    zLlamaForCausalLM.get_decoder)output_typer  Nr  r   r   r   r  labelsr   r   r  r  r   c                    s  |dk	r|n| j j}|	dk	r |	n| j j}	|
dk	r4|
n| j j}
| j||||||||	|
d	}|d  | j jdkr| jjj| j	| j j dd fddt
| j jD }tj|dd}n
|  }| }d}|dk	r8|d	ddddf  }|d	ddf  }t }|d| j j	}|d}||j}|||}|
sh|f|dd  }|dk	rd|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)	r  r   r   r   r  r   r   r  r  r   r   r5   c                    s   g | ]}t  | qS r-   r   r   rX   Zlm_head_slicesr-   r.   r     s     z,LlamaForCausalLM.forward.<locals>.<listcomp>r   .losslogitsr   rX   r  )r   r   r  r  r   r   r#  rM   r   r  r   r#   r>   rj   r   r   r<   r=   r1   r   r   rX   r  )rO   r  r   r   r   r  r.  r   r   r  r  r   r2  r1  Zshift_logitsZshift_labelsloss_fctoutputr-   r/  r.   rZ     sR    )



zLlamaForCausalLM.forwardc                 K   s   |r|d d dd f }| dd }|d k	rp|d krp| dd }||dkd |rp|d d df d}|d k	r|d krd|i}nd|i}|||| d|d |S )	Nr   r   r   r   r  r  r   )r   r   r   r   )getr  r*   r;   r   update)rO   r  r   r   r  kwargsr   Z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)Zindex_selectr=   r1   )r   Z
past_statebeam_idxr-   r.   r  _  s     z2LlamaForCausalLM._reorder_cache.<locals>.<genexpr>)r  )r   r:  Zreordered_pastZ
layer_pastr-   r9  r.   _reorder_cacheZ  s    zLlamaForCausalLM._reorder_cache)
NNNNNNNNNN)NNN)r\   r]   r^   Z_tied_weights_keysrJ   r  r  r&  r'  r*  r+  r   r!  r   r   _CONFIG_FOR_DOCr#   r   r   r   r   r   rE   r   r   rZ   r8  staticmethodr;  r_   r-   r-   rR   r.   r"    sN   	
          
]     
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ej	e
ej e
ej	 e
eej  e
ej e
ej	 e
e e
e e
e e
e eeef dd	d
Z  ZS )LlamaForSequenceClassificationc                    s@   t  | |j| _t|| _tj|j| jdd| _| 	  d S r   )
rI   rJ   
num_labelsr   r   r   r   rP   scorer  r   rR   r-   r.   rJ   t  s
    
z'LlamaForSequenceClassification.__init__c                 C   s   | j jS r|   r$  r
  r-   r-   r.   r  }  s    z3LlamaForSequenceClassification.get_input_embeddingsc                 C   s   || j _d S r|   r$  r  r-   r-   r.   r    s    z3LlamaForSequenceClassification.set_input_embeddingsNr-  c                 C   s(  |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}|dk	rV|jd }n
|jd }| j jdkr||dkr|td| j jdkrd}n4|dk	rt|| j j	 
dd |j}nd}|tj||jd|f }d}|dk	r||j}| j jdkrR| jdkrd| j _n:| jdkrJ|jtj	ks@|jtjkrJd	| j _nd
| j _| j jdkrt }| jdkr|| | }n
|||}nN| j jd	krt }||d| j|d}n| j jd
krt }|||}|
s|f|dd  }|dk	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)r   r   r   r  r   r   r  r  r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r   r3   Z
regressionZsingle_label_classificationZmulti_label_classificationr0  )r   r  r   r@  r   r  r   r#   eqr  Zargmaxr=   r1   r9   Zproblem_typer?  r    r   r	   r   r   r<   r   r   r   rX   r  )rO   r  r   r   r   r  r.  r   r   r  r  Ztransformer_outputsrX   r2  r   Zsequence_lengthsZpooled_logitsr1  r3  r4  r-   r-   r.   rZ     sr    



(

z&LlamaForSequenceClassification.forward)
NNNNNNNNNN)r\   r]   r^   rJ   r  r  r   r!  r#   r   r   r   r   r   rE   r   r   r   rZ   r_   r-   r-   rR   r.   r>  d  s6   	          
r>  )r   )N)Ir   r   typingr   r   r   r   r#   Ztorch.nn.functionalr   r   r(   Ztorch.utils.checkpointZtorch.nnr   r   r	   Zactivationsr   Zmodeling_outputsr   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r  r   r   r   r   r   Zconfiguration_llamar   Z
flash_attnr   r   Zflash_attn.bert_paddingr   r   r   Z
get_loggerr\   r   r<  r/   Sizer    r1   r   rC   r   rF   ModulerG   appendr`   r{   r   r   r   r   r   r   r   r   ZLLAMA_START_DOCSTRINGr   r!  r   r"  r>  r-   r-   r-   r.   <module>   sz   
    
$"  3F@ 9 %