
    Pg                        d dl mZ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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 ddlmZ ddlm Z m!Z!m"Z"m#Z#m$Z$ ddl%m&Z& ddl'm(Z(  e#jR                  e*      Z+dZ,dZ- G d dej\                        Z/ G d dej\                        Z0d Z1d;dZ2dejf                  de4dejf                  fdZ5	 	 	 d<dej\                  dejf                  dejf                  dejf                  d eejf                     d!e6d"ee6   d#ee6   deejf                  ejf                  f   fd$Z7 G d% d&ej\                        Z8 G d' d(ej\                        Z9 G d) d*ej\                        Z:d+Z; e!d,e;       G d- d.e             Z<d/Z= e!d,e;       G d0 d1e<             Z> G d2 d3e<e      Z? e!d4e;       G d5 d6e<             Z@ e!d7e;       G d8 d9e<             ZAg d:ZBy)=    )CallableListOptionalTupleUnionN   )ACT2FN)CacheHybridCacheStaticCache)GenerationMixin)FlashAttentionKwargs)BaseModelOutputWithPastCausalLMOutputWithPast SequenceClassifierOutputWithPastTokenClassifierOutput)ROPE_INIT_FUNCTIONS)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings)deprecate_kwarg   )Gemma2Configz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      q/var/www/html/suriana-translation/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._norm@   s4    5;;quuQx}}R}>IJJJr/   c                     | j                  |j                               }|d| j                  j                         z   z  }|j                  |      S )Ng      ?)r8   floatr+   type_as)r,   r7   outputs      r.   forwardzGemma2RMSNorm.forwardC   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_reprJ   s'    ))*+6$((<<r/   )gư>)
__name__
__module____qualname__intr:   r&   r8   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__O   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   )r,   r7   rU   s      r.   r=   zGemma2MLP.forwardY   s6    NN4;;t~~a/@#ADLLQRO#ST	r/   )rC   rD   rE   r&   r=   rG   rH   s   @r.   rJ   rJ   N   s    7r/   rJ   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..Nr2   r1   r!   )r@   r)   cat)r7   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kcossinposition_idsunsqueeze_dimq_embedk_embeds           r.   apply_rotary_pos_embrj   e   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@   expandreshape)rk   rl   batchnum_key_value_headsslenhead_dims         r.   	repeat_kvru      so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr/   modulequerykeyvalueattention_maskdropoutscalingsoftcapc                    || j                   dz  }t        || j                        }	t        || j                        }
t        j                  ||	j                  dd            |z  }|||z  }t        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                        }t        j                  ||
      }|j                  dd      j!                         }||fS )	N      r1   r   r2   )r!   dtype)ptrainingr   )rt   ru   num_key_value_groupsr)   matmul	transposetanhr@   r'   
functionalsoftmaxfloat32tor   r{   r   
contiguous)rv   rw   rx   ry   rz   r{   r|   r}   kwargs
key_statesvalue_statesattn_weightscausal_maskattn_outputs                 r.   eager_attention_forwardr      sA    //4'3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL#g-zz,/#g-!$Q1.D
0@0@0D.D%DE#k1 ==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r/   c                   6    e Zd ZdZdedef fdZ	 	 ddej                  de	ej                  ej                  f   de
ej                     de
e   d	e
ej                     d
ee   de	ej                  e
ej                     e
e	ej                        f   fdZ xZS )Gemma2Attentionz=Multi-headed attention from 'Attention Is All You Need' paperrO   	layer_idxc                    t         |           || _        || _        t	        |d|j
                  |j                  z        | _        |j                  |j                  z  | _	        |j                  dz  | _        | j                  j                  | _        d| _        t        j                  |j
                  |j                  | j                  z  |j                         | _        t        j                  |j
                  |j                  | j                  z  |j                         | _        t        j                  |j
                  |j                  | j                  z  |j                         | _        t        j                  |j                  | j                  z  |j
                  |j                         | _        | j                  j*                  | _        t-        |dz        s|j.                  | _        y d | _        y )Nrt   r   TrM   r1   )r%   r&   rO   r   getattrrP   num_attention_headsrt   rr   r   query_pre_attn_scalarr|   attention_dropout	is_causalr'   rR   attention_biasq_projk_projv_projo_projattn_logit_softcappingboolsliding_windowr,   rO   r   r-   s      r.   r&   zGemma2Attention.__init__   s   "
F4F4F&JdJd4de$*$>$>&B\B\$\!33T9!%!>!>ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf
 '+kk&H&H#;?	A;Nf33TXr/   rk   position_embeddingsrz   past_key_valuecache_positionr   rm   c                    |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }	| j                  |      j                  |      j	                  dd      }
| j                  |      j                  |      j	                  dd      }|\  }}t        |	|
||      \  }	}
|~|||| j                  d}|j                  |
|| j                  |      \  }
}|J| j                  j                  dk(  r1|j                   d   }|
d d d d d |d d f   |d d d d d |d d f   }}
t        }| j                  j                  dk7  r^| j                  j                  dk(  r(|j                  dd	      rt        j!                  d
       nt"        | j                  j                     } || |	|
||f| j$                  r| j&                  nd| j(                  | j                  | j*                  d|\  }} |j,                  g |d j/                         }| j1                  |      }||fS )Nr2   r   r1   )re   rd   r   r   flash_attention_2eagersdpaoutput_attentionsFz`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.        )r{   r|   r   r}   )r@   rt   r   viewr   r   r   rj   r   updater   rO   _attn_implementationr   getloggerwarning_oncer   r   r   r|   r   rp   r   r   )r,   rk   r   rz   r   r   r   input_shapehidden_shapequery_statesr   r   rd   re   cache_kwargsseq_lenattention_interfacer   r   s                      r.   r=   zGemma2Attention.forward   sa    $))#2.88b8$--8{{=166|DNNqRST[[/44\BLLQPQR
{{=166|DNNqRST&S#7jRUWZ#[ j% "0"&"5"5	L (6'<'<ZW[WeWegs't$J )dkk.N.NRe.e(..r2+5aHWHa6G+H,WXZ[]e^e]eghWhJiL
(?;;++w6{{//69fjjI\^c>d##L
 '>dkk>^>^&_#$7%
 /3mmD**LL..//%
 %
!\ *k));;;;FFHkk+.L((r/   )NN)rC   rD   rE   __doc__r   rF   r&   r)   Tensorr   r   r
   
LongTensorr   r   r=   rG   rH   s   @r.   r   r      s    GY| Y Y< +/59;)||;) #5<<#=>;) !.	;)
 !;) !!1!12;) -.;) 
u||Xell3XeELL>Q5RR	S;)r/   r   c                   d    e Zd Zdedef fdZ	 	 	 	 	 	 	 ddej                  deej                  ej                  f   de	ej                     de	ej                     de	e   d	e	e   d
e	e   de	ej                     de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 )Nr1   )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/   rk   r   rz   rf   r   r   	use_cacher   last_cache_positionrm   c
                     | j                   r|t        |j                  d   | j                        }| j                  j
                  dk(  r|d d | d f   }nt        j                  |j                        j                  }t        j                  t        j                  |t        j                        | j                         }t        j                  |||      }|	|z
  }t        d|      }|d d d d d d |||z   f   }|}| j                  |      } | j                  d||||||||d|
\  }}| j!                  |      }||z   }|}| j#                  |      }| j%                  |      }| j'                  |      }||z   }|f}|r||fz  }|S )Nr   r   r   diagonal)rk   r   rz   rf   r   r   r   r    )r   maxr@   r   rO   r   r)   finfor   mintril	ones_liker   wherer   r   r   r   r   r   )r,   rk   r   rz   rf   r   r   r   r   r   r   effective_seq_len	min_dtypesliding_window_maskoffsetresidualself_attn_weightsoutputss                     r.   r=   zGemma2DecoderLayer.forward  s    ??~9 #N$8$8$;T=P=P Q {{//3FF!/4E3E3F0F!G "KK(<(<=AA	&+jjOON%**EQUQdQdPd'# "'-@)^!\ -/@@Q!/1a&K\B\9\0\!] ,,]; ,:4>> 
,
' 3)%)/)
,
 
,
(( 55mD =0 66}E/77F =0 ")++Gr/   )NNNFFNr   )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#$A||A #5<<#=>A !.	A
 u//0A !A $D>A D>A !!1!12A !A 
u  (51B1BEDUDU1U+V"WW	XAr/   r   c                   Z     e Zd Zddef fdZd Z ej                         d        Z xZ	S )Gemma2RotaryEmbeddingrO   c                    t         |           t        |d      rG|j                  ;|j                  j	                  d|j                  j	                  d            | _        nd| _        |j                  | _        |j                  | _        || _	        t        | j
                     | _        | j                  | j                  |      \  }| _        | j                  d|d       | j                  | _        y )Nrope_scaling	rope_typetypedefaultinv_freqF
persistent)r%   r&   hasattrr   r   r   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrO   r   rope_init_fnattention_scalingregister_bufferr   original_inv_freq)r,   rO   devicer   r-   s       r.   r&   zGemma2RotaryEmbedding.__init__]  s    6>*v/B/B/N#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q($(ZeD!%r/   c                    t        j                  |      dz   }|| j                  kD  rA| j                  | j                  ||      \  }| _        | j                  d|d       || _        || j                  k  rj| j                  | j                  kD  rP| j                  j                  |      | _        | j                  d| j                  d       | j                  | _        yyy)a  
        dynamic RoPE layers should recompute `inv_freq` in the following situations:
        1 - growing beyond the cached sequence length (allow scaling)
        2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
        r   )r   r   Fr   N)
r)   r   r   r   rO   r   r   r   r   r   )r,   rf   r   r   r   s        r.   _dynamic_frequency_updatez/Gemma2RotaryEmbedding._dynamic_frequency_updaten  s     ))L)A-T,,,/3/@/@f^e/@/f,Hd,  X% H&-D#T...43J3JTMfMf3f &*%;%;%>%>v%FD"  T-C-CPU V&*&?&?D# 4g.r/   c                 t   d| j                   v r| 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                  |j                        |j	                         z  j                  dd
      }t        j                  ||fd      }|j                         }|j!                         }	d d d        | j"                  z  }	| j"                  z  }	|j                  |j$                        |	j                  |j$                        fS # 1 sw Y   _xY w)Ndynamicr   r   r2   r   mpscpuF)device_typeenabledr1   r[   r   )r   r   r   r   r:   ro   r@   r   
isinstancestrr)   autocastr   r   r\   rd   re   r   r   )
r,   r7   rf   inv_freq_expandedposition_ids_expandedr   freqsembrd   re   s
             r.   r=   zGemma2RotaryEmbedding.forward  su   &**<*I !MM$4-8>>@GGHZHZ[\H]_acde ,QaZ 8 > > @hhmm%/S%AkUZFZk`e^^UC 	&,,.11!((;>S>Y>Y>[[ffghjklE))UEN3C'')C'')C		 D***D***vvAGGv$cff177f&;;;	 	s   BF..F7r$   )
rC   rD   rE   r   r&   r   r)   no_gradr=   rG   rH   s   @r.   r   r   \  s1    /| /"@& U]]_< <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                   F    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dZd Zy)Gemma2PreTrainedModelmodelTr   past_key_valuesc                    | 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   )r6   std)rO   initializer_ranger   r'   rR   r+   datanormal_rN   zero_	Embeddingpadding_idx)r,   rv   r  s      r.   _init_weightsz#Gemma2PreTrainedModel._init_weights  s    kk++fbii(MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> . .r/   N)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_flex_attn_supports_cache_class_supports_quantized_cache_supports_static_cache_supports_attention_backendr  r   r/   r.   r  r    sU    
  L&*#-.#4"5!N  $!"&	?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                   L    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   dee   deeef   fd       Z e
j0                         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
j6                  de
j8                  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           	         t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        t#        |      | _        d| _        | j)                          y c c}w )Nr   )rO   F)r%   r&   pad_token_idr  
vocab_sizer'   r  rP   embed_tokens
ModuleListrangenum_hidden_layersr   layersr    r   normr   
rotary_embgradient_checkpointing	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	/v>&+# 	 es   Dc                     | j                   S r$   r!  rA   s    r.   get_input_embeddingsz Gemma2Model.get_input_embeddings/  s       r/   c                     || _         y r$   r+  r,   ry   s     r.   set_input_embeddingsz Gemma2Model.set_input_embeddings2  s
    !r/   	input_idsrz   rf   r  inputs_embedsr   r   output_hidden_statesreturn_dictr   r   flash_attn_kwargsrm   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        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      }|9d}|5|j'                         dk(  r|j                  d	   n|
d	   j)                         }| j+                  |||
||      }|}| j-                  ||      }t!        j.                  | j                   j0                  d
z  |j                        }||z  }|rdnd }|rdnd }| j2                  d | j                   j4                   D ]j  }|r||fz  }| j                  r1| j                  r%| j7                  |j8                  ||||||||
|
      }n ||f|||||||
|d|}|d   }|sb||d   fz  }l | j;                  |      }|r||fz  }t=        ||||      }|	r|S |j?                         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)max_batch_sizemax_cache_lenr   r   r   r   r   r1   r2   g      ?r   r   )r   rz   rf   r   r   r   r   r   )last_hidden_stater  rk   
attentions) rO   r   r2  r   use_return_dict
ValueErrorr(  r   r   r   r!  r@   r   r   r   get_seq_lengthr)   arangera   r!   item_update_causal_maskr'  tensorrP   r%  r$  _gradient_checkpointing_func__call__r&  r   to_tuple)r,   r0  rz   rf   r  r1  r   r   r2  r3  r   r   r4  
batch_sizer   _past_seen_tokensr   rk   r   
normalizerall_hidden_statesall_self_attnsdecoder_layerlayer_outputsr<   s                             r.   r=   zGemma2Model.forward5  sW     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 &"#) 1?0B0B0D0IN((,~^`OaOfOfOh $ ..M>?L]

 & #oom\J
 \\$++"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E"	6H 		-0-!11(+++%	
 %v;&//*;;r/   input_tensorc           
      b   | j                   j                  dk(  r|S |j                  |j                  }}|j                  d   }t        |t        t        f      r|j                         }	n ||j                  d   n|j                  d   }	| j                  |||	||||j                  d         }
|
S )Nr   r   r2   r   sequence_lengthtarget_lengthr   r   r   rD  )
rO   r   r   r   r@   r   r   r   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_position)r,   rz   rL  r   r  r   r   r   rO  rP  r   s              r.   r?  zGemma2Model._update_causal_mask  s     ;;++/BB!!$**L,?,?v&,,Q/o['AB+??AM8F8RN004XdXjXjklXmM PP+')#))!, Q 
 r/   rO  rP  r   r   rD  c                    | | 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      }| |j                         }| j                  d   }
|ddddddd|
f   | ddddddf   j                  |j                        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 place 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   r   r   r   r   r2   r   )r!   r)   r   r   fulltriur=  rp   ro   cloner@   r   r   masked_fill)rz   rO  rP  r   r   r   rD  r   r   r   mask_lengthpadding_masks               r.   rR  zAGemma2Model._prepare_4d_causal_attention_mask_with_cache_position  sy   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\`bcScDdDgDg&&E    ,q05@Aq,;,AV5W5c5c )6Aq!\k\12 r/   )NNNNNNNNNNN)rC   rD   rE   r   r   r&   r,  r/  r   GEMMA2_INPUTS_DOCSTRINGr)   r   r   r   r   r   r   rF   r   r   r   r   r   r=   r  r?  staticmethodr   r   rR  rG   rH   s   @r.   r  r    s   
|  !" ++BC '+15371559$(,0/3&*59-1C<##C< !.C< u//0	C<
 "+.C<   1 12C< D>C< $D>C< 'tnC< d^C< !!1!12C< &c]C< $$89C< 
u--	.C< DC<J U]]_   ll  	 
 %      D 777 7 {{	7
 7 7 7 7r/   r  c                        e Zd ZdgZddiZddgdgfiZ fdZd Zd Zd	 Z	d
 Z
d Zd Z eddd       ee       eee      	 	 	 	 	 	 	 	 	 	 	 	 d dej(                  deej,                     deej(                     dee   deej0                     deej(                     dee   dee   dee   dee   deej(                     deeej,                  f   deeef   fd                     Z	 	 	 	 	 	 	 d! fd	Z xZS )"Gemma2ForCausalLMzlm_head.weightlm_headcolwise_reprk   logitsc                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y rL   )
r%   r&   r  r  r   r'   rR   rP   r`  r)  rX   s     r.   r&   zGemma2ForCausalLM.__init__  sU      (
 ++yy!3!3V5F5FUS 	r/   c                 .    | j                   j                  S r$   r  r!  rA   s    r.   r,  z&Gemma2ForCausalLM.get_input_embeddings'      zz&&&r/   c                 &    || j                   _        y r$   re  r.  s     r.   r/  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$   rj  )r,   new_embeddingss     r.   set_output_embeddingsz'Gemma2ForCausalLM.set_output_embeddings0  s	    %r/   c                     || _         y r$   r  )r,   decoders     r.   set_decoderzGemma2ForCausalLM.set_decoder3  s	    
r/   c                     | j                   S r$   rp  rA   s    r.   get_decoderzGemma2ForCausalLM.get_decoder6  s    zzr/   num_logits_to_keepz4.50logits_to_keep)versionnew_name)output_typer  r0  rz   rf   r  r1  labelsr   r   r2  r3  r   rm   c                    | j                   rF| j                  j                  dk7  r-t        j	                  d| j                  j                   d       ||n| j                  j
                  }|	|	n| j                  j                  }	|
|
n| j                  j                  }
 | j                  d	||||||||	|
|d
|}|d   }t        |t              rt        | d      n|}| j                  |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  
            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]`.

            logits_to_keep (`int` or `torch.Tensor`, *optional*):
                If an `int`, compute logits for the last `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.
                If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
                This is useful when using packed tensor format (single dimension for batch and sequence length).

        Returns:

        Example:

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

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

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

        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "What is your favorite condiment?"
        ```r   zhIt is strongly recommended to train Gemma2 models with the `eager` attention implementation instead of `zp`. Use `eager` with `AutoModelForCausalLM.from_pretrained('<path-to-checkpoint>', attn_implementation='eager')`.N)
r0  rz   rf   r  r1  r   r   r2  r3  r   r   r   lossrb  r  rk   r9  r   )r   rO   r   r   r   r   r2  r:  r  r   rF   slicer`  final_logit_softcappingr)   r   loss_functionr   r   r  rk   r9  )r,   r0  rz   rf   r  r1  rz  r   r   r2  r3  r   rv  loss_kwargsr   rk   slice_indicesrb  r}  r<   s                       r.   r=   zGemma2ForCausalLM.forward9  s   f ==T[[==H#{{??@  Aqr 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]$** 
)%+'/!5#)
 
  
8B>SV8W~ot4]kmA}a,?@A;;..:dkkAAAFZZ'FdkkAAAF%4%%ffdooUUDY,F'+'7D7V#CVC%#33!//))
 	
r/   c	                 4   t        |   |f|||||||d|	}
||j                  d   nd|
d<   ||
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<   |
S )N)r  rz   r1  r   rf   r   rv  r2   r   r   rv  r1   r   r1  r0  rN  rz   )r%   prepare_inputs_for_generationr@   popr   r   ndimrO   r   r   r  rR  rQ  r`  r+   r   )r,   r0  r  rz   r1  r   rf   r   rv  r   model_inputsrE  rD  rO  r   r-   s                  r.   r  z/Gemma2ForCausalLM.prepare_inputs_for_generation  sU    w<

+)')%)

 

 KYJdn.B.B2.Fjk*+!  !148A 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 .<L)*r/   )NNNNNNNNNNNr   )NNNNNTN) rC   rD   rE   _tied_weights_keys_tp_plan_pp_planr&   r,  r/  rk  rn  rr  rt  r   r   r\  r   r   _CONFIG_FOR_DOCr)   r   r   r   r   r   r   r   rF   r   r=   r  rG   rH   s   @r.   r_  r_    s   *+=)H_-z:;H'(& )6DTU*+BC+AP_` '+15371559-1$(,0/3&*5934`
##`
 !.`
 u//0	`

 "+.`
   1 12`
 ))*`
 D>`
 $D>`
 'tn`
 d^`
 !!1!12`
 c5<</0`
 
u,,	-`
 a D V`
J 7 7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   scorer)  rX   s     r.   r&   z(Gemma2ForSequenceClassification.__init__  sS      ++ (
YYv114??O
 	r/   c                 .    | j                   j                  S r$   re  rA   s    r.   r,  z4Gemma2ForSequenceClassification.get_input_embeddings  rf  r/   c                 &    || j                   _        y r$   re  r.  s     r.   r/  z4Gemma2ForSequenceClassification.set_input_embeddings  rh  r/   r0  rz   rf   r  r1  rz  r   r   r2  r3  rm   c                    |
|
n| j                   j                  }
| j                  ||||||||	|
	      }|d   }| j                  |      }||j                  d   }n|j                  d   }| j                   j
                  |dk7  rt        d      | j                   j
                  d}n||| j                   j
                  k7  j                  |j                  t        j                        }t        j                  |j                  d   |j                  t        j                        }||z  j                  d      }n.d}t        j                  | j                  j                    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rz   rf   r  r1  r   r   r2  r3  r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r2   )r   r   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`r   )rb  rz  pooled_logitsrO   r|  )rO   r:  r  r  r@   r  r;  r   r   r)   int32r=  argmaxr   r   r-   rC   r  r   r  rk   r9  )r,   r0  rz   rf   r  r1  rz  r   r   r2  r3  transformer_outputsrk   rb  rD  last_non_pad_tokennon_pad_masktoken_indicesr  r}  r<   s                        r.   r=   z'Gemma2ForSequenceClassification.forward  s   ( &1%<k$++B]B]"jj)%+'/!5# ) 

 ,A.M* "+J&,,Q/J;;##+
a\]];;##+!#"%)A)AAEEfmmUZU`U`aL!LL)<V]]Z_ZeZefM"/,">!F!Fr!J!#>>**+ ,Z Z
 u||Jv}}MOaab%%VFR_hlhshs%tD#%(;AB(??F)-)9TGf$EvE/ /??-;;*55
 	
r/   
NNNNNNNNNN)rC   rD   rE   r&   r,  r/  r   r\  r   r)   r   r   r   r
   r   r   r   r   r   r=   rG   rH   s   @r.   r  r    s0    '( ++BC 151537KO59-1$(,0/3&*H
E,,-H
 !.H
 u//0	H

 "%tE4E4E/F(F"GHH
   1 12H
 ))*H
 D>H
 $D>H
 'tnH
 d^H
 
u66	7H
 DH
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  r   r  r  r'   Dropoutr{   rR   rP   r  r)  )r,   rO   r  r-   s      r.   r&   z%Gemma2ForTokenClassification.__init__K  s      ++ (
6/6B!'!:!:V-t4@!'!6!6!$zz"45YYv1163D3DE
 	r/   c                 .    | j                   j                  S r$   re  rA   s    r.   r,  z1Gemma2ForTokenClassification.get_input_embeddings[  rf  r/   c                 &    || j                   _        y r$   re  r.  s     r.   r/  z1Gemma2ForTokenClassification.set_input_embeddings^  rh  r/   )
checkpointry  r  r0  rz   rf   r  r1  rz  r   r   r2  r3  rm   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   r1   )r}  rb  rk   r9  )	rO   r:  r  r{   r  r  r   rk   r9  )r,   r0  rz   rf   r  r1  rz  r   r   r2  r3  r   sequence_outputrb  r}  r<   s                   r.   r=   z$Gemma2ForTokenClassification.forwarda  s    2 &1%<k$++B]B]**)%+'/!5#  

 "!*,,7O,%%ffdkkBDY,F)-)9TGf$EvE$!//))	
 	
r/   r  )rC   rD   rE   r&   r,  r/  r   r\  r   _CHECKPOINT_FOR_DOCr   r  r   r)   r   r   r   r   r   r   r   r=   rG   rH   s   @r.   r  r  C  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  )r_  r  r  r  r  )Nr   )r   NN)Ctypingr   r   r   r   r   r)   torch.nnr'   activationsr	   cache_utilsr
   r   r   
generationr   modeling_flash_attention_utilsr   modeling_outputsr   r   r   r   modeling_rope_utilsr   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   r   utils.deprecationr   configuration_gemma2r   
get_loggerrC   r   r  r  Moduler    rJ   r_   rj   r   rF   ru   r:   r   r   r   r   GEMMA2_START_DOCSTRINGr  r\  r  r_  r  r  __all__r   r/   r.   <module>r     se  , : 9   ! : : ) B  7 F &  1 . 
		H	% )  =BII =(		  (6	UU\\ 	U# 	U%,, 	U$ ## %II %<< % 
 % <<	 %
 U\\* %  % e_ % e_ % 5<<%& %FW)bii W)tP Pf:<BII :<z " Z?O ?	?4H V Z' 	D|- |~  Y
&; Y
Y
x  N
#8 N
N
br/   