o
    	۷ia                     @   s   d dl mZmZmZ d dlZd dlmZ ddlmZ ddl	m
Z
mZ 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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!m"Z"m#Z#m$Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z* e$+e,Z-G dd dej.Z/G dd dej.Z0dd Z1d8ddZ2dej3de4dej3fddZ5	 		d9d!ej.d"ej3d#ej3d$ej3d%eej3 d&e6d'ee6 d(ee6 de7ej3ej3f fd)d*Z8G d+d, d,ej.Z9G d-d. d.eZ:G d/d0 d0ej.Z;e"G d1d2 d2eZ<e"G d3d4 d4e<Z=e"G d5d6 d6e<eZ>g d7Z?dS ):    )CallableOptionalUnionN   )ACT2FN)CacheDynamicCache)GenerationMixin)create_causal_mask!create_sliding_window_causal_mask)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuplelogging)deprecate_kwarg)check_model_inputs   )VaultGemmaConfigc                       s@   e Zd Zddedef fddZdd Zdd	 Zd
d Z  Z	S )VaultGemmaRMSNormư>dimepsc                    s&   t    || _tt|| _d S N)super__init__r    nn	Parametertorchzerosweight)selfr   r    	__class__ h/home/ubuntu/vllm_env/lib/python3.10/site-packages/transformers/models/vaultgemma/modeling_vaultgemma.pyr#   /   s   
zVaultGemmaRMSNorm.__init__c                 C   s$   |t |djddd| j  S )N   T)keepdim)r&   rsqrtpowmeanr    )r)   xr,   r,   r-   _norm4   s   $zVaultGemmaRMSNorm._normc                 C   s*   |  | }|d| j   }||S )Ng      ?)r5   floatr(   type_as)r)   r4   outputr,   r,   r-   forward7   s   
zVaultGemmaRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)tupler(   shaper    )r)   r,   r,   r-   
extra_repr>   s   zVaultGemmaRMSNorm.extra_repr)r   )
__name__
__module____qualname__intr6   r#   r5   r9   r<   __classcell__r,   r,   r*   r-   r   .   s
    r   c                       s$   e Zd Z fddZdd Z  ZS )VaultGemmaMLPc                    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)r"   r#   confighidden_sizeintermediate_sizer$   Linear	gate_projup_proj	down_projr   hidden_activationact_fnr)   rF   r*   r,   r-   r#   C   s   
zVaultGemmaMLP.__init__c                 C   s$   |  | | || | }|S r!   )rL   rN   rJ   rK   )r)   r4   rL   r,   r,   r-   r9   M   s    zVaultGemmaMLP.forward)r=   r>   r?   r#   r9   rA   r,   r,   r*   r-   rB   B   s    
rB   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/   r.   r   )r;   r&   cat)r4   x1x2r,   r,   r-   rotate_halfR   s   rT   c                 C   sD   | |}| |}| | t| |  }|| t||  }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )	unsqueezerT   )qkcossinposition_idsunsqueeze_dimq_embedk_embedr,   r,   r-   apply_rotary_pos_embY   s
   

r^   hidden_statesn_repreturnc                 C   s^   | j \}}}}|dkr| S | dddddddddf |||||} | ||| ||S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)r;   expandreshape)r_   r`   batchnum_key_value_headsslenhead_dimr,   r,   r-   	repeat_kvt   s
   0rh           modulequerykeyvalueattention_maskdropoutscalingsoftcapc                 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   r/   )r   dtype)ptrainingr   )rg   rh   num_key_value_groupsr&   matmul	transposetanhr;   r$   
functionalsoftmaxfloat32tort   ro   rv   
contiguous)rj   rk   rl   rm   rn   ro   rp   rq   kwargs
key_statesvalue_statesattn_weightscausal_maskattn_outputr,   r,   r-   eager_attention_forward   s"   

&r   c                       s   e Zd ZdZdedef fddZedddd		
	
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 )VaultGemmaAttentionz=Multi-headed attention from 'Attention Is All You Need' paperrF   	layer_idxc                    s   t    || _|| _t|d|j|j | _|j|j | _	|j
d | _| jj| _d| _tj|j|j| j |jd| _tj|j|j| j |jd| _tj|j|j| j |jd| _tj|j| j |j|jd| _| jj| _|j| dkry|j| _d S d | _d S )Nrg   rr   TrD   sliding_attention)r"   r#   rF   r   getattrrG   num_attention_headsrg   re   rw   query_pre_attn_scalarrp   attention_dropout	is_causalr$   rI   attention_biasq_projk_projv_projo_projattn_logit_softcappinglayer_typessliding_windowr)   rF   r   r*   r,   r-   r#      s,   


$zVaultGemmaAttention.__init__past_key_valuepast_key_values4.58new_nameversionNr_   position_embeddingsrn   cache_positionr   ra   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/   r   r.   )rY   rX   r   eagerri   )ro   rp   r   rq   )r;   rg   r   viewry   r   r   r^   updater   r   rF   _attn_implementationr   rv   r   rp   r   r   rc   r   r   )r)   r_   r   rn   r   r   r   input_shapehidden_shapequery_statesr   r   rX   rY   cache_kwargsattention_interfacer   r   r,   r,   r-   r9      s<   



zVaultGemmaAttention.forward)NN)r=   r>   r?   __doc__r   r@   r#   r   r&   Tensorr:   r   r   
LongTensorr   r   r9   rA   r,   r,   r*   r-   r      s*    r   c                       s   e Zd Zdedef fddZed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 )VaultGemmaDecoderLayerrF   r   c                    sd   t    |j| _|| _|j| | _t||d| _t|| _	t
|j|jd| _t
|j|jd| _d S )N)rF   r   r    )r"   r#   rG   rF   r   attention_typer   	self_attnrB   mlpr   rms_norm_epsinput_layernormpre_feedforward_layernormr   r*   r,   r-   r#      s   

zVaultGemmaDecoderLayer.__init__r   r   r   r   NFr_   r   rn   rZ   output_attentions	use_cacher   ra   c	                 K   st   |}
|  |}| jd||||||||d|	\}}|
| }|}
| |}| |}|
| }|f}|r8||f7 }|S )N)r_   r   rn   rZ   r   r   r   r   r,   )r   r   r   r   )r)   r_   r   rn   rZ   r   r   r   r   r   residualself_attn_weightsoutputsr,   r,   r-   r9      s.   
	



zVaultGemmaDecoderLayer.forward)NNNFFN)r=   r>   r?   r   r@   r#   r   r&   r   r:   r   r   r   boolFloatTensorr9   rA   r,   r,   r*   r-   r      s8    	r   c                       sD   e Zd ZU ejed< ddef fddZe e	dd Z
  ZS )	VaultGemmaRotaryEmbeddinginv_freqNrF   c                    s   t    t|drt|jtr|jd|jd| _nd| _|j| _	|j| _
|| _t| j | _| | j|\}| _| jd|dd | j| _d S )Nrope_scaling	rope_typetypedefaultr   F)
persistent)r"   r#   hasattr
isinstancer   dictgetr   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrF   r   rope_init_fnattention_scalingregister_bufferr   original_inv_freq)r)   rF   devicer   r*   r,   r-   r#   &  s   
z"VaultGemmaRotaryEmbedding.__init__c           
      C   s   | j d d d d f  |jd dd|j}|d d d d d f  }t|jjtr6|jjdkr6|jjnd}t	j
|dd+ | |  dd}t	j||fdd	}| | j }| | j }	W d    n1 smw   Y  |j|jd
|	j|jd
fS )Nr   r/   r   mpscpuF)device_typeenabledr.   rP   rt   )r   r6   rb   r;   r~   r   r   r   strr&   autocastry   rQ   rX   r   rY   rt   )
r)   r4   rZ   inv_freq_expandedposition_ids_expandedr   freqsembrX   rY   r,   r,   r-   r9   7  s   0&z!VaultGemmaRotaryEmbedding.forwardr!   )r=   r>   r?   r&   r   __annotations__r   r#   no_gradr   r9   rA   r,   r,   r*   r-   r   #  s   
 
r   c                       sX   e Zd ZU eed< dZdZdgZdgZdZ	dZ
dZdZdZeedZ fddZ  ZS )	VaultGemmaPreTrainedModelrF   modelTr   r   )r_   
attentionsc                    s,   t  | d|jjv r|jj  d S d S )NRMSNorm)r"   _init_weightsr+   r=   r(   datazero_)r)   rj   r*   r,   r-   r   Y  s   z'VaultGemmaPreTrainedModel._init_weights)r=   r>   r?   r   r   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraph_supports_attention_backendr   r   _can_record_outputsr   rA   r,   r,   r*   r-   r   G  s   
 r   c                       s   e Zd Zdef fddZe e									ddeej	 deej
 deej	 dee d	eej d
ee dee dee deej	 dee defddZ  ZS )VaultGemmaModelrF   c                    s   t     j| _ j| _t j j| j| _t	 fddt
 jD | _t j jd| _t d| _d| _|   d S )Nc                    s   g | ]}t  |qS r,   )r   ).0r   rF   r,   r-   
<listcomp>j  s    z,VaultGemmaModel.__init__.<locals>.<listcomp>r   r   F)r"   r#   pad_token_idpadding_idx
vocab_sizer$   	EmbeddingrG   embed_tokens
ModuleListrangenum_hidden_layerslayersr   r   normr   
rotary_embgradient_checkpointing	post_initrO   r*   r   r-   r#   c  s   zVaultGemmaModel.__init__N	input_idsrn   rZ   r   inputs_embedsr   r   output_hidden_statesr   r   ra   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| 	|}|rQ|d u rQ| jsQt
| j d}|	d u rm|d ur]| nd}tj|||jd  |jd}	|d u rv|	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   r   r   )r   )rF   input_embedsrn   r   r   rZ   )full_attentionr   g      ?r   r,   )r   rn   rZ   r   r   r   r   )last_hidden_stater   r_   r   )rF   r   r   r   
ValueErrorr   rv   loggerwarning_oncer   r   get_seq_lengthr&   aranger;   r   rU   r   r   r
   r   r   tensorrG   rt   r   r   r   r   r   )r)   r   rn   rZ   r   r   r   r   r   r   r   past_seen_tokenscausal_mask_mappingmask_kwargsr_   r   
normalizerall_hidden_statesall_self_attnsdecoder_layerlayer_outputsr,   r,   r-   r9   s  s   



	

zVaultGemmaModel.forward)	NNNNNNNNN)r=   r>   r?   r   r#   r   r   r   r&   r   r   r   r   r   r   r   r   r9   rA   r,   r,   r*   r-   r   a  sH    	
r   c                       s   e Zd ZdgZddiZddgdgfiZ fddZee												dd
e	e
j de	e
j de	e
j de	e de	e
j de	e
j de	e de	e de	e de	e
j deee
jf defddZ  ZS )VaultGemmaForCausalLMzlm_head.weightlm_headcolwise_repr_   logitsc                    s@   t  | t|| _|j| _tj|j|jdd| _| 	  d S rC   )
r"   r#   r   r   r   r$   rI   rG   r  r   rO   r*   r,   r-   r#     s
   
zVaultGemmaForCausalLM.__init__Nr   r   rn   rZ   r   r   labelsr   r   r   r   logits_to_keepra   c                 K   s   |dur|n| j j}|	dur|	n| j j}	| jd||||||||	|
d	|}|j}t|tr4t| dn|}| |dd|ddf }| j j	dur[|| j j	 }t
|}|| j j	 }d}|durm| j||| jfi |}t|||j|j|jdS )a  
        Example:

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

        >>> model = VaultGemmaForCausalLM.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?"
        ```N)	r   rn   rZ   r   r   r   r   r   r   )lossr  r   r_   r   r,   )rF   r   r   r   r  r   r@   slicer  final_logit_softcappingr&   rz   loss_functionr   r   r   r_   r   )r)   r   rn   rZ   r   r   r  r   r   r   r   r  r   r   r_   slice_indicesr  r  r,   r,   r-   r9     sB   #

zVaultGemmaForCausalLM.forward)NNNNNNNNNNr   )r=   r>   r?   _tied_weights_keys_tp_plan_pp_planr#   r   r   r   r&   r   r   r   r   r   r   r@   r   r9   rA   r,   r,   r*   r-   r    sV    		
r  )r  r   r   )Nr   )ri   NN)@typingr   r   r   r&   torch.nnr$   activationsr   cache_utilsr   r   
generationr	   masking_utilsr
   r   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   utils.deprecationr   utils.genericr   configuration_vaultgemmar   
get_loggerr=   r  Moduler   rB   rT   r^   r   r@   rh   r6   r:   r   r   r   r   r   r   r  __all__r,   r,   r,   r-   <module>   sp   



#K5$ Y