
     `i`c                        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mZ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&j-        e.          Z/ G d dej0                  Z1 G d dej0                  Z2 G d dej0                  Z3d Z4d8dZ5dej6        de7dej6        fdZ8	 	 	 d9d ej0        d!ej6        d"ej6        d#ej6        d$eej6                 d%e9d&ee9         d'ee9         de:ej6        ej6        f         fd(Z; G d) d*ej0                  Z< G d+ d,e          Z=e$ G d- d.e                      Z>e$ G d/ d0e>                      Z?e$ G d1 d2e>e                      Z@ G d3 d4ee>          ZA G d5 d6ee>          ZBg d7ZCdS ):    )CallableOptionalUnionN   )ACT2FN)CacheDynamicCache)GenerationMixin)create_causal_mask!create_sliding_window_causal_mask)FlashAttentionKwargs) GenericForSequenceClassificationGenericForTokenClassification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   )Gemma2Configc                   <     e Zd Zddedef fdZd Zd Zd Z xZ	S )	Gemma2RMSNormư>dimepsc                     t                                                       || _        t          j        t          j        |                    | _        d S N)super__init__r$   nn	Parametertorchzerosweight)selfr#   r$   	__class__s      ~/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/transformers/models/gemma2/modeling_gemma2.pyr(   zGemma2RMSNorm.__init__3   s?    l5;s#3#344    c                     |t          j        |                    d                              dd          | j        z             z  S )N   T)keepdim)r+   rsqrtpowmeanr$   )r.   xs     r0   _normzGemma2RMSNorm._norm8   s8    5;quuQxx}}R}>>IJJJJr1   c                     |                      |                                          }|d| j                                        z   z  }|                    |          S )Ng      ?)r:   floatr-   type_as)r.   r9   outputs      r0   forwardzGemma2RMSNorm.forward;   sL    AGGII&& 3!2!2!4!445~~a   r1   c                 H    t          | j        j                   d| j         S )Nz, eps=)tupler-   shaper$   )r.   s    r0   
extra_reprzGemma2RMSNorm.extra_reprB   s%    )**<<$(<<<r1   )r"   )
__name__
__module____qualname__intr<   r(   r:   r?   rC   __classcell__r/   s   @r0   r!   r!   2   s        5 5C 5e 5 5 5 5 5 5
K K K! ! != = = = = = =r1   r!   c                   $     e Zd Z fdZd Z xZS )	Gemma2MLPc                    t                                                       || _        |j        | _        |j        | _        t          j        | j        | j        d          | _        t          j        | j        | j        d          | _        t          j        | j        | j        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.   rP   r/   s     r0   r(   zGemma2MLP.__init__G   s    !-!'!94#3T5KRWXXXy!143IPUVVV4#94;KRWXXXV56r1   c                     |                      |                     |                     |                    |                     |          z            }|S r&   )rV   rX   rT   rU   )r.   r9   rV   s      r0   r?   zGemma2MLP.forwardQ   sA    NN4;;t~~a/@/@#A#ADLLQROO#STT	r1   )rD   rE   rF   r(   r?   rH   rI   s   @r0   rK   rK   F   sG        7 7 7 7 7      r1   rK   c                   |     e Zd ZU ej        ed<   ddef fdZ ej                    e	d                         Z
 xZS )Gemma2RotaryEmbeddinginv_freqNrP   c                    t                                                       t          |d          rSt          |j        t
                    r9|j                            d|j                            d                    | _        nd| _        |j        | _	        |j        | _
        || _        t          | j                 | _        |                     | j        |          \  }| _        |                     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_lenrP   r   rope_init_fnattention_scalingregister_bufferr]   original_inv_freq)r.   rP   devicer]   r/   s       r0   r(   zGemma2RotaryEmbedding.__init__Y   s    6>** 	'z&:Mt/T/T 	'#044[&BUBYBYZ`BaBabbDNN&DN"("@$*$B!/?+/+<+<T[&+Q+Q($(ZeDDD!%r1   c                 X   | j         d d d d f                                                             |j        d         dd                              |j                  }|d d d d d f                                         }t          |j        j        t                    r|j        j        dk    r|j        j        nd}t          j
        |d          5  |                                |                                z                      dd          }t          j        ||fd	          }|                                | j        z  }|                                | j        z  }	d d d            n# 1 swxY w Y   |                    |j        
          |	                    |j        
          fS )Nr   r4   r   mpscpuF)device_typeenabledr3   r#   dtype)r]   r<   expandrB   toro   re   ra   strr+   autocast	transposecatcosrl   sinrw   )
r.   r9   position_idsinv_freq_expandedposition_ids_expandedrs   freqsembr~   r   s
             r0   r?   zGemma2RotaryEmbedding.forwardj   s    !M$4-8>>@@GGHZ[\H]_acdeehhijiqrr ,QQQaaaZ 8 > > @ @'1!(-'E'Ek!(-[`J`J`ahmmfk^UCCC 	5 	5&,,..1F1L1L1N1NNYYZ[]^__E)UEN333C''))d44C''))d44C		5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 vvAGv$$cff17f&;&;;;s   BE++E/2E/r&   )rD   rE   rF   r+   Tensor__annotations__r   r(   no_gradr   r?   rH   rI   s   @r0   r\   r\   V   s         l/ /| / / / / / /" U]__< <  _< < < < <r1   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..Nr4   r3   ru   )rB   r+   r}   )r9   x1x2s      r0   rotate_halfr   z   s]    	
3"!'"+"""	#B	
3q """	#B9rc2YB''''r1   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   r   unsqueeze_dimq_embedk_embeds           r0   apply_rotary_pos_embr      sc    ( --
&
&C
--
&
&C3w;q>>C/0G3w;q>>C/0GGr1   hidden_states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)rB   rx   reshape)r   r   batchnum_key_value_headsslenhead_dims         r0   	repeat_kvr      s    
 2?1D.Ehzz!!!!QQQaaa"23::5BUW\^bdlmmM  (;e(CT8TTTr1           modulequerykeyvalueattention_maskdropoutscalingsoftcapc                    |
| j         dz  }t          || j                  }	t          || j                  }
t          j        ||	                    dd                    |z  }|||z  }t          j        |          }||z  }|$|d d d d d d d |	j        d         f         }||z   }t          j	        
                    |dt          j                                      |j                  }t          j	                            ||| j                  }t          j        ||
          }|                    dd                                          }||fS )	N      r3   r   r4   )r#   rw   )ptrainingr   )r   r   num_key_value_groupsr+   matmulr|   tanhrB   r)   
functionalsoftmaxfloat32ry   rw   r   r   
contiguous)r   r   r   r   r   r   r   r   kwargs
key_statesvalue_statesattn_weightscausal_maskattn_outputs                 r0   eager_attention_forwardr      sR    /4'3 ;<<JUF$?@@L<z';';Aq'A'ABBWLL#g-z,//#g-!$QQQ111.D
0@0D.D%DE#k1 =((2U](SSVVW\WbccL=((6?([[L,|\::K''1--88::K$$r1   c                   D    e Zd ZdZdedef fdZ e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            Z xZS )Gemma2Attentionz=Multi-headed attention from 'Attention Is All You Need' paperrP   	layer_idxc                    t                                                       || _        || _        t	          |d|j        |j        z            | _        |j        |j        z  | _	        |j
        d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                  | _        | j        j        | _        |j        |         dk    r|j        nd | _        d S )Nr   r   TrN   sliding_attention)r'   r(   rP   r   getattrrQ   num_attention_headsr   r   r   query_pre_attn_scalarr   attention_dropout	is_causalr)   rS   attention_biasq_projk_projv_projo_projattn_logit_softcappinglayer_typessliding_windowr.   rP   r   r/   s      r0   r(   zGemma2Attention.__init__   sz   "
F4F&Jd4dee$*$>&B\$\!3T9!%!>i :T] JQWQf
 
 
 i :T] JQWQf
 
 
 i :T] JQWQf
 
 
 i&68JQWQf
 
 
 '+k&H#7=7I)7TXk7k7kf33qur1   past_key_valuepast_key_values4.58new_nameversionNr   position_embeddingsr   cache_positionr   r   c                 \   |j         d d         }g |d| j        R }|                     |                              |                              dd          }	|                     |                              |                              dd          }
|                     |                              |                              dd          }|\  }}t          |	|
||          \  }	}
|&|||d}|                    |
|| j	        |          \  }
}t          }| j        j        dk    rt          | j        j                 } || |	|
||f| j        r| j        nd| j        | j        | j        d|\  }} |j        g |dR                                  }|                     |          }||fS )Nr4   r   r3   )r   r~   r   eagerr   )r   r   r   r   )rB   r   r   viewr|   r   r   r   updater   r   rP   _attn_implementationr   r   r   r   r   r   r   r   r   )r.   r   r   r   r   r   r   input_shapehidden_shapequery_statesr   r   r~   r   cache_kwargsattention_interfacer   r   s                     r0   r?   zGemma2Attention.forward   s    $)#2#.88b8$-88{{=1166|DDNNqRSTT[[//44\BBLLQPQRR
{{=1166|DDNNqRSTT&S#7jRUWZ#[#[ j&#&snUUL'6'='=j,X\Xfht'u'u$J(?;+w66"9$+:Z"[$7$7%
 /3mDD**L./%
 %
 %
 %
!\ *k);;;;;;FFHHkk+..L((r1   )NN)rD   rE   rF   __doc__r   rG   r(   r   r+   r   rA   r   r   
LongTensorr   r   r?   rH   rI   s   @r0   r   r      s)       GGv| v v v v v v v2 _%0A6RRR ,059+) +)|+) #5<#=>+) !.	+)
 "%+) !!12+) -.+) 
u|Xel3XeEL>Q5RR	S+) +) +) SR+) +) +) +) +)r1   r   c                   h    e Zd Zdedef f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            Z xZS )Gemma2DecoderLayerrP   r   c                    t                                                       |j        | _        || _        |j        |         | _        t          ||          | _        t          |          | _	        t          |j        |j                  | _        t          |j        |j                  | _        t          |j        |j                  | _        t          |j        |j                  | _        d S )N)rP   r   r$   )r'   r(   rQ   rP   r   attention_typer   	self_attnrK   mlpr!   rms_norm_epsinput_layernormpost_attention_layernormpre_feedforward_layernormpost_feedforward_layernormr   s      r0   r(   zGemma2DecoderLayer.__init__  s    !-$0;()LLLV$$,V-?VEXYYY(5f6HfNa(b(b(b%)6v7IvOb)c)c)c&*78JPVPc*d*d*d'''r1   r   r   r   r   NFr   r   r   r   output_attentions	use_cacher   r   c	                 <   |}
|                      |          } | j        d||||||||d|	\  }}|                     |          }|
|z   }|}
|                     |          }|                     |          }|                     |          }|
|z   }|f}|r||fz  }|S )N)r   r   r   r   r   r   r   r    )r   r   r   r   r   r   )r.   r   r   r   r   r   r   r   r   r   residualself_attn_weightsoutputss                r0   r?   zGemma2DecoderLayer.forward$  s     !,,];; ,:4> 
,
' 3)%+/)
,
 
,
 
,
 
,
(( 55mDD =0 66}EE//77FF =0 " 	,)++Gr1   )NNNFFN)rD   rE   rF   r   rG   r(   r   r+   r   rA   r   r   r   boolFloatTensorr?   rH   rI   s   @r0   r   r     sN       e| e e e e e e e _%0A6RRR
 2637+/,1$)59* *|* #5<#=>* !.	*
 u/0* "%* $D>* D>* !!12* 
u (51BEDU1U+V"WW	X* * * SR* * * * *r1   r   c                   \     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Z xZS )Gemma2PreTrainedModelrP   modelTr   r   )r   
attentionsc                     t                                          |           d|j        j        v r |j        j                                         d S d S )NRMSNorm)r'   _init_weightsr/   rD   r-   datazero_)r.   r   r/   s     r0   r   z#Gemma2PreTrainedModel._init_weightsd  sS    f%%% (111M$$&&&&& 21r1   )rD   rE   rF   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   rH   rI   s   @r0   r   r   R  s         &*#-.#4"5N!"&+% 
' ' ' ' ' ' ' ' 'r1   r   c                   6    e Zd Zdef f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                        Z xZS )Gemma2ModelrP   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   ).0r   rP   s     r0   
<listcomp>z(Gemma2Model.__init__.<locals>.<listcomp>u  s$    dddy	22dddr1   r   rP   F)r'   r(   pad_token_idpadding_idx
vocab_sizer)   	EmbeddingrQ   embed_tokens
ModuleListrangenum_hidden_layerslayersr!   r   normr\   
rotary_embgradient_checkpointing	post_initrY   s    `r0   r(   zGemma2Model.__init__n  s       !. +L):F<NPTP`aamddddE&JbDcDcddd
 
 "&"4&:MNNN	/v>>>&+# 	r1   N	input_idsr   r   r   inputs_embedsr   r   output_hidden_statesr   r   r   c
                 8   ||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}|| 	                    |          }|r|| j        st          | j                   }|	B||                                nd}t          j        |||j        d         z   |j                  }	||	                    d          }t#          |x}t$                    s'| j         |||	||d}t'          di |t)          di |d	}|}|                     ||          }t          j        | j         j        d
z  |j                  }||z  }|rdnd }|rdnd }| j        d | j         j                 D ]<}|r||fz  } ||f|||j                 |||||	d|
}|d         }|r||d         fz  }=|                     |          }|r||fz  }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`.Fr  r   r   )ro   )rP   input_embedsr   r   r   r   )full_attentionr   g      ?rv   r   )r   r   r   r   r   r   r   )last_hidden_stater   r   r   )rP   r   r  r   
ValueErrorr  r   loggerwarning_oncer  r	   get_seq_lengthr+   arangerB   ro   r   re   rf   r   r   r  tensorrQ   rw   r  r  r   r  r   )r.   r  r   r   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_outputss                        r0   r?   zGemma2Model.forward~  s    2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	-t";< 	[YZZZ& 	4= 	Y 	j   I  --i88M 	?00*$+>>>O!CRC^==???de"\ "2]5H5K"KTaTh  N )33A66L ?-FF 	 + -"0"0#2 , K #5"C"C{"C"C%F%U%U%U%U# # & #oom\JJ
 \$+"93">mFYZZZ
%
2 #7@BBD0:d![)H4;+H)HI 	6 	6M# 6!m%55!)M
$72=3OP) /"3#-
 
 
 
M *!,M  6=#3"55		-00 	2-!11&+++%	
 
 
 	
r1   )	NNNNNNNNN)rD   rE   rF   r   r(   r   r   r   r+   r   r   r   r   r   r   r   r   r?   rH   rI   s   @r0   r
  r
  l  sN       |         151537+/59$(,0/359k
 k
E,-k
 !.k
 u/0	k

 "%k
   12k
 D>k
 $D>k
 'tnk
 !!12k
 +,k
 
!k
 k
 k
 ^ k
 k
 k
 k
 k
r1   r
  c                   z    e Zd ZdgZddiZddgdgfiZ f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                        Z xZS )Gemma2ForCausalLMzlm_head.weightlm_headcolwise_repr   logitsc                     t                                          |           t          |          | _        |j        | _        t          j        |j        |j        d          | _        | 	                                 d S rM   )
r'   r(   r
  r   r  r)   rS   rQ   r4  r  rY   s     r0   r(   zGemma2ForCausalLM.__init__  sj        ((
 +y!3V5FUSSS 	r1   Nr   r  r   r   r   r  labelsr   r   r  r   logits_to_keepr   c                    ||n| j         j        }|	|	n| j         j        }	 | j        d||||||||	|
d	|}|j        }t          |t                    rt          | d          n|}|                     |dd|ddf                   }| j         j	        2|| j         j	        z  }t          j        |          }|| j         j	        z  }d}| | j        ||| j        fi |}t          |||j        |j        |j                  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?"
        ```N)	r  r   r   r   r  r   r   r  r   )lossr6  r   r   r   r   )rP   r   r  r   r#  re   rG   slicer4  final_logit_softcappingr+   r   loss_functionr  r   r   r   r   )r.   r  r   r   r   r  r8  r   r   r  r   r9  r   r   r   slice_indicesr6  r;  s                     r0   r?   zGemma2ForCausalLM.forward  sb   F 2C1N--TXT_Tq$8$D  $+Jj 	 ,64: ,
)%+'/!5),
 ,
 ,
 ,
  18B>SV8W8Wk~ot444]kmAAA}aaa,?@AA;.:dkAAFZ''FdkAAF%4%ffdoPPPPD%#3!/)
 
 
 	
r1   )NNNNNNNNNNr   )rD   rE   rF   _tied_weights_keys_tp_plan_pp_planr(   r   r   r   r+   r   r   r   r   r   r   rG   r   r?   rH   rI   s   @r0   r3  r3    s       *+=)H_-z:;H      151537+/59-1$(,0/35934F
 F
E,-F
 !.F
 u/0	F

 "%F
   12F
 )*F
 D>F
 $D>F
 'tnF
 !!12F
 c5</0F
 
 F
 F
 F
 ^ F
 F
 F
 F
 F
r1   r3  c                       e Zd ZdS )Gemma2ForSequenceClassificationNrD   rE   rF   r   r1   r0   rD  rD  H          Dr1   rD  c                       e Zd ZdS )Gemma2ForTokenClassificationNrE  r   r1   r0   rH  rH  L  rF  r1   rH  )r3  r
  r   rD  rH  )Nr   )r   NN)Dtypingr   r   r   r+   torch.nnr)   activationsr   cache_utilsr   r	   
generationr
   masking_utilsr   r   modeling_flash_attention_utilsr   modeling_layersr   r   r   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   utils.deprecationr   utils.genericr   configuration_gemma2r   
get_loggerrD   r%  Moduler!   rK   r\   r   r   r   rG   r   r<   rA   r   r   r   r   r
  r3  rD  rH  __all__r   r1   r0   <module>r\     s  , - , , , , , , , , ,        ! ! ! ! ! ! . . . . . . . . ) ) ) ) ) ) R R R R R R R R B B B B B B         
 P O O O O O O O K K K K K K K K F F F F F F F F & & & & & & R R R R R R R R R R R R 0 0 0 0 0 0 / / / / / / . . . . . . 
	H	%	%= = = = =BI = = =(    	    !< !< !< !< !<BI !< !< !<H( ( (   6	UU\ 	U# 	U%, 	U 	U 	U 	U$ ## %  %I %< % 
 % <	 %
 U\* %  % e_ % e_ % 5<%& %  %  %  %FH) H) H) H) H)bi H) H) H)V9 9 9 9 93 9 9 9x ' ' ' ' 'O ' ' '2 ~
 ~
 ~
 ~
 ~
' ~
 ~
 ~
B V
 V
 V
 V
 V
- V
 V
 V
r	 	 	 	 	&FH] 	 	 		 	 	 	 	#@BW 	 	 	  r1   