o
    wib                     @   s  d dl mZmZmZ d dlZd dlmZ d dlZddlm	Z	 ddl
mZmZ ddlmZmZ ddlmZmZ ddlmZ dd	lmZ dd
lmZmZ ddl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(m)Z)m*Z*m+Z+ e,e-Z.G dd deZ/G dd de)Z0G dd de'Z1			d0dej2dej3dej3dej3deej3 de4dee4 dee4 d e5ej3ej3f fd!d"Z6G d#d$ d$e#Z7G d%d& d&eZ8G d'd( d(e(Z9G d)d* d*e$Z:G d+d, d,e%Z;G d-d. d.e&Z<g d/Z=dS )1    )CallableOptionalUnionN   )ACT2FN)CacheDynamicCache)PretrainedConfiglayer_type_validation)create_causal_mask!create_sliding_window_causal_mask)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPast)ALL_ATTENTION_FUNCTIONS)Unpack)logging)deprecate_kwarg   )	GemmaAttentionGemmaForCausalLMGemmaForSequenceClassificationGemmaForTokenClassificationGemmaMLP
GemmaModelGemmaRMSNormapply_rotary_pos_emb	repeat_kvc                       s   e Zd ZdZdZdgZddddddddZdgdgfd	d
gd	gfd	gd	gfdZ																							 	!d$ fd"d#	Z  Z	S )%Gemma2Configa  
    This is the configuration class to store the configuration of a [`Gemma2Model`]. It is used to instantiate an Gemma2
    model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
    defaults will yield a similar configuration to that of the Gemma2-7B.
    e.g. [google/gemma2-7b](https://huggingface.co/google/gemma2-7b)
    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information.
    Args:
        vocab_size (`int`, *optional*, defaults to 256000):
            Vocabulary size of the Gemma2 model. Defines the number of different tokens that can be represented by the
            `inputs_ids` passed when calling [`Gemma2Model`]
        hidden_size (`int`, *optional*, defaults to 2304):
            Dimension of the hidden representations.
        intermediate_size (`int`, *optional*, defaults to 9216):
            Dimension of the MLP representations.
        num_hidden_layers (`int`, *optional*, defaults to 26):
            Number of hidden layers in the Transformer decoder.
        num_attention_heads (`int`, *optional*, defaults to 8):
            Number of attention heads for each attention layer in the Transformer decoder.
        num_key_value_heads (`int`, *optional*, defaults to 4):
            This is the number of key_value heads that should be used to implement Grouped Query Attention. If
            `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
            `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
            converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
            by meanpooling all the original heads within that group. For more details, check out [this
            paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
            `num_attention_heads`.
        head_dim (`int`, *optional*, defaults to 256):
            The attention head dimension.
        hidden_activation (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
            The non-linear activation function (function or string) in the decoder. Will default to `"gelu_pytorch_tanh"`
            if not specified. `"gelu_pytorch_tanh"` uses an approximation of the `"gelu"` activation function.
        max_position_embeddings (`int`, *optional*, defaults to 8192):
            The maximum sequence length that this model might ever be used with.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        rms_norm_eps (`float`, *optional*, defaults to 1e-06):
            The epsilon used by the rms normalization layers.
        use_cache (`bool`, *optional*, defaults to `True`):
            Whether or not the model should return the last key/values attentions (not used by all models). Only
            relevant if `config.is_decoder=True`.
        pad_token_id (`int`, *optional*, defaults to 0):
            Padding token id.
        eos_token_id (`int`, *optional*, defaults to 1):
            End of stream token id.
        bos_token_id (`int`, *optional*, defaults to 2):
            Beginning of stream token id.
        tie_word_embeddings (`bool`, *optional*, defaults to `True`):
            Whether to tie weight embeddings
        rope_theta (`float`, *optional*, defaults to 10000.0):
            The base period of the RoPE embeddings.
        attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
            Whether to use a bias in the query, key, value and output projection layers during self-attention.
        attention_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the attention probabilities.
        query_pre_attn_scalar (`float`, *optional*, defaults to 256):
            scaling factor used on the attention scores
        sliding_window (`int`, *optional*, defaults to 4096):
            in Gemma2, every other layer uses sliding window attention. This is the size of the sliding window.
        layer_types (`list`, *optional*):
            Attention pattern for each layer.
        final_logit_softcapping (`float`, *optional*, defaults to 30.0):
            scaling factor when applying tanh softcapping on the logits.
        attn_logit_softcapping (`float`, *optional*, defaults to 50.0):
            scaling factor when applying tanh softcapping on the attention scores.

    ```python
    >>> from transformers import Gemma2Model, Gemma2Config
    >>> # Initializing a Gemma2 gemma2-7b style configuration
    >>> configuration = Gemma2Config()
    >>> # Initializing a model from the gemma2-7b style configuration
    >>> model = Gemma2Model(configuration)
    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```gemma2past_key_valuescolwiserowwise)zlayers.*.self_attn.q_projzlayers.*.self_attn.k_projzlayers.*.self_attn.v_projzlayers.*.self_attn.o_projzlayers.*.mlp.gate_projzlayers.*.mlp.up_projzlayers.*.mlp.down_proj	input_idsinputs_embedshidden_statesattention_mask)embed_tokenslayersnorm   	   $              gelu_pytorch_tanh    {Gz?ư>Tr      r        @F           N      >@      I@c                    s   t  jd||||d| || _|	| _|| _|| _|| _|| _|| _|| _	|
| _
|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _| jd u rZdd t| jD | _t| j d S )N)pad_token_idbos_token_ideos_token_idtie_word_embeddingsc                 S   s$   g | ]}t |d  d rdndqS )r6   r   sliding_attentionfull_attention)bool).0i rE   f/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/transformers/models/gemma2/modular_gemma2.py
<listcomp>   s    z)Gemma2Config.__init__.<locals>.<listcomp>rE   )super__init__
vocab_sizemax_position_embeddingshidden_sizeintermediate_sizenum_hidden_layersnum_attention_headshead_dimnum_key_value_headsinitializer_rangerms_norm_eps	use_cache
rope_thetaattention_biasattention_dropouthidden_activationquery_pre_attn_scalarsliding_windowfinal_logit_softcappingattn_logit_softcappinglayer_typesranger
   )selfrJ   rL   rM   rN   rO   rQ   rP   rX   rK   rR   rS   rT   r<   r>   r=   r?   rU   rV   rW   rY   rZ   r]   r[   r\   kwargs	__class__rE   rF   rI      sB   
zGemma2Config.__init__)r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   Tr   r6   r   Tr7   Fr8   r1   r9   Nr:   r;   )
__name__
__module____qualname____doc__
model_typekeys_to_ignore_at_inferencebase_model_tp_planbase_model_pp_planrI   __classcell__rE   rE   ra   rF   r   1   sR    L


r   c                   @   s   e Zd ZdS )Gemma2RMSNormN)rc   rd   re   rE   rE   rE   rF   rl      s    rl   c                          e Zd Z fddZ  ZS )	Gemma2MLPc                    s   t    t|j | _d S N)rH   rI   r   rX   act_fnr_   configra   rE   rF   rI      s   
zGemma2MLP.__init__rc   rd   re   rI   rk   rE   rE   ra   rF   rn          rn   r8   modulequerykeyvaluer'   dropoutscalingsoftcapreturnc                 K   s   |d u r	| j d }t|| j}	t|| j}
t||	dd| }|d ur2|| }t|}|| }|d urM|d d d d d d d |	jd f }|| }tj	j
|dtjd|j}tj	j||| jd}t||
}|dd }||fS )	N      r   r   )dimdtype)ptrainingr6   )rP   r   num_key_value_groupstorchmatmul	transposetanhshapenn
functionalsoftmaxfloat32tor   ry   r   
contiguous)ru   rv   rw   rx   r'   ry   rz   r{   r`   
key_statesvalue_statesattn_weightscausal_maskattn_outputrE   rE   rF   eager_attention_forward   s"   

&r   c                       s   e Zd Zdedef fddZ		ddejdeejejf de	ej d	e	e
 d
e	ej dee deeje	ej e	eej  f fddZ  ZS )Gemma2Attentionrr   	layer_idxc                    sX   t  || | jj| _| jj| _d| _|jd | _|j| dkr'|j	| _	d S d | _	d S )NTr}   r@   )
rH   rI   rr   r\   rW   	is_causalrY   rz   r]   rZ   r_   rr   r   ra   rE   rF   rI      s   

$zGemma2Attention.__init__Nr&   position_embeddingsr'   past_key_valuecache_positionr`   r|   c                 K   s,  |j d d }g |d| jR }| ||dd}	| ||dd}
| ||dd}|\}}t|	|
||\}	}
|d urW|||d}||
|| j	|\}
}t
}| jjdkret| jj }|| |	|
||f| jrr| jnd| j| j| jd|\}}|jg |dR   }| |}||fS )Nr   r6   r   )sincosr   eagerr8   )ry   rz   rZ   r{   )r   rP   q_projviewr   k_projv_projr   updater   r   rr   _attn_implementationr   r   rW   rz   rZ   r\   reshaper   o_proj)r_   r&   r   r'   r   r   r`   input_shapehidden_shapequery_statesr   r   r   r   cache_kwargsattention_interfacer   r   rE   rE   rF   forward  s<   	


zGemma2Attention.forward)NN)rc   rd   re   r   intrI   r   Tensortupler   r   
LongTensorr   r   r   rk   rE   rE   ra   rF   r      s&    r   c                       s   e Zd Zdedef fddZeddd								dd
ejde	ejejf de
ej de
ej de
e de
e de
e de
ej de	eje
e	ejejf  f fddZ  ZS )Gemma2DecoderLayerrr   r   c                    s   t    |j| _|| _|j| | _t||d| _t|| _	t
|j|jd| _t
|j|jd| _t
|j|jd| _t
|j|jd| _d S )N)rr   r   )eps)rH   rI   rL   rr   r]   attention_typer   	self_attnrn   mlprl   rS   input_layernormpost_attention_layernormpre_feedforward_layernormpost_feedforward_layernormr   ra   rE   rF   rI   3  s   

zGemma2DecoderLayer.__init__last_cache_positionz4.53.0)versionNFr&   r   r'   position_idsr   output_attentionsrT   r   r|   c	                 K   s   |}
|  |}| jd||||||||d|	\}}| |}|
| }|}
| |}| |}| |}|
| }|f}|rB||f7 }|S )N)r&   r   r'   r   r   r   rT   r   rE   )r   r   r   r   r   r   )r_   r&   r   r'   r   r   r   rT   r   r`   residualself_attn_weightsoutputsrE   rE   rF   r   @  s2   
	





zGemma2DecoderLayer.forward)NNNFFN)rc   rd   re   r   r   rI   r   r   r   r   r   r   r   rB   FloatTensorr   rk   rE   rE   ra   rF   r   2  s8    
	r   c                       s   e Zd Zdef fddZ									ddeej deej deej dee	 d	eej
 d
ee dee dee deej dee defddZ  ZS )Gemma2Modelrr   c                    s0   t    t fddt jD | _d S )Nc                    s   g | ]}t  |qS rE   )r   )rC   r   rr   rE   rF   rG   r  s    z(Gemma2Model.__init__.<locals>.<listcomp>)rH   rI   r   
ModuleListr^   rN   r)   rq   ra   r   rF   rI   o  s   
zGemma2Model.__init__Nr$   r'   r   r!   r%   rT   r   output_hidden_statesr   flash_attn_kwargsr|   c
                 K   s  |d ur|n| j j}|d ur|n| j j}|d ur|n| j j}|d u |d uA r*td| jr9| jr9|r9td d}|d u rB| 	|}|rN|d u rN| jsNt
 }|	d u rj|d urZ| nd}tj|||jd  |jd}	|d u rs|	d}t| }ts| j |||	||d}tdi |tdi |d}|}| ||}tj| j jd	 |jd
}|| }|rdnd }|rdnd }| jd | j j D ])}|r||f7 }||f|||j |||||	d|
}|d }|r||d f7 }q| |}|r||f7 }t||||dS )Nz:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.Fr   r6   )device)rr   input_embedsr'   r   r!   r   )rA   r@   g      ?)r   rE   )r   r'   r   r   r   rT   r   )last_hidden_stater!   r&   
attentions)rr   r   r   rT   
ValueErrorgradient_checkpointingr   loggerwarning_oncer(   r   get_seq_lengthr   aranger   r   	unsqueeze
isinstancedictr   r   
rotary_embtensorrL   r   r)   rN   r   r*   r   )r_   r$   r'   r   r!   r%   rT   r   r   r   r   past_seen_tokenscausal_mask_mappingmask_kwargsr&   r   
normalizerall_hidden_statesall_self_attnsdecoder_layerlayer_outputsrE   rE   rF   r   u  s   



	

zGemma2Model.forward)	NNNNNNNNN)rc   rd   re   r   rI   r   r   r   r   r   r   rB   r   r   r   r   rk   rE   rE   ra   rF   r   n  sD    	
r   c                       s   e Zd Z fddZ											ddeej deej deej dee d	eej	 d
eej dee
 dee
 dee
 deej deeejf defddZ  ZS )Gemma2ForCausalLMc                    "   t  | t|| _|   d S ro   rH   rI   r   model	post_initrq   ra   rE   rF   rI        
zGemma2ForCausalLM.__init__Nr   r$   r'   r   r!   r%   labelsrT   r   r   r   logits_to_keepr|   c                 K   s  | j r| jjdkrtd| jj d |dur|n| jj}|	dur$|	n| jj}	| jd||||||||	|
d	|}|j}t	|t
rHt| dn|}| |dd|ddf }| jjduro|| jj }t|}|| jj }d}|dur| j||| jfi |}t|||j|j|jdS )a  
        Example:

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

        >>> model = Gemma2ForCausalLM.from_pretrained("google/gemma-2-9b")
        >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-9b")

        >>> prompt = "What is your favorite condiment?"
        >>> inputs = tokenizer(prompt, return_tensors="pt")

        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "What is your favorite condiment?"
        ```r   zhIt is strongly recommended to train Gemma2 models with the `eager` attention implementation instead of `zp`. Use `eager` with `AutoModelForCausalLM.from_pretrained('<path-to-checkpoint>', attn_implementation='eager')`.N)	r$   r'   r   r!   r%   rT   r   r   r   )losslogitsr!   r&   r   rE   )r   rr   r   r   r   r   r   r   r   r   r   slicelm_headr[   r   r   loss_functionrJ   r   r!   r&   r   )r_   r$   r'   r   r!   r%   r   rT   r   r   r   r   loss_kwargsr   r&   slice_indicesr   r   rE   rE   rF   r     sN   !

zGemma2ForCausalLM.forward)NNNNNNNNNNr   )rc   rd   re   rI   r   r   r   r   r   r   rB   r   r   r   r   rk   rE   rE   ra   rF   r     sL    	
r   c                       rm   )Gemma2ForSequenceClassificationc                    r   ro   r   rq   ra   rE   rF   rI   8  r   z(Gemma2ForSequenceClassification.__init__rs   rE   rE   ra   rF   r   7  rt   r   c                       rm   )Gemma2ForTokenClassificationc                    r   ro   r   rq   ra   rE   rF   rI   ?  r   z%Gemma2ForTokenClassification.__init__rs   rE   rE   ra   rF   r   >  rt   r   )r   r   r   Gemma2PreTrainedModelr   r   )r8   NN)>typingr   r   r   r   torch.nnr   torch.utils.checkpointactivationsr   cache_utilsr   r   configuration_utilsr	   r
   masking_utilsr   r   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   modeling_utilsr   processing_utilsr   utilsr   utils.deprecationr   gemma.modeling_gemmar   r   r   r   r   r   r   r   r   
get_loggerrc   r   r   rl   rn   Moduler   floatr   r   r   r   r   r   r   r   __all__rE   rE   rE   rF   <module>   sd   ,
 

#7<uT