
    sg                        d dl mZ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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mZ d
dlm Z   e       rddl!m"Z"  ed      rd dl#m$Z$  ejJ                  e&      Z'dZ(dZ) G d dejT                        Z+ G d dejT                        Z, G d dejT                        Z-d Z.d@dZ/dej`                  de1dej`                  fdZ2de dej`                  dej`                  d ej`                  d!eej`                     deej`                  ej`                  f   fd"Z3ejh                  fde dej`                  dej`                  d ej`                  d!eej`                     d#ejj                  deej`                  df   fd$Z6	 dAde dej`                  dej`                  d ej`                  d!eej`                     d%e7deej`                  eej`                     f   fd&Z8de dej`                  dej`                  d ej`                  d!eej`                     deej`                  df   fd'Z9e6e8e3e9d(Z: G d) d*ejT                        Z; G d+ d,e;      Z< G d- d.e;      Z= G d/ d0ejT                        Z>d1Z? ed2e?       G d3 d4e             Z@d5ZA ed2e?       G d6 d7e@             ZB G d8 d9e@e      ZC ed:e?       G d; d<e@             ZD ed=e?       G d> d?e@             ZEy)B    )ListOptionalTupleUnionN   )ACT2FN)CacheHybridCache)GenerationMixin)BaseModelOutputWithPastCausalLMOutputWithPast SequenceClassifierOutputWithPastTokenClassifierOutput)PreTrainedModel)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_2_availableis_flash_attn_greater_or_equalis_torch_greater_or_equalloggingreplace_return_docstrings   )Gemma2Config)_flash_attention_forwardz2.5)flex_attentionzgoogle/gemma2-7br   c                   <     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                  |            | _        y N)super__init__r    nn	Parametertorchzerosweight)selfr   r    	__class__s      ]/var/www/html/venv/lib/python3.12/site-packages/transformers/models/gemma2/modeling_gemma2.pyr$   zGemma2RMSNorm.__init__@   s.    ll5;;s#34    c                     |t        j                  |j                  d      j                  dd      | j                  z         z  S )N   T)keepdim)r'   rsqrtpowmeanr    r*   xs     r,   _normzGemma2RMSNorm._normE   s4    5;;quuQx}}R}>IJJJr-   c                     | j                  |j                               }|d| j                  j                         z   z  }|j                  |      S )N      ?)r7   floatr)   type_as)r*   r6   outputs      r,   forwardzGemma2RMSNorm.forwardH   sC    AGGI& 3!2!2!445~~a  r-   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler)   shaper    r*   s    r,   
extra_reprzGemma2RMSNorm.extra_reprO   s'    ))*+6$((<<r-   )gư>)
__name__
__module____qualname__intr:   r$   r7   r=   rB   __classcell__r+   s   @r,   r   r   ?   s&    5C 5e 5
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                     | _        y NFbias)r#   r$   confighidden_sizeintermediate_sizer%   Linear	gate_projup_proj	down_projr   hidden_activationact_fnr*   rO   r+   s     r,   r$   zGemma2MLP.__init__T   s    !--!'!9!94#3#3T5K5KRWXyy!1!143I3IPUV4#9#94;K;KRWXV556r-   c                     | j                  | j                  | j                  |            | j                  |      z        S r"   )rU   rW   rS   rT   r5   s     r,   r=   zGemma2MLP.forward^   s0    ~~dkk$..*;<t||ANOOr-   )rC   rD   rE   r$   r=   rG   rH   s   @r,   rJ   rJ   S   s    7Pr-   rJ   c                   P     e Zd Zd fd	Z ej
                         dd       Z xZS )Gemma2RotaryEmbeddingc                 ,   t         |           || _        || _        || _        d| j                  t        j                  d| j                  dt
        j                        j                         | j                  z  z  z  }| j                  d|d       y )Nr9   r   r/   dtypeinv_freqF)tensor
persistent)
r#   r$   r   max_position_embeddingsbaser'   arangeint64r:   register_buffer)r*   r   rb   rc   devicer_   r+   s         r,   r$   zGemma2RotaryEmbedding.__init__c   sx    '>$	$))Q!5;;(W(](](_bfbjbj(jklZUKr-   c                    | j                   j                  |j                         | j                   d d d d f   j                         j	                  |j
                  d   dd      }|d d d d d f   j                         }|j                  j                  }t        |t              r|dk7  r|nd}t        j                  |d      5  |j                         |j                         z  j                  dd      }t        j                  ||fd	      }|j                         }	|j                         }
d d d        	j                  |j                  
      
j                  |j                  
      fS # 1 sw Y   AxY w)Nr   r0   r   mpscpuF)device_typeenabledr/   r   r]   )r_   torg   r:   expandr@   type
isinstancestrr'   autocast	transposecatcossinr^   )r*   r6   position_idsseq_leninv_freq_expandedposition_ids_expandedrk   freqsembrv   rw   s              r,   r=   zGemma2RotaryEmbedding.forwardl   s;    	" MM$4-8>>@GGHZHZ[\H]_acde ,QaZ 8 > > @ hhmm%/S%AkUZFZk`e^^UC 	&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')C'')C		
 vvAGGv$cff177f&;;;	 	s   A+E11E:)i   i'  Nr"   )rC   rD   rE   r$   r'   no_gradr=   rG   rH   s   @r,   r[   r[   b   s%    L U]]_< <r-   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..Nr0   r/   rm   )r@   r'   ru   )r6   x1x2s      r,   rotate_halfr   ~   sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r-   c                     |j                  |      }|j                  |      }| |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krv   rw   rx   unsqueeze_dimq_embedk_embeds           r,   apply_rotary_pos_embr      sY    ( --
&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   j                  |||||      } | j                  |||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@   ro   reshape)r   r   batchnum_key_value_headsslenhead_dims         r,   	repeat_kvr      so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr-   rO   querykeyvaluemaskc                    t        || j                        }t        || j                        }t        j                  ||j	                  dd            | j
                  z  }| j                  3|| j                  z  }t        j                  |      }|| j                  z  }|#|d d d d d d d |j                  d   f   }	||	z   }t        j                  j                  |dt        j                        j                  |j                        }t        j                  j                  || j                   | j"                        }t        j                  ||      }
|
j	                  dd      j%                         }
|
|fS )Nr/   r   r0   )r   r^   )ptrainingr   )r   num_key_value_groupsr'   matmulrt   scalingattn_logit_softcappingtanhr@   r%   
functionalsoftmaxfloat32rn   r^   dropoutattention_dropoutr   
contiguous)rO   r   r   r   r   _kwargs
key_statesvalue_statesattn_weightscausal_maskattn_outputs              r,   eager_attention_forwardr      sM    3 ; ;<JUF$?$?@L<<z';';Aq'ABV^^SL$$0#f&C&CCzz,/#f&C&CC1a$:j&6&6r&:$::;#k1 ==((2U]](SVVW\WbWbcL==((9Q9Q\b\k\k(lL,,|\:K''1-88:K$$r-   target_dtypec                 R   |+|j                   d   }|d d d d d |f   }|d d d d d |f   }|j                  dd      }|j                  dd      }	|j                  dd      }
| j                  r| j                  nd}|j                  }|t
        j                  k(  r3|j                  |      }|	j                  |      }	|
j                  |      }
t        ||	|
||| j                  | j                  | j                  | j                  t        d      r| j                  nd       }|d fS )Nr   r/           z2.6.0)r   softmax_scale	is_causalsliding_windowuse_top_left_masksoftcap)r@   rt   r   r   r^   r'   r   rn   r   r   r   r   _flash_attn_uses_top_left_maskr   r   )rO   r   r   r   r   r   r   ry   query_statesr   r   dropout_rateinput_dtyper   s                 r,   flash_attention_forwardr      s$    **Q-aHWHn%aHWHn% ??1a(Lq!$J??1a(L/56++CL$$Kemm##|4]]<0
#|4*nn"",, ??1OPW1X--^bK r-   output_attentionsc           	            fd}t        ||||d j                  |      }|sd }	n|\  }}	|j                  dd      j                         }||	fS )Nc                 |    j                   }|t        j                  | |z        z  } | |   d   |   |   z   S | S )Nr   )r   r'   r   )scorebhq_idxkv_idxsoft_caprO   r   s         r,   tanh_softcapz,flex_attention_forward.<locals>.tanh_softcap   sN    005::eh&677471:e,V444r-   T)	score_mod
enable_gqascale
return_lser   r/   )r   r   rt   r   )
rO   r   r   r   r   r   r   r   r   r   s
   `   `     r,   flex_attention_forwardr      sg     !nn$K $/!\''1-88:K$$r-   c           	      P   t        || j                        }t        || j                        }|}||d d d d d d d |j                  d   f   }|j                  j                  dk(  r2|0|j                         }|j                         }|j                         }||j                  d   dkD  rdnd}t        j                  j                  j                  ||||| j                  r| j                  nd|| j                        }|j                  dd      j                         }|d fS )	Nr   cudar   TFr   )	attn_mask	dropout_pr   r   r/   )r   r   r@   rg   rp   r   r'   r%   r   scaled_dot_product_attentionr   r   r   rt   )	rO   r   r   r   r   r   r   r   r   s	            r,   sdpa_attention_forwardr     s    C44
5CeV889EK!!Q?SYYr]?":; ||F"{'>  "nn  " $+A0BI((%%BB.4oo&**3nn C K ''1-88:Kr-   )flash_attention_2r   eagersdpac                   ,    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' paperrO   	layer_idxc                 (   t         |           || _        || _        |j                  | _        |j
                  | _        |j                  | _        |j                  | _        |j                  | _	        | j                  | j                  z  | _
        |j                  | _        |j                  | _        d| _        |j                  dz  | _        t!        |dz        s|j"                  nd | _        |j$                  | _        | j
                  | j                  z  dk7  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,                        | _        t7        | j                  | j                  | j                  	      | _        y )
NTg      r/   r   z?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).rM   )rb   rc   )r#   r$   rO   r   r   rP   num_attention_heads	num_headsr   r   r   rb   
rope_thetar   query_pre_attn_scalarr   boolr   r   
ValueErrorr%   rR   attention_biasq_projk_projv_projo_projr[   
rotary_embr*   rO   r   r+   s      r,   r$   zGemma2Attention.__init__J  s   "!'!9!9!--33#)#=#= $(NNd6N6N$N!'-'E'E$ ++33T9;?	A;Nf33TX&,&C&C#dnn,1QRVRbRbQc$T^^$4B8 
 ii 0 0$..4==2PW]WlWlmii 0 0$2J2JT]]2Zagavavwii 0 0$2J2JT]]2Zagavavwii >@P@PW]WlWlm/MM$($@$@
r-   r   attention_maskrx   past_key_valuer   	use_cachecache_positionr   c                    |j                         \  }}	}
| j                  |      }| j                  |      }| j                  |      }|j	                  ||	| j
                  | j                        j                  dd      }|j	                  ||	| j                  | j                        j                  dd      }|j	                  ||	| j                  | j                        j                  dd      }| j                  ||      \  }}t        ||||      \  }}|2||| j                  |d}|j                  ||| j                  |      \  }}|r0| j                  j                  dv rt         j#                  d       d}n| j                  j                  }t%        |   | |||||      \  }}|j'                  ||	d      j)                         }| j+                  |      }|sd }|||fS )	Nr   r/   )rw   rv   r   r   )r   r   zMSetting `attention_type` to `flex_attention` because `output_attentions=True`r   )r   r0   )sizer   r   r   viewr   r   rt   r   r   r   r   updater   rO   _attn_implementationloggerwarning_onceGEMMA2_ATTENTION_FUNCTIONr   r   r   )r*   r   r   rx   r   r   r   r   bszq_len_r   r   r   rv   rw   cache_kwargsattention_typer   r   s                       r,   r=   zGemma2Attention.forwardk  s    &**,UA{{=1[[/
{{=1#((eT^^T]]S]]^_abc__S%1I1I4==Yccdeghi
#((eT5M5Mt}}]gghiklm??<>S#7jRUWZ#[ j% "&"5"5"0	L (6'<'<ZW[WeWegs't$J!A!AEb!b op-N![[==N$=n$M,
L.\m%
!\ "))#ub9DDFkk+. LL.88r-   r"   NNNFFN)rC   rD   rE   __doc__r   r   rF   r$   r'   Tensor
LongTensorr	   r   r   r=   rG   rH   s   @r,   r   r   G  s    G
| 
 
H 2637*."'5919||19 !.19 u//0	19
 !19  19 19 !!1!1219 
u||Xell3XeELL>Q5RR	S19r-   r   c                   0     e Zd Zddedee   f fdZ xZS )Gemma2FlashAttention2rO   r   c                 r    t         |   ||       d| j                  _        t        j                  d       y )Nr   The `Gemma2FlashAttention2` class is deprecated in favor of simply modifying the `config._attn_implementation`attribute of the `GemmaAttention` class! It will be removed in v4.48r#   r$   rO   r   r   r   r   s      r,   r$   zGemma2FlashAttention2.__init__  s2    ++>(S	
r-   r"   rC   rD   rE   r   r   rF   r$   rG   rH   s   @r,   r   r         
| 
 
 
r-   r   c                   0     e Zd Zddedee   f fdZ xZS )Gemma2SdpaAttentionrO   r   c                 r    t         |   ||       d| j                  _        t        j                  d       y )Nr   r   r   r   s      r,   r$   zGemma2SdpaAttention.__init__  s2    ++1(S	
r-   r"   r   rH   s   @r,   r  r    r   r-   r  c                   (    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 )Gemma2DecoderLayerrO   r   c                    t         |           |j                  | _        || _        t	        |dz         | _        t        ||      | _        t        |      | _	        t        |j                  |j                        | _        t        |j                  |j                        | _        t        |j                  |j                        | _        t        |j                  |j                        | _        |j                   | _        y )Nr/   )rO   r   r    )r#   r$   rP   rO   r   
is_slidingr   	self_attnrJ   mlpr   rms_norm_epsinput_layernormpost_attention_layernormpre_feedforward_layernormpost_feedforward_layernormr   r   s      r,   r$   zGemma2DecoderLayer.__init__  s    !--"9q=11()LV$,V-?-?VEXEXY(5f6H6HfNaNa(b%)6v7I7IvObOb)c&*78J8JPVPcPc*d'$33r-   r   r   rx   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   }|}
| j                  |      }| j                  |||||||      \  }}}| j                  |      }|
|z   }|}
| j!                  |      }| j#                  |      }| j%                  |      }|
|z   }|f}|r||fz  }|r||fz  }|S )Nr   r]   diagonalr0   r   )r   r   rx   r   r   r   r   )r  rO   r   r   r'   finfor^   mintril	ones_liker   wherer@   r  r	  r  r  r
  r  )r*   r   r   rx   r   r   r   r   	min_dtypesliding_window_maskresidualself_attn_weightspresent_key_valueoutputss                 r,   r=   zGemma2DecoderLayer.forward  s    ??~9{{//3FF!-%3A8K8K7K7M4M%NN!KK(;(;<@@	&+jjOON%**EQUQdQdPd'# "'-@)^!\!''+q0%3Aq!d>Q>Q=Q=S4S%TN ,,]; ?Cnn')%)/) ?M ?
;(*; 55mD =0 66}E/77F =0 ")++G)++Gr-   r   )rC   rD   rE   r   rF   r$   r'   r   r   r   r	   r   r   FloatTensorr=   rG   rH   s   @r,   r  r    s    4| 4 4" 2637*.,1$)597||7 !.7 u//0	7
 !7 $D>7 D>7 !!1!127 
u  (51B1BEDUDU1U+V"WW	X7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                   b     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                        rY|j
                  j                  j                  d|       |j                  %|j                  j                  j                          y y t        |t        j                        rf|j
                  j                  j                  d|       |j                  2|j
                  j                  |j                     j                          y y y )Nr   )r4   std)rO   initializer_rangerq   r%   rR   r)   datanormal_rN   zero_	Embeddingpadding_idx)r*   moduler$  s      r,   _init_weightsz#Gemma2PreTrainedModel._init_weights  s    kk++fbii(MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> . .r-   hard_check_onlyc                 Z    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   )clsrO   r-  r+   s      r,   r/  z,Gemma2PreTrainedModel._check_and_enable_sdpa(  s8     //X 6#>#>&#H*1F'r-   F)rC   rD   rE   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/  rG   rH   s   @r,   r   r     se    
  L&*#-.#4"5!N  %!	? T  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                   6    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 e
j*                         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
j2                  de
j4                  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
    rO   c           	      4   t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        d| _        t%        |dd      dk7  rt&        j)                  d       | j+                          y c c}w )Nr  Fpretraining_tpr   zK`pretraining_tp` is deprecated, please use `model.tensor_parallel` instead.)r#   r$   pad_token_idr*  
vocab_sizer%   r)  rP   embed_tokens
ModuleListrangenum_hidden_layersr  layersr   r  normgradient_checkpointinggetattrr   warn	post_initr   s      r,   r$   zGemma2Model.__init__  s     !.. ++LL):):F<N<NPTP`P`ammDI&JbJbDcdy	2d
 "&"4"4&:M:MN	&+#6+Q/14KKef 	 es   Dc                     | j                   S r"   rC  rA   s    r,   get_input_embeddingsz Gemma2Model.get_input_embeddings  s       r-   c                     || _         y r"   rN  r*   r   s     r,   set_input_embeddingsz Gemma2Model.set_input_embeddings  s
    !r-   	input_idsr   rx   r"  inputs_embedsr   r   output_hidden_statesreturn_dictr   r   c                 6   ||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        j                  d       d}|| j                  |      }|rL|J| j                  s>|j                  \  }}}t        | j                   ||| j                  |j                        }|
F||j                         nd}t!        j"                  |||j                  d   z   |j                        }
||
j%                  d      }| j'                  |||
||      }|}t!        j(                  | j                   j*                  dz  |j                  	      }||z  }|rd
nd }|rd
nd }| j,                  d | j                   j.                   D ]e  }|r||fz  }| j                  r/| j                  r#| j1                  |j2                  |||||||
      }n ||||||||
      }|d   }|s]||d   fz  }g | j5                  |      }|r||fz  }|r|nd }|	st7        d ||||fD              S t9        ||||      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_lenrg   r^   r   r   rg   g      ?r]    )r   rx   r   r   r   r   c              3   &   K   | ]	  }||  y wr"   r[  ).0vs     r,   	<genexpr>z&Gemma2Model.forward.<locals>.<genexpr>  s     tqfgfsts   )last_hidden_stater"  r   
attentions)rO   r   rU  r   use_return_dictr   rI  r   r   r   rC  r@   r
   rg   r^   get_seq_lengthr'   rd   r   _update_causal_maskr`   rP   rG  rF  _gradient_checkpointing_func__call__rH  r?   r   )r*   rS  r   rx   r"  rT  r   r   rU  rV  r   rX  ry   r   past_seen_tokensr   r   
normalizerall_hidden_statesall_self_attnsdecoder_layerlayer_outputs
next_caches                          r,   r=   zGemma2Model.forward  s    2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]-t";<YZZ&&4==Yj I  --i8M0%2%8%8"J)%%{{#))O !CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L..M>?L]

 &
 \\$++"9"93">mFYFYZ
%
2 #7BD0d![[)H4;;+H+HI 	6M#!m%55!**t}} $ A A!**! #%"	! !.!#.!-#2&7'#1! *!,M =#3"55;	6> 		-0-!11(1_t
t]J@QSa$bttt&+&+%	
 	
r-   input_tensorc           
      V   | j                   j                  dk(  r|S |j                  |j                  }}|j                  d   }t        |t              r|j                         }	n ||j                  d   n|j                  d   }	| j                  |||	||||j                  d         }
|
S )Nr   r   r0   r   sequence_lengthtarget_lengthr^   rg   r   rX  )	rO   r   r^   rg   r@   rq   r
   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_position)r*   r   rn  r   r"  r   r^   rg   rq  rr  r   s              r,   rd  zGemma2Model._update_causal_mask  s     ;;++/BB!!$**L,?,?v&,,Q/o{3+??AM8F8RN004XdXjXjklXmM PP+')#))!, Q 
 r-   rq  rr  r^   rg   rX  c                 f   | | j                         dk(  r| }|S t        j                  |      j                  }	t        j                  ||f|	||      }|dk7  rt        j
                  |d      }|t        j                  ||      |j                  dd      kD  z  }|ddddddf   j                  |ddd      }| s|j                         }| 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   j                  ||	      |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^   rg   r   r  rZ  r0   r   )r   r'   r  r  fulltriurd   r   ro   cloner@   masked_fill)r   rq  rr  r^   rg   r   rX  kwargsr   r  mask_lengthpadding_masks               r,   rt  zAGemma2Model._prepare_4d_causal_attention_mask_with_cache_position=  s`   B %.*<*<*>!*C(K& # E*..I** -0Ye\bK !##jjqA5<<fEH^H^_acdHeeeK%dD!Q&67>>z1bRTUK))//1,2226*1aL[L+@ANSTVZ\`bcScDdd+q05@Aq,;,AV5W5c5c )6Aq!\k\12 r-   
NNNNNNNNNN)rC   rD   rE   r   r   r$   rO  rR  r   GEMMA2_INPUTS_DOCSTRINGr'   r   r   r   r
   r  r   r   r   r   r=   r~   rd  staticmethodrF   r^   rg   rt  rG   rH   s   @r,   r>  r>    s   
| $!" ++BC '+15371559$(,0/3&*59q
##q
 !.q
 u//0	q

 "+.q
   1 12q
 D>q
 $D>q
 'tnq
 d^q
 !!1!12q
 
u--	.q
 Dq
f U]]_   ll  	 
 %      D 555 5 {{	5
 5 5 5 5r-   r>  c                       e Zd ZdgZddi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.weightlm_headcolwise_repc                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y rL   )
r#   r$   r>  r!  rB  r%   rR   rP   r  rL  rX   s     r,   r$   zGemma2ForCausalLM.__init__z  sU      (
 ++yy!3!3V5F5FUS 	r-   c                 .    | j                   j                  S r"   r!  rC  rA   s    r,   rO  z&Gemma2ForCausalLM.get_input_embeddings      zz&&&r-   c                 &    || j                   _        y r"   r  rQ  s     r,   rR  z&Gemma2ForCausalLM.set_input_embeddings      "'

r-   c                     | j                   S r"   r  rA   s    r,   get_output_embeddingsz'Gemma2ForCausalLM.get_output_embeddings  s    ||r-   c                     || _         y r"   r  )r*   new_embeddingss     r,   set_output_embeddingsz'Gemma2ForCausalLM.set_output_embeddings  s	    %r-   c                     || _         y r"   r!  )r*   decoders     r,   set_decoderzGemma2ForCausalLM.set_decoder  s	    
r-   c                     | j                   S r"   r  rA   s    r,   get_decoderzGemma2ForCausalLM.get_decoder  s    zzr-   )output_typer2  rS  r   rx   r"  rT  labelsr   r   rU  rV  r   num_logits_to_keepr   c                 D   | j                   rF| j                  j                  dk7  r-t        j	                  d| j                  j                   d       ||n| j                  j
                  }|	|	n| j                  j                  }	|
|
n| j                  j                  }
| j                  ||||||||	|
|
      }|d   }| j                  |dd| dddf         }| j                  j                  G|| j                  j                  z  }t        j                  |      }|| j                  j                  z  }d}| | j                  ||| j                  fi |}|
s|f|dd z   }||f|z   S |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)
rS  r   rx   r"  rT  r   r   rU  rV  r   r   r   losslogitsr"  r   ra  )r   rO   r   r   r   r   rU  rb  r!  r  final_logit_softcappingr'   r   loss_functionrB  r   r"  r   ra  )r*   rS  r   rx   r"  rT  r  r   r   rU  rV  r   r  loss_kwargsr  r   r  r  r<   s                      r,   r=   zGemma2ForCausalLM.forward  s   b ==T[[==H#{{??@  Aqr 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]**)%+'/!5#)  
  
mA0B/B/CQ,FGH;;..:dkkAAAFZZ'FdkkAAAF%4%%ffdooUUDY,F'+'7D7V#CVC%#33!//))
 	
r-   c	           	         |D||d d |j                   d    d f   }n(|j                   d   |j                   d   k7  r	|d d |f   }|t|r|j                         j                  d      dz
  }|j                  |dk(  d       |r9|d d |j                   d    d f   }|j	                  t
        j                        }||d   dk(  r|d d}
n#|j	                  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                   j"                  j$                  |||      }|||
d<   |
j'                  |||||d       |
S )Nr   r   r0   )memory_format)rT  rS  )rS  rT  r/   r   rT  rS  rp  r  )rx   r   r"  r   r   )r@   longcumsummasked_fill_rz  r'   contiguous_formatrq   r
   ndimrO   r   rg   r!  rt  rs  r  r)   r^   r   )r*   rS  r"  r   rT  r   rx   r   r  r|  model_inputsrX  rq  r   rg   s                  r,   prepare_inputs_for_generationz/Gemma2ForCausalLM.prepare_inputs_for_generation  s   " &(%a.*>*>q*A)A)C&CD	#~';';A'>>%a&78	%,*>)..077;a?L%%n&91=+A	0B/B/D,DE  ,11@W@W1X $):a)?-:NL *3uG^G^)_rvwL 4##q(KK448KKO,81=o1N1T1T.
OQ%o6==.:;.G.M.M+
O%k299!ZZ]] /-AACll))//-% ^ N )1CL-. ,"0#2&"0	
 r-   )NNNNNNNNNNNr   )NNNNNTN)rC   rD   rE   _tied_weights_keys_tp_planr$   rO  rR  r  r  r  r  r   r  r   r   _CONFIG_FOR_DOCr'   r   r   r   r
   r  r   rF   r   r   r=   r  rG   rH   s   @r,   r  r  v  s   *+=)H'(& ++BC+AP_` '+15371559-1$(,0/3&*59"#]
##]
 !.]
 u//0	]

 "+.]
   1 12]
 ))*]
 D>]
 $D>]
 'tn]
 d^]
 !!1!12]
  ]
 
u,,	-]
 a D]
D Lr-   r  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                   X    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      | _        | j                          y rL   )
r#   r$   
num_labelsr>  r!  r%   rR   rP   r   rL  rX   s     r,   r$   z(Gemma2ForSequenceClassification.__init__U  sS      ++ (
YYv114??O
 	r-   c                 .    | j                   j                  S r"   r  rA   s    r,   rO  z4Gemma2ForSequenceClassification.get_input_embeddings^  r  r-   c                 &    || j                   _        y r"   r  rQ  s     r,   rR  z4Gemma2ForSequenceClassification.set_input_embeddingsa  r  r-   rS  r   rx   r"  rT  r  r   r   rU  rV  r   c                 f   |
|
n| j                   j                  }
| j                  ||||||||	|
	      }|d   }| j                  |      }||j                  d   }n|j                  d   }| j                   j
                  |dk7  rt        d      | j                   j
                  d}n||xt        j                  || j                   j
                        j                         j                  d      dz
  }||j                  d   z  }|j                  |j                        }nd}|t        j                  ||j                        |f   }d}|| j                  |||| j                         }|
s|f|dd z   }||f|z   S |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   rx   r"  rT  r   r   rU  rV  r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r0   rZ  )r  r  pooled_logitsrO   r  )rO   rb  r!  r   r@   rA  r   r'   eqrF   argmaxrn   rg   rd   r  r   r"  r   ra  )r*   rS  r   rx   r"  rT  r  r   r   rU  rV  transformer_outputsr   r  rX  sequence_lengthsr  r  r<   s                      r,   r=   z'Gemma2ForSequenceClassification.forwardd  s   ( &1%<k$++B]B]"jj)%+'/!5# ) 

 ,A.M* "+J&,,Q/J;;##+
a\]];;##+!$#(88It{{7O7O#P#T#T#V#]#]^`#ade#e #3ioob6I#I #3#6#6v}}#E #% u||Jv}}MO__`%%VFR_hlhshs%tD#%(;AB(??F)-)9TGf$EvE/ /??-;;*55
 	
r-   r  )rC   rD   rE   r$   rO  rR  r   r  r   r'   r   r   r   r	   r   r  r   r   r   r=   rG   rH   s   @r,   r  r  E  s0    '( ++BC 151537KO59-1$(,0/3&*E
E,,-E
 !.E
 u//0	E

 "%tE4E4E/F(F"GHE
   1 12E
 ))*E
 D>E
 $D>E
 'tnE
 d^E
 
u66	7E
 D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                   j    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                        | _        | j                          y )Nclassifier_dropouthidden_dropoutg?)r#   r$   r  r>  r!  rJ  r  r  r%   Dropoutr   rR   rP   r   rL  )r*   rO   r  r+   s      r,   r$   z%Gemma2ForTokenClassification.__init__  s      ++ (
6/6B!'!:!:V-t4@!'!6!6!$zz"45YYv1163D3DE
 	r-   c                 .    | j                   j                  S r"   r  rA   s    r,   rO  z1Gemma2ForTokenClassification.get_input_embeddings  r  r-   c                 &    || j                   _        y r"   r  rQ  s     r,   rR  z1Gemma2ForTokenClassification.set_input_embeddings  r  r-   )
checkpointr  r2  rS  r   rx   r"  rT  r  r   r   rU  rV  r   c                 j   |
|
n| j                   j                  }
| j                  ||||||||	|
	      }|d   }| j                  |      }| j	                  |      }d}|| j                  ||| j                         }|
s|f|dd z   }||f|z   S |S t        |||j                  |j                        S )r  Nr  r   r/   )r  r  r   ra  )	rO   rb  r!  r   r   r  r   r   ra  )r*   rS  r   rx   r"  rT  r  r   r   rU  rV  r  sequence_outputr  r  r<   s                   r,   r=   z$Gemma2ForTokenClassification.forward  s    2 &1%<k$++B]B]**)%+'/!5#  

 "!*,,7O,%%ffdkkBDY,F)-)9TGf$EvE$!//))	
 	
r-   r  )rC   rD   rE   r$   rO  rR  r   r  r   _CHECKPOINT_FOR_DOCr   r  r   r'   r   r   r   r  r   r   r   r=   rG   rH   s   @r,   r  r    s/    '( ++BC&)$ 151537=A59-1$(,0/3&*1
E,,-1
 !.1
 u//0	1

 "$u'8'8"9:1
   1 121
 ))*1
 D>1
 $D>1
 'tn1
 d^1
 
u++	,1
 D1
r-   r  )Nr   r1  )Ftypingr   r   r   r   r'   torch.nnr%   activationsr   cache_utilsr	   r
   
generationr   modeling_outputsr   r   r   r   modeling_utilsr   utilsr   r   r   r   r   r   r   r   configuration_gemma2r   modeling_flash_attention_utilsr   !torch.nn.attention.flex_attentionr   
get_loggerrC   r   r  r  Moduler   rJ   r[   r   r   r   rF   r   r   float16r^   r   r   r   r   r   r   r   r  r  GEMMA2_START_DOCSTRINGr   r  r>  r  r  r  r[  r-   r,   <module>r     s  , 0 /   ! - )  .	 	 	 / JU#@			H	% )  =BII =(P		 P<BII <8(6	UU\\ 	U# 	U%,, 	U%%<<% 
% <<	%
 5<<
 % 5<<%&%F !&**<<* 
* <<	*
 5<<
 * ++* 5<<*f $%%<<% 
% <<	%
 5<<
 % % 5<<%,,//0%D$$<<$ 
$ <<	$
 5<<
 $ 5<<$P 1,$"	 U9bii U9p
O 

/ 
F FR " Z#O #	#LH V Zm' m	m`L- L^  V
&; V
V
r  N
#8 N
N
r-   