
    gW                     H   d dl mZ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 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mZmZmZmZmZm Z  ddl!m"Z" dZ# G d dej$                  Z% G d dej$                  Z& ej'        e(          Z) G d dej$                  Z*d Z+d3dZ,dej-        de.dej-        fdZ/ G d dej$                  Z0 G d de0          Z1 G d de0          Z2e0e1e2d Z3 G d! d"ej$                  Z4d#Z5 ed$e5           G d% d&e                      Z6d'Z7d(Z8 ed$e5           G d) d*e6                      Z9 G d+ d,e6e          Z: ed-e5           G d. d/e6                      Z; ed0e5           G d1 d2e6                      Z<dS )4    )ListOptionalTupleUnionN   )ACT2FN)CacheHybridCache)GenerationMixin)_flash_attention_forward)BaseModelOutputWithPastCausalLMOutputWithPast SequenceClassifierOutputWithPastTokenClassifierOutput)PreTrainedModel)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_greater_or_equal#is_flash_attn_greater_or_equal_2_10loggingreplace_return_docstrings   )Gemma2Configzgoogle/gemma2-7bc                   <     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      f/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/gemma2/modeling_gemma2.pyr#   zGemma2RMSNorm.__init__7   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     r+   _normzGemma2RMSNorm._norm<   s8    5;quuQxx}}R}>>IJJJJr,   c                     |                      |                                          }|d| j                                        z   z  }|                    |          S )N      ?)r6   floatr(   type_as)r)   r5   outputs      r+   forwardzGemma2RMSNorm.forward?   sL    AGGII&& 3!2!2!4!445~~a   r,   c                 H    t          | j        j                   d| j         S )Nz, eps=)tupler(   shaper   r)   s    r+   
extra_reprzGemma2RMSNorm.extra_reprF   s%    )**<<$(<<<r,   )r   )
__name__
__module____qualname__intr9   r#   r6   r<   rA   __classcell__r*   s   @r+   r   r   6   s        5 5C 5e 5 5 5 5 5 5
K K K! ! != = = = = = =r,   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)   rN   r*   s     r+   r#   zGemma2MLP.__init__K   s    !-!'!94#3T5KRWXXXy!143IPUVVV4#94;KRWXXXV56r,   c                     |                      |                     |                     |                    |                     |          z            S r!   )rT   rV   rR   rS   r4   s     r+   r<   zGemma2MLP.forwardU   s;    ~~dkk$..*;*;<<t||ANOOOr,   )rB   rC   rD   r#   r<   rF   rG   s   @r+   rI   rI   J   sN        7 7 7 7 7P P P P P P Pr,   rI   c                   R     e Zd Zd fd	Z ej                    dd            Z xZS )Gemma2RotaryEmbedding   '  Nc                 :   t                                                       || _        || _        || _        d| j        t          j        d| j        dt
          j                                                  | j        z  z  z  }| 	                    d|d           d S )Nr8   r   r.   dtypeinv_freqF)tensor
persistent)
r"   r#   r   max_position_embeddingsbaser&   arangeint64r9   register_buffer)r)   r   rc   rd   devicer`   r*   s         r+   r#   zGemma2RotaryEmbedding.__init__]   s    '>$	$)Q!5;(W(W(W(](](_(_bfbj(jklZUKKKKKr,   c                 "   | j                             |j                   | j         d d d d f                                                             |j        d         dd          }|d d d d d f                                         }|j        j        }t          |t                    r|dk    r|nd}t          j
        |d          5  |                                |                                z                      dd          }t          j        ||fd	          }|                                }	|                                }
d d d            n# 1 swxY w Y   |	                    |j        
          |
                    |j        
          fS )Nr   r/   r   mpscpuF)device_typeenabledr.   r   r^   )r`   torh   r9   expandr?   type
isinstancestrr&   autocast	transposecatcossinr_   )r)   r5   position_idsseq_leninv_freq_expandedposition_ids_expandedrl   freqsembrw   rx   s              r+   r<   zGemma2RotaryEmbedding.forwardf   s    	""" M$4-8>>@@GGHZ[\H]_acdee ,QQQaaaZ 8 > > @ @ hm%/S%A%AekUZFZFZkk`e^UCCC 	 	&,,..1F1L1L1N1NNYYZ[]^__E)UEN333C''))C''))C		 	 	 	 	 	 	 	 	 	 	 	 	 	 	
 vvAGv$$cff17f&;&;;;s   A>EEE)r[   r\   Nr!   )rB   rC   rD   r#   r&   no_gradr<   rF   rG   s   @r+   rZ   rZ   \   sk        L L L L L L U]__< < < _< < < < <r,   rZ   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..Nr/   r.   rn   )r?   r&   rv   )r5   x1x2s      r+   rotate_halfr   x   s]    	
3"!'"+"""	#B	
3q """	#B9rc2YB''''r,   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krw   rx   ry   unsqueeze_dimq_embedk_embeds           r+   apply_rotary_pos_embr      sc    ( --
&
&C
--
&
&C3w;q>>C/0G3w;q>>C/0GGr,   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)r?   rp   reshape)r   r   batchnum_key_value_headsslenhead_dims         r+   	repeat_kvr      s    
 2?1D.Ehzz!!!!QQQaaa"23::5BUW\^bdlmmM  (;e(CT8TTTr,   c                       e Zd ZdZddedee         f fdZ	 	 	 	 	 	 ddej	        deej	                 d	eej
                 d
ee         dededeej
                 dee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' paperNrN   	layer_idxc                 >   t                                                       || _        || _        |(t                              d| j        j         d           |j        | _        |j	        | _	        |j
        | _        |j        | _        |j        | _        | j        | j        z  | _        |j        | _        |j        | _        d| _        |j        dz  | _        | j	        | j        z  dk    r t)          d| j	         d| 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        	          | _        t9          |d
z            s|j        nd | _        t=          | j        | j        | j                  | _        d S )NzInstantiating z without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.Tg      r   z?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).rL   r.   )rc   rd   ) r"   r#   rN   r   loggerwarning_oncer*   rB   attention_dropoutrO   num_attention_heads	num_headsr   r   num_key_value_groupsrc   
rope_theta	is_causalquery_pre_attn_scalarscaling
ValueErrorr$   rQ   attention_biasq_projk_projv_projo_projboolsliding_windowrZ   
rotary_embr)   rN   r   r*   s      r+   r#   zGemma2Attention.__init__   s   ",!8 , , ,   "(!9!-3#)#= $(Nd6N$N!'-'E$ +3T9dn,118RVRb 8 8%)^8 8 8  
 i 0$.4=2PW]Wlmmmi 0$2JT]2Zagavwwwi 0$2JT]2Zagavwwwi >@PW]Wlmmm;?	A;N;NXf33TX/M$($@
 
 
r,   Fr   attention_maskry   past_key_valueoutput_attentions	use_cachecache_positionr   c                    |                                 \  }}	}
|                     |          }|                     |          }|                     |          }|                    ||	| j        | j                                      dd          }|                    ||	| j        | j                                      dd          }|                    ||	| j        | j                                      dd          }| 	                    ||          \  }}t          ||||          \  }}|,||| j        |d}|                    ||| j        |          \  }}t          || j                  }t          || j                  }t!          j        ||                    dd                    | j        z  }| j        j        2|| j        j        z  }t!          j        |          }|| j        j        z  }|$|d d d d d d d |j        d         f         }||z   }t.          j                            |dt           j                                      |j                  }t.          j                            || j        | j                  }t!          j        ||          }|                                 || j        |	| j        fk    r5tA          d	|| j        |	| j        f d
|                                            |                    dd          !                                }|                    ||	d          }| "                    |          }|sd }|||fS )Nr   r.   rx   rw   r   r   r   r/   )r   r_   )ptrainingz `attn_output` should be of size z	, but is )#sizer   r   r   viewr   r   ru   r   r   r   r   updater   r   r   r&   matmulr   rN   attn_logit_softcappingtanhr?   r$   
functionalsoftmaxfloat32ro   r_   dropoutr   r   r   
contiguousr   )r)   r   r   ry   r   r   r   r   bszq_len_query_states
key_statesvalue_statesrw   rx   cache_kwargsattn_weightscausal_maskattn_outputs                       r+   r<   zGemma2Attention.forward   sQ    &**,,UA{{=11[[//
{{=11#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm??<>>S#7jRUWZ#[#[ j% "&"5"0	 L (6'<'<ZW[Wegs't't$Jz4+DEE
 t/HII|L*2F2Fq!2L2LMMPTP\\;-9'$+*LLL :l33L'$+*LLL%(AAAqqq2HJ4DR4H2H)HIK'+5L },,\r,WWZZ[g[mnn},,\T=S^b^k,lll<>>#t~udm!LLL)CPTP]3^ ) )$$&&) )  
 "++Aq11<<>>!&&sE266kk+..  	 LL.88r,   r!   NNNFFN)rB   rC   rD   __doc__r   r   rE   r#   r&   Tensor
LongTensorr	   r   r   r<   rF   rG   s   @r+   r   r      s%       GG%
 %
| %
 %
 %
 %
 %
 %
 %
T 2637*."'59A9 A9|A9 !.A9 u/0	A9
 !A9  A9 A9 !!12A9 
u|Xel3XeEL>Q5RR	SA9 A9 A9 A9 A9 A9 A9 A9r,   r   c                       e Zd ZdZ fdZ	 	 	 	 	 	 ddej        deej                 deej                 dee	         d	e
d
e
deej                 deej        eej                 eeej                          f         fdZ xZS )Gemma2FlashAttention2aH  
    Gemma2 flash attention module. This module inherits from `Gemma2Attention` as the weights of the module stays
    untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
    flash attention and deal with padding tokens in case the input contains any of them.
    c                 b     t                      j        |i | t                       | _        d S r!   )r"   r#   r   _flash_attn_uses_top_left_mask)r)   argskwargsr*   s      r+   r#   zGemma2FlashAttention2.__init__  s9    $)&)))
 3V2W2W.W+++r,   NFr   r   ry   r   r   r   r   r   c                 r   d}|                                 \  }}	}
|                     |          }|                     |          }|                     |          }|                    ||	| j        | j                                      dd          }|                    ||	| j        | j                                      dd          }|                    ||	| j        | j                                      dd          }| 	                    ||          \  }}t          ||||          \  }}|,||| j        |d}|                    ||| j        |          \  }}|/|j        d         }|d d d d d |f         }|d d d d d |f         }|                    dd          }|                    dd          }|                    dd          }| j        r| j        nd}|j        }|t$          j        k    rt%          j                    rt%          j                    }n3t-          | j        d          r| j        j        }n| j        j        j        }t4                              d| d           |                    |          }|                    |          }|                    |          }t;          |||||	|| j        | j        | j        | j         tC          d	          r| j        j"        nd 
          }|#                    ||	d          $                                }| %                    |          }|sd }|||fS )NFr   r.   r           _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .z2.6.0)r   softmax_scaler   r   use_top_left_masksoftcapr/   )&r   r   r   r   r   r   r   ru   r   r   r   r   r   r   r?   r   r   r_   r&   r   is_autocast_enabledget_autocast_gpu_dtypehasattrrN   r   r(   r   r   ro   r   r   r   r   r   r   r   r   r   )r)   r   r   ry   r   r   r   r   r   r   r   r   r   r   rw   rx   r   rz   dropout_rateinput_dtypetarget_dtyper   r   s                          r+   r<   zGemma2FlashAttention2.forward#  sn    "%**,,UA{{=11[[//
{{=11
 $((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm??<>>S#7jRUWZ#[#[ j% "&"5"0	 L (6'<'<ZW[Wegs't't$J%$*1-G#AAAqqq(7(N3J'111hwh7L $--a33))!Q//
#--a3315Gt--C #(%-''(** 8$;==&?@@ 8#{B#{17$ $ $ $   (??<88L#|44J'??<88L. ,n."A:XY`:a:akDK66gk
 
 
 "))#ub99DDFFkk+..  	 LL.88r,   r   )rB   rC   rD   r   r#   r&   r   r   r   r	   r   r   r<   rF   rG   s   @r+   r   r     s        X X X X X 6:37*."'59a9 a9|a9 !!12a9 u/0	a9
 !a9  a9 a9 !!12a9 
u|Xel3XeEL>Q5RR	Sa9 a9 a9 a9 a9 a9 a9 a9r,   r   c                        e Zd ZdZ	 	 	 	 	 	 ddej        deej                 deej                 dee         de	d	e	d
eej                 de
ej        eej                 ee
ej                          f         f fdZ xZS )Gemma2SdpaAttentionz
    Gemma2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `Gemma2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    NFr   r   ry   r   r   r   r   r   c           	         |rBt                               d           t                                          |||||||          S |                                \  }}	}
|                     |          }|                     |          }|                     |          }|                    ||	| j	        | j
                                      dd          }|                    ||	| j        | j
                                      dd          }|                    ||	| j        | j
                                      dd          }|                     ||          \  }}t          ||||          \  }}|,||| j        |d}|                    ||| j        |          \  }}t%          || j                  }t%          || j                  }|}||d d d d d d d |j        d         f         }|j        j        dk    r>|<|                                }|                                }|                                }||	dk    rdnd	}t0          j        j                            ||||| j        r| j        nd
|| j                  }|                    dd                                          }|                    ||	d          }|                     |          }|d |fS )Na  Gemma2Model is using Gemma2SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.r   r   ry   r   r   r   r   r   r.   r   r   cudaTFr   )	attn_mask	dropout_pr   scaler/   ) r   r   r"   r<   r   r   r   r   r   r   r   ru   r   r   r   r   r   r   r   r   r?   rh   rq   r   r&   r$   r   scaled_dot_product_attentionr   r   r   r   )r)   r   r   ry   r   r   r   r   r   r   r   r   r   r   rw   rx   r   r   r   r   r*   s                       r+   r<   zGemma2SdpaAttention.forward  s     	[   77??+-)-"3#- #    &**,,UA{{=11[[//
{{=11#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm??<>>S#7jRUWZ#[#[ j% "&"5"0	 L (6'<'<ZW[Wegs't't$Jz4+DEE
 t/HII$%%aaaAAA/E1A"1E/E&EFK #v--+2I'2244L#..00J'2244L (/EAIIDD5	h)FF!04Fd,,3, G 
 
 "++Aq11<<>>!&&sE266kk+..D.00r,   r   )rB   rC   rD   r   r&   r   r   r   r	   r   r   r<   rF   rG   s   @r+   r   r     s          2637*."'59R1 R1|R1 !.R1 u/0	R1
 !R1  R1 R1 !!12R1 
u|Xel3XeEL>Q5RR	SR1 R1 R1 R1 R1 R1 R1 R1 R1 R1r,   r   )eagerflash_attention_2sdpac                       e Zd Zdedef fdZ	 	 	 	 	 	 ddej        deej                 deej	                 d	ee
         d
ee         dee         deej	                 deej        eeej        ej        f                  f         fdZ xZS )Gemma2DecoderLayerrN   r   c                     t                                                       |j        | _        t          |j                 ||          | _        t          |          | _        t          |j        |j	                  | _
        || _        t          |dz             | _        t          |j        |j	                  | _        t          |j        |j	                  | _        |j        | _        t          |j        |j	                  | _        d S )N)rN   r   r   r.   )r"   r#   rO   GEMMA2_ATTENTION_CLASSES_attn_implementation	self_attnrI   mlpr   rms_norm_epsinput_layernormrN   r   
is_slidingpre_feedforward_layernormpost_feedforward_layernormr   post_attention_layernormr   s      r+   r#   zGemma2DecoderLayer.__init__  s    !-1&2MNV\hqrrrV$$,V-?VEXYYY"9q=111)6v7IvOb)c)c)c&*78JPVPc*d*d*d'$3(5f6HfNa(b(b(b%%%r,   NFr   r   ry   r   r   r   r   r   c           	         | j         r|| j        j        dk    r||dd| j         df         }nt	          j        |j                  j        }t	          j        t	          j	        |t          j
                  | j                   }	t	          j        |	||          }|j        d         dk    r|dddddd| j         df         }|}
|                     |          }|                     |||||||          \  }}}|                     |          }|
|z   }|}
|                     |          }|                     |          }|                     |          }|
|z   }|f}|r||fz  }|r||fz  }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *optional*):
                attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
                query_sequence_length, key_sequence_length)` if default attention is used.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
            past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence
            kwargs (`dict`, *optional*):
                Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
                into the model
        Nr   r^   diagonalr/   r   r   )r   rN   r   r   r&   finfor_   mintril	ones_liker   wherer?   r   r   r   r   r   r   )r)   r   r   ry   r   r   r   r   	min_dtypesliding_window_maskresidualself_attn_weightspresent_key_valueoutputss                 r+   r<   zGemma2DecoderLayer.forward  s   : ? 	U~9{/3FFF!-%3AAA8K7K7M7M4M%NN!K(;<<@	&+jON%*EEEQUQdPd' ' '# "'-@)^!\!\!'+q00%3AAAqqq!!!d>Q=Q=S=S4S%TN ,,];; ?Cnn')%)/) ?M ?
 ?
;(*; 55mDD =0 66}EE//77FF =0 " 	,)++G 	,)++Gr,   r   )rB   rC   rD   r   rE   r#   r&   r   r   r   r	   r   r   FloatTensorr<   rF   rG   s   @r+   r   r     s&       c| c c c c c c c  2637*.,1$)59J J|J !.J u/0	J
 !J $D>J D>J !!12J 
u (51BEDU1U+V"WW	XJ J J J J J J Jr,   r   aK  
    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 ([`Gemma2Config`]):
            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.
zTThe bare Gemma2 Model outputting raw hidden-states without any specific head on top.c                   h     e Zd ZeZdZdZdgZdgZdZ	dZ
dZdZdZd Zed	def fd            Z xZS )
Gemma2PreTrainedModelmodelTr   past_key_valuesFc                    | j         j        }t          |t          j                  rJ|j        j                            d|           |j         |j        j        	                                 d S d S t          |t          j
                  rS|j        j                            d|           |j        -|j        j        |j                 	                                 d S d S d S )Nr   )r3   std)rN   initializer_rangerr   r$   rQ   r(   datanormal_rM   zero_	Embeddingpadding_idx)r)   moduler  s      r+   _init_weightsz#Gemma2PreTrainedModel._init_weightsg  s    k+fbi(( 	?M&&CS&999{& &&((((( '&-- 	?M&&CS&999!-"6#56<<>>>>>	? 	?--r,   hard_check_onlyc                 v    t                                          ||          }|s|j        dk    rd|_        |S )z
        Overloads `PreTrainedModel._check_and_enable_sdpa` so as to DISABLE torch SDPA by default on Gemma2 models.
        SDPA reduces the model performance on Gemma2 because of the logits softcapping.
        )r  r   r   )r"   _check_and_enable_sdpar   )clsrN   r  r*   s      r+   r  z,Gemma2PreTrainedModel._check_and_enable_sdpar  sE     ///XX  	26#>&#H#H*1F'r,   )F)rB   rC   rD   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_cache_class_supports_quantized_cache_supports_static_cacher  classmethodr   r  rF   rG   s   @r+   r  r  W  s        
  L&*#-.#4"5!N  %!	? 	? 	?  T      [    r,   r  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 (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
            Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
            returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

            Two formats are allowed:
            - a [`~cache_utils.Cache`] instance, see our
            [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
            - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
            shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
            cache format.

            The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
            legacy cache format will be returned.

            If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
            have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
            of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
c                       e Zd ZdZdef fdZd Zd Z ee	          	 	 	 	 	 	 	 	 	 	 dde
j        dee
j                 d	ee
j                 d
ee         dee
j                 dee         dee         dee         dee         dee
j                 deeef         fd            Zde
j        de
j        de
j        d
edef
dZede
j        dedede
j        de
j        de
j        defd            Z xZS )Gemma2Modelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Gemma2DecoderLayer`]

    Args:
        config: Gemma2Config
    rN   c                    t                                                     j        | _        j        | _        t          j        j        j        | j                  | _        t          j	        fdt          j                  D                       | _        t          j        j                  | _        d| _        |                                  d S )Nc                 0    g | ]}t          |          S  )r   ).0r   rN   s     r+   
<listcomp>z(Gemma2Model.__init__.<locals>.<listcomp>  s$    dddy	22dddr,   r   F)r"   r#   pad_token_idr  
vocab_sizer$   r  rO   embed_tokens
ModuleListrangenum_hidden_layerslayersr   r   normgradient_checkpointing	post_initrW   s    `r+   r#   zGemma2Model.__init__  s       !. +L):F<NPTP`aamddddE&JbDcDcddd
 
 "&"4&:MNNN	&+# 	r,   c                     | j         S r!   r3  r@   s    r+   get_input_embeddingsz Gemma2Model.get_input_embeddings  s      r,   c                     || _         d S r!   r<  r)   values     r+   set_input_embeddingsz Gemma2Model.set_input_embeddings  s    !r,   N	input_idsr   ry   r  inputs_embedsr   r   output_hidden_statesreturn_dictr   r   c                    ||n| j         j        }||n| j         j        }||n| j         j        }|	|	n| j         j        }	|d u |d uz  rt          d          | j        r%| j        r|rt          	                    d           d}|| 
                    |          }|r7|5| j        s.|j        \  }}}t          | j         ||| j        |j                  }|
B||                                nd}t!          j        |||j        d         z   |j                  }
||
                    d          }|                     |||
||          }|}t!          j        | j         j        dz  |j        	          }||z  }|rd
nd }|rd
nd }| j        D ]b}|r||fz  }| j        r)| j        r"|                     |j        |||||||
          }n ||||||||
          }|d         }|r||d         fz  }c|                     |          }|r||fz  }|r|nd }|	st5          d ||||fD                       S t7          ||||          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`.F)
batch_sizemax_cache_lenrh   r_   r   r   rh   g      ?r^   r.  )r   ry   r   r   r   r   c              3      K   | ]}||V  	d S r!   r.  )r/  vs     r+   	<genexpr>z&Gemma2Model.forward.<locals>.<genexpr>\  s(      ttqfgfsfsfsfsfsttr,   )last_hidden_stater  r   
attentions)rN   r   rD  r   use_return_dictr   r9  r   r   r   r3  r?   r
   rh   r_   get_seq_lengthr&   re   r   _update_causal_maskra   rO   r7  _gradient_checkpointing_func__call__r8  r>   r   )r)   rB  r   ry   r  rC  r   r   rD  rE  r   rG  rz   r   past_seen_tokensr   r   
normalizerall_hidden_statesall_self_attnsdecoder_layerlayer_outputs
next_caches                          r+   r<   zGemma2Model.forward  sT    2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]-t";< 	[YZZZ& 	4= 	Y 	j   I  --i88M 	00%2%8"J)%%{#)  O !CRC^==???de"\ "2]5H5K"KTaTh  N )33A66L..M>?L]
 

 &
 \$+"93">mFYZZZ
%
2 #7@BBD0:d![ 	6 	6M# 6!m%55!* t}  $ A A!*! #%"	! 	! !.!#.!-#2&7'#1! ! ! *!,M  6=#3"55		-00 	2-!11(1;__t
 	utt]J@QSa$btttttt&+&+%	
 
 
 	
r,   input_tensorc           
      :   | j         j        dk    r|S |j        |j        }}|j        d         }t          |t                    r|                                }	n||j        d         n|j        d         }	|                     |||	||||j        d                   }
|
S )Nr   r   r/   r   sequence_lengthtarget_lengthr_   rh   r   rG  )	rN   r   r_   rh   r?   rr   r
   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_position)r)   r   r[  r   r  r   r_   rh   r^  r_  r   s              r+   rQ  zGemma2Model._update_causal_maskd  s     ;+/BBB!!$*L,?v&,Q/o{33 	n+??AAMM8F8RN044XdXjklXmM PP+')#)!, Q 
 
 r,   r^  r_  r_   rh   rG  c                    | |                                  dk    r| }n+t          j        |          j        }	t          j        ||f|	||          }|dk    rt          j        |d          }|t          j        ||          |                    dd          k    z  }|ddddddf                             |ddd          }| |	                                }| j
        d         }
|ddddddd|
f         | ddddddf         z   }|dk    }|ddddddd|
f                             ||	          |ddddddd|
f<   |S )	a  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            device (`torch.device`):
                The device to plcae the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )
fill_valuer_   rh   r   r   rI  r/   r   )r   r&   r  r  fulltriure   r   rp   cloner?   masked_fill)r   r^  r_  r_   rh   r   rG  r   r   r  mask_lengthpadding_masks               r+   ra  zAGemma2Model._prepare_4d_causal_attention_mask_with_cache_position  s   B %.*<*<*>*>!*C*C(KKE**.I* -0Ye\b  K !###jqAAA5<fEEEH^H^_acdHeHeeeK%dD!!!QQQ&67>>z1bRTUUK))//11,226*111aaaL[L+@ANSTSTSTVZ\`bcbcbcScDdd+q05@AAAqqq,;,AV5W5c5c )6 6AAAqqq!!!\k\12 r,   
NNNNNNNNNN)rB   rC   rD   r   r   r#   r=  rA  r   GEMMA2_INPUTS_DOCSTRINGr&   r   r   r   r
   r  r   r   r   r   r<   rQ  staticmethodrE   r_   rh   ra  rF   rG   s   @r+   r+  r+    s3       
 |      ! ! !" " " +*+BCC '+15371559$(,0/3&*59q
 q
#q
 !.q
 u/0	q

 "+.q
   12q
 D>q
 $D>q
 'tnq
 d^q
 !!12q
 
u--	.q
 q
 q
 DCq
f   l  	 
 %          D 555 5 {	5
 5 5 5 5 5 \5 5 5 5 5r,   r+  c                       e Zd ZdgZ fdZd Zd Zd Zd Zd Z	d Z
 ee           eee	          	 	 	 	 	 	 	 	 	 	 	 	 ddej        deej                 deej                 dee         deej                 deej                 dee         dee         dee         dee         deej                 dedeeef         fd                        Z	 	 	 	 	 	 	 ddZ xZS )Gemma2ForCausalLMzlm_head.weightc                     t                                          |           t          |          | _        |j        | _        t          j        |j        |j        d          | _        | 	                                 d S rK   )
r"   r#   r+  r  r2  r$   rQ   rO   lm_headr:  rW   s     r+   r#   zGemma2ForCausalLM.__init__  sj        ((
 +y!3V5FUSSS 	r,   c                     | j         j        S r!   r  r3  r@   s    r+   r=  z&Gemma2ForCausalLM.get_input_embeddings      z&&r,   c                     || j         _        d S r!   rs  r?  s     r+   rA  z&Gemma2ForCausalLM.set_input_embeddings      "'
r,   c                     | j         S r!   rq  r@   s    r+   get_output_embeddingsz'Gemma2ForCausalLM.get_output_embeddings  s
    |r,   c                     || _         d S r!   rx  )r)   new_embeddingss     r+   set_output_embeddingsz'Gemma2ForCausalLM.set_output_embeddings  s    %r,   c                     || _         d S r!   r  )r)   decoders     r+   set_decoderzGemma2ForCausalLM.set_decoder  s    


r,   c                     | j         S r!   r~  r@   s    r+   get_decoderzGemma2ForCausalLM.get_decoder  s
    zr,   )output_typer  Nr   rB  r   ry   r  rC  labelsr   r   rD  rE  r   num_logits_to_keepr   c                    | j         r8| j        j        dk    r(t                              d| j        j         d           ||n| j        j        }|	|	n| j        j        }	|
|
n| j        j        }
|                     ||||||||	|
|
  
        }|d         }| 	                    |dd| dddf                   }| j        j
        2|| j        j
        z  }t          j        |          }|| j        j
        z  }d}| | j        ||| j        fi |}|
s|f|dd         z   }||f|z   n|S t          |||j        |j        |j                  S )	a  
        Args:
            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

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

        Returns:

        Example:

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

        >>> model = GemmaForCausalLM.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)
rB  r   ry   r  rC  r   r   rD  rE  r   r   r   losslogitsr  r   rN  )r   rN   r   r   r   r   rD  rO  r  rq  final_logit_softcappingr&   r   loss_functionr2  r   r  r   rN  )r)   rB  r   ry   r  rC  r  r   r   rD  rE  r   r  loss_kwargsr  r   r  r  r;   s                      r+   r<   zGemma2ForCausalLM.forward  s   b = 	T[=HHr#{?r r r   2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]**)%+'/!5#)  
 
  
mAAA0B/B/C/CQQQ,FGHH;.:dkAAFZ''FdkAAF%4%ffdoUUUUD 	DY,F'+'7D7V##VC%#3!/)
 
 
 	
r,   Tc	           	         |E||d d |j         d          d f         }n(|j         d         |j         d         k    r|d d |f         }|||                                                    d          dz
  }|                    |dk    d           |r:|d d |j         d          d f         }|                    t
          j                  }||d         dk    r|d d}
n#|                    t
          j                  d d}
t          |t                    r|j	        dk    r| j
        j        dk    s|
d	         |
d	         j         \  }}}|
d	         j        }n|
d
         j         \  }}|
d
         j        }| j                            |||                                | j        j        j        |||          }|||
d<   |
                    |||||d           |
S )Nr   r   r/   )memory_format)rC  rB  )rB  rC  r.   r   rC  rB  r]  r  )ry   r   r  r   r   )r?   longcumsummasked_fill_rg  r&   contiguous_formatrr   r
   ndimrN   r   rh   r  ra  r`  rq  r(   r_   r   )r)   rB  r  r   rC  r   ry   r   r  r   model_inputsrG  r^  r   rh   s                  r+   prepare_inputs_for_generationz/Gemma2ForCausalLM.prepare_inputs_for_generation>  sM   " &(%aaa.*>q*A)A)C)C&CD		#~';A'>>>%aaa&78	%,*>)..0077;;a?L%%n&91=== Y+AAA	0B/B/D/D,DE  ,11@W1XX $):a)?)?-:NNLL *3uG^)_)_rvwwL 44	#q((K48KKKO,81=o1N1T.
OQ%o6=.:;.G.M+
O%k29!Z]] /-AACCl)/-% ^  N )1CL-. ,"0#2&"0 	
 	
 	
 r,   )NNNNNNNNNNNr   )NNNNNTN)rB   rC   rD   _tied_weights_keysr#   r=  rA  ry  r|  r  r  r   rl  r   r   _CONFIG_FOR_DOCr&   r   r   r   r
   r  r   rE   r   r   r<   r  rF   rG   s   @r+   ro  ro    s"       *+    ' ' '( ( (  & & &     +*+BCC+AP_``` '+15371559-1$(,0/3&*59"#]
 ]
#]
 !.]
 u/0	]

 "+.]
   12]
 )*]
 D>]
 $D>]
 'tn]
 d^]
 !!12]
  ]
 
u,,	-]
 ]
 ]
 a` DC]
D L L L L L L L Lr,   ro  a  
    The Gemma2 Model transformer with a sequence classification head on top (linear layer).

    [`Gemma2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT-2) do.

    Since it does classification on the last token, it requires to know the position of the last token. If a
    `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
    no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
    padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
    each row of the batch).
    c                   v    e Zd Z fdZd Zd Z ee          	 	 	 	 	 	 	 	 	 	 ddee	j
                 dee	j                 dee	j
                 deeeee	j                 f                  d	ee	j                 d
ee	j
                 dee         dee         dee         dee         deeef         fd            Z xZS )Gemma2ForSequenceClassificationc                     t                                          |           |j        | _        t          |          | _        t          j        |j        | j        d          | _        | 	                                 d S rK   )
r"   r#   
num_labelsr+  r  r$   rQ   rO   scorer:  rW   s     r+   r#   z(Gemma2ForSequenceClassification.__init__  si        + ((
Yv14?OOO
 	r,   c                     | j         j        S r!   rs  r@   s    r+   r=  z4Gemma2ForSequenceClassification.get_input_embeddings  rt  r,   c                     || j         _        d S r!   rs  r?  s     r+   rA  z4Gemma2ForSequenceClassification.set_input_embeddings  rv  r,   NrB  r   ry   r  rC  r  r   r   rD  rE  r   c                 "   |
|
n| j         j        }
|                     ||||||||	|
	  	        }|d         }|                     |          }||j        d         }n|j        d         }| j         j        |dk    rt          d          | j         j        d}nv|rt          j        || j         j                  	                                
                    d          dz
  }||j        d         z  }|                    |j                  }nd}|t          j        ||j                  |f         }d}||                     |||| j                   }|
s|f|dd         z   }||f|z   n|S t          |||j        |j        |j        	          S )
  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        Nr   ry   r  rC  r   r   rD  rE  r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r/   rI  )r  r  pooled_logitsrN   r  )rN   rO  r  r  r?   r1  r   r&   eqrE   argmaxro   rh   re   r  r   r  r   rN  )r)   rB  r   ry   r  rC  r  r   r   rD  rE  transformer_outputsr   r  rG  sequence_lengthsr  r  r;   s                      r+   r<   z'Gemma2ForSequenceClassification.forward  s   ( &1%<kk$+B]"jj)%+'/!5# ) 

 

 ,A.M** "+JJ&,Q/J;#+
a\]]];#+!$#(8It{7O#P#P#T#T#V#V#]#]^`#a#ade#e #3iob6I#I #3#6#6v}#E#E  #% u|Jv}MMMO__`%%VFR_hlhs%ttD 	F#%(;ABB(??F)-)9TGf$$vE/ /?-;*5
 
 
 	
r,   rk  )rB   rC   rD   r#   r=  rA  r   rl  r   r&   r   r   r   r	   r   r  r   r   r   r<   rF   rG   s   @r+   r  r    s            ' ' '( ( ( +*+BCC 151537KO59-1$(,0/3&*E
 E
E,-E
 !.E
 u/0	E

 "%tE4E/F(F"GHE
   12E
 )*E
 D>E
 $D>E
 'tnE
 d^E
 
u66	7E
 E
 E
 DCE
 E
 E
 E
 E
r,   r  z
    The Gemma2 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
    output) e.g. for Named-Entity-Recognition (NER) tasks.
    c                       e Zd Z fdZd Zd Z ee           ee	e
e          	 	 	 	 	 	 	 	 	 	 ddeej                 deej                 deej                 d	eeej                          d
eej                 deej                 dee         dee         dee         dee         deee
f         fd                        Z xZS )Gemma2ForTokenClassificationc                    t                                          |           |j        | _        t          |          | _        t          |dd           |j        }nt          |dd           |j        }nd}t          j	        |          | _
        t          j        |j        |j                  | _        |                                  d S )Nclassifier_dropouthidden_dropoutg?)r"   r#   r  r+  r  getattrr  r  r$   Dropoutr   rQ   rO   r  r:  )r)   rN   r  r*   s      r+   r#   z%Gemma2ForTokenClassification.__init__  s        + ((
6/66B!'!:V-t44@!'!6!$z"455Yv163DEE
 	r,   c                     | j         j        S r!   rs  r@   s    r+   r=  z1Gemma2ForTokenClassification.get_input_embeddings  rt  r,   c                     || j         _        d S r!   rs  r?  s     r+   rA  z1Gemma2ForTokenClassification.set_input_embeddings  rv  r,   )
checkpointr  r  NrB  r   ry   r  rC  r  r   r   rD  rE  r   c                 p   |
|
n| j         j        }
|                     ||||||||	|
	  	        }|d         }|                     |          }|                     |          }d}||                     ||| j                   }|
s|f|dd         z   }||f|z   n|S t          |||j        |j                  S )r  Nr  r   r.   )r  r  r   rN  )	rN   rO  r  r   r  r  r   r   rN  )r)   rB  r   ry   r  rC  r  r   r   rD  rE  r  sequence_outputr  r  r;   s                   r+   r<   z$Gemma2ForTokenClassification.forward  s    2 &1%<kk$+B]**)%+'/!5#  

 

 "!*,,77O,,%%ffdkBBD 	FY,F)-)9TGf$$vE$!/)	
 
 
 	
r,   rk  )rB   rC   rD   r#   r=  rA  r   rl  r   _CHECKPOINT_FOR_DOCr   r  r   r&   r   r   r   r  r   r   r   r<   rF   rG   s   @r+   r  r    s            ' ' '( ( ( +*+BCC&)$   151537=A59-1$(,0/3&*1
 1
E,-1
 !.1
 u/0	1

 "$u'8"9:1
   121
 )*1
 D>1
 $D>1
 'tn1
 d^1
 
u++	,1
 1
 1
  DC1
 1
 1
 1
 1
r,   r  )Nr   )=typingr   r   r   r   r&   torch.nnr$   torch.utils.checkpointactivationsr   cache_utilsr	   r
   
generationr   modeling_flash_attention_utilsr   modeling_outputsr   r   r   r   modeling_utilsr   utilsr   r   r   r   r   r   r   configuration_gemma2r   r  Moduler   rI   
get_loggerrB   r   rZ   r   r   r   rE   r   r   r   r   r   r   GEMMA2_START_DOCSTRINGr  r  rl  r+  ro  r  r  r.  r,   r+   <module>r     s  , 0 / / / / / / / / / / /            ! ! ! ! ! ! - - - - - - - - ) ) ) ) ) ) F F F F F F            . - - - - -                  / . . . . . ) = = = = =BI = = =(P P P P P	 P P P 
	H	%	%< < < < <BI < < <8( ( (   6	UU\ 	U# 	U%, 	U 	U 	U 	Uk9 k9 k9 k9 k9bi k9 k9 k9\p9 p9 p9 p9 p9O p9 p9 p9fZ1 Z1 Z1 Z1 Z1/ Z1 Z1 Z1| .  X X X X X X X Xv " Z # # # # #O # #	 #L !H V Z i i i i i' i i	 iXK K K K K- K K K\   V
 V
 V
 V
 V
&; V
 V
 V
r   N
 N
 N
 N
 N
#8 N
 N
 N
 N
 N
r,   