
    Uh                        d dl mZ 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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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)  e$       rd dl*m+Z+ ddl,m-Z-  e%j\                  e/      Z0 G d de	jb                        Z2 G d de	jb                        Z3d Z4d9dZ5dejl                  de7dejl                  fdZ8	 	 	 d:de	jb                  dejl                  dejl                  d ejl                  d!eejl                     d"e9d#ee9   d$ee9   deejl                  ejl                  f   fd%Z: G d& d'e	jb                        Z; G d( d)e	jb                        Z< G d* d+e	jb                        Z=e" G d, d-e             Z>e" G d. d/e>             Z?e" G d0 d1e>e             Z@ e"d23       G d4 d5e>             ZAe" G d6 d7e>             ZBg d8ZCy);    )partial)CallableOptionalTupleUnionN   )ACT2FN)CacheHybridCacheStaticCache)GenerationMixin)FlashAttentionKwargs)BaseModelOutputWithPastCausalLMOutputWithPast SequenceClassifierOutputWithPastTokenClassifierOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)auto_docstringcan_return_tupleis_torch_flex_attn_availablelogging)deprecate_kwarg   )Gemma2Config)	BlockMask)make_flex_block_causal_maskc                   <     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/catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/transformers/models/gemma2/modeling_gemma2.pyr(   zGemma2RMSNorm.__init__8   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     r0   _normzGemma2RMSNorm._norm=   s4    5;;quuQx}}R}>IJJJr1   c                     | j                  |j                               }|d| j                  j                         z   z  }|j                  |      S )N      ?)r:   floatr-   type_as)r.   r9   outputs      r0   forwardzGemma2RMSNorm.forward@   sC    AGGI& 3!2!2!445~~a  r1   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler-   shaper$   r.   s    r0   
extra_reprzGemma2RMSNorm.extra_reprG   s'    ))*+6$((<<r1   )gư>)
__name__
__module____qualname__intr=   r(   r:   r@   rE   __classcell__r/   s   @r0   r"   r"   7   s&    5C 5e 5
K!=r1   r"   c                   $     e Zd Z fdZd Z xZS )	Gemma2MLPc                    t         |           || _        |j                  | _        |j                  | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _	        t        |j                     | _        y NFbias)r'   r(   confighidden_sizeintermediate_sizer)   Linear	gate_projup_proj	down_projr	   hidden_activationact_fnr.   rR   r/   s     r0   r(   zGemma2MLP.__init__L   s    !--!'!9!94#3#3T5K5KRWXyy!1!143I3IPUV4#9#94;K;KRWXV556r1   c                     | j                  | j                  | j                  |            | j                  |      z        }|S r&   )rX   rZ   rV   rW   )r.   r9   rX   s      r0   r@   zGemma2MLP.forwardV   s6    NN4;;t~~a/@#ADLLQRO#ST	r1   )rF   rG   rH   r(   r@   rJ   rK   s   @r0   rM   rM   K   s    7r1   rM   c                     | dd| j                   d   dz  f   }| d| j                   d   dz  df   }t        j                  | |fd      S )z*Rotates half the hidden dims of the input..Nr4   r3   r#   )rC   r+   cat)r9   x1x2s      r0   rotate_halfrb   [   sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r1   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.
    )	unsqueezerb   )qkcossinposition_idsunsqueeze_dimq_embedk_embeds           r0   apply_rotary_pos_embrm   b   sY    ( --
&C
--
&C3w;q>C/0G3w;q>C/0GGr1   hidden_statesn_repreturnc                     | j                   \  }}}}|dk(  r| S | dddddddddf   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)rC   expandreshape)rn   ro   batchnum_key_value_headsslenhead_dims         r0   	repeat_kvrx   }   so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr1   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      r3   r   r4   )r#   dtype)ptrainingr   )rw   rx   num_key_value_groupsr+   matmul	transposetanhrC   r)   
functionalsoftmaxfloat32tor   r~   r   
contiguous)ry   rz   r{   r|   r}   r~   r   r   kwargs
key_statesvalue_statesattn_weightscausal_maskattn_outputs                 r0   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$$r1   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' paperrR   	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 )Nrw   r   TrP   r3   )r'   r(   rR   r   getattrrS   num_attention_headsrw   ru   r   query_pre_attn_scalarr   attention_dropout	is_causalr)   rU   attention_biasq_projk_projv_projo_projattn_logit_softcappingboolsliding_windowr.   rR   r   r/   s      r0   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r1   rn   position_embeddingsr}   past_key_valuecache_positionr   rp   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 )Nr4   r   r3   )rh   rg   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   )rC   rw   r   viewr   r   r   rm   r   updater   rR   _attn_implementationr   getloggerwarning_oncer   r   r   r   r   rs   r   r   )r.   rn   r   r}   r   r   r   input_shapehidden_shapequery_statesr   r   rg   rh   cache_kwargsseq_lenattention_interfacer   r   s                      r0   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((r1   )NN)rF   rG   rH   __doc__r   rI   r(   r+   Tensorr   r   r
   
LongTensorr   r   r@   rJ   rK   s   @r0   r   r      s    GY| Y Y< +/59;)||;) #5<<#=>;) !.	;)
 !;) !!1!12;) -.;) 
u||Xell3XeELL>Q5RR	S;)r1   r   c                   x    e Zd Zdedef fdZ edd      	 	 	 	 	 	 ddej                  de	ej                  ej                  f   d	e
ej                     d
e
ej                     de
e   de
e   de
e   de
ej                     de	ej                  e
e	ej                  ej                  f      f   fd       Z xZS )Gemma2DecoderLayerrR   r   c                    t         |           |j                  | _        || _        t	        |dz         | _        t        ||      | _        t        |      | _	        t        |j                  |j                        | _        t        |j                  |j                        | _        t        |j                  |j                        | _        t        |j                  |j                        | _        |j                   | _        y )Nr3   )rR   r   r$   )r'   r(   rS   rR   r   
is_slidingr   	self_attnrM   mlpr"   rms_norm_epsinput_layernormpost_attention_layernormpre_feedforward_layernormpost_feedforward_layernormr   r   s      r0   r(   zGemma2DecoderLayer.__init__  s    !--"9q=11()LV$,V-?-?VEXEXY(5f6H6HfNaNa(b%)6v7I7IvObOb)c&*78J8JPVPcPc*d'$33r1   last_cache_positionz4.53.0)versionrn   r   r}   ri   r   r   	use_cacher   rp   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                  |||      }|d   |
z
  dz   }t        j                  |d      }t        j                  t        |
|j                  d         |j                         }||z  }|d d d d d d |f   }|}| j#                  |      } | j$                  d
||||||||d	|	\  }}| j'                  |      }||z   }|}| j)                  |      }| j+                  |      }| j-                  |      }||z   }|f}|r||fz  }|S )Nr   r   r   diagonalr4   r   )mindevice)rn   r   r}   ri   r   r   r   r    )r   maxrC   r   rR   r   r+   finfor   r   tril	ones_liker   whereclamparanger   r   r   r   r   r   r   )r.   rn   r   r}   ri   r   r   r   r   r   effective_seq_len	min_dtypesliding_window_maskoffsetmask_indexesresidualself_attn_weightsoutputss                     r0   r@   zGemma2DecoderLayer.forward  s    ??~9 #N$8$8$;T=P=P Q {{//3FF!/4E3E3F0F!G "KK(<(<=AA	&+jjOON%**EQUQdQdPd'# "'-@)^!\'+.??!CV3  %||)>+?+?+CD^MbMb  &!/1a0E!F ,,]; ,:4>> 
,
' 3)%)/)
,
 
,
(( 55mD =0 66}E/77F =0 ")++Gr1   )NNNFFN)rF   rG   rH   r   rI   r(   r   r+   r   r   r   r   r
   r   FloatTensorr@   rJ   rK   s   @r0   r   r     s   4| 4 4 *H=
 2637*.,1$)59E||E #5<<#=>E !.	E
 u//0E !E $D>E D>E !!1!12E 
u  (51B1BEDUDU1U+V"WW	XE >Er1   r   c                   ^     e Zd Zddef fdZ ej                         ed               Z xZ	S )Gemma2RotaryEmbeddingrR   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_lenrR   r   rope_init_fnattention_scalingregister_bufferr   original_inv_freq)r.   rR   r   r   r/   s       r0   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!%r1   c                 b   | j                   d d d d f   j                         j                  |j                  d   dd      j	                  |j
                        }|d d d d d f   j                         }t        |j
                  j                  t              r/|j
                  j                  dk7  r|j
                  j                  nd}t        j                  |d      5  |j                         |j                         z  j                  dd      }t        j                  ||fd	      }|j                         | j                  z  }|j                         | j                  z  }	d d d        j	                  |j                   
      	j	                  |j                   
      fS # 1 sw Y   AxY w)Nr   r4   r   mpscpuF)device_typeenabledr3   r^   r   )r   r=   rr   rC   r   r   
isinstancer   strr+   autocastr   r_   rg   r   rh   r   )
r.   r9   ri   inv_freq_expandedposition_ids_expandedr   freqsembrg   rh   s
             r0   r@   zGemma2RotaryEmbedding.forwardp  sV    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfk^^UC 	5&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')d444C'')d444C		5 vvAGGv$cff177f&;;;	5 	5s    BF%%F.r&   )
rF   rG   rH   r   r(   r+   no_gradr   r@   rJ   rK   s   @r0   r   r   ^  s3    /| /" U]]_<  <r1   r   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 t        |t              r&|j
                  j                  j                  d       y y )Nr   )r8   stdr<   )rR   initializer_ranger   r)   rU   r-   datanormal_rQ   zero_	Embeddingpadding_idxr"   fill_)r.   ry   r  s      r0   _init_weightsz#Gemma2PreTrainedModel._init_weights  s    kk++fbii(MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> ..MM$$S) /r1   N)rF   rG   rH   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   r1   r0   r  r    sS    L&*#-.#4"5!N  $!"&*r1   r  c                        e Zd Zdef 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   d	e	e
j                     d
e	e   de	e   de	e   de	e
j                     dee   defd              Z e
j(                         	 ddee
j                  df   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
j                  defd       Z xZS )Gemma2ModelrR   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   )rR   F)r'   r(   pad_token_idr  
vocab_sizer)   r  rS   embed_tokens
ModuleListrangenum_hidden_layersr   layersr"   r   normr   
rotary_embgradient_checkpointing	post_initr   s      r0   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%  rD   s    r0   get_input_embeddingsz Gemma2Model.get_input_embeddings  s       r1   c                     || _         y r&   r/  r.   r|   s     r0   set_input_embeddingsz Gemma2Model.set_input_embeddings  s
    !r1   	input_idsr}   ri   r	  inputs_embedsr   r   output_hidden_statesr   flash_attn_kwargsrp   c
                    ||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%                  |||	||      }|}| j'                  ||      }t        j(                  | j                   j*                  dz  |j                  	      }||z  }|rd
nd }|rd
nd }| j,                  d | j                   j.                   D ]r  }|r||fz  }| j
                  r:| j                  r.| j1                  t3        |j4                  fi |
||||||||		      }n ||f|||||||	d|
}|d   }|sj||d   fz  }t | j7                  |      }|r||fz  }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)max_batch_sizemax_cache_lenr   r   r   r   r   g      ?r   r   )r   r}   ri   r   r   r   r   )last_hidden_stater	  rn   
attentions)rR   r   r6  r   
ValueErrorr,  r   r   r   r%  rC   r   r   r   get_seq_lengthr+   r   rd   _update_causal_maskr+  tensorrS   r)  r(  _gradient_checkpointing_funcr   __call__r*  r   )r.   r4  r}   ri   r	  r5  r   r   r6  r   r7  
batch_sizer   _past_seen_tokensr   rn   r   
normalizerall_hidden_statesall_self_attnsdecoder_layerlayer_outputss                          r0   r@   zGemma2Model.forward  s    2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	-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]

 & #oom\J
 \\$++"9"93">mFYFYZ
%
2 #7BD0d![[)H4;;+H+HI  	6M#!m%55!**t}} $ A AM22H6GH!' #%"
! !.!
!(;#.!-#2&7'#1
! (
! *!,M =#3"55A 	6D 		-0-!11&+++%	
 	
r1   r   input_tensorc           
         | j                   j                  dk(  r|S | j                   j                  dk(  r't        |t        j                        rt        |      }|S |j                  |j                  }}|j                  d   }t        |t        t        f      r|j                         }	n ||j                  d   n|j                  d   }	| j                  |||	||||j                  d         }
|
S )Nr   flex_attentionr   r4   r   sequence_lengthtarget_lengthr   r   r   rC  )rR   r   r   r+   r   r    r   r   rC   r   r   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_position)r.   r}   rK  r   r	  r   r   r   rO  rP  r   s              r0   r?  zGemma2Model._update_causal_mask,  s     ;;++/BB!!;;++/??.%,,7!<^!L!!$**L,?,?v&,,Q/o['AB+??AM8F8RN004XdXjXjklXmM PP+')#))!, Q 
 r1   rO  rP  r   rC  c                    | | j                         dk(  r| }|S t        j                  |      j                  }t        j                  ||f|||j
                        }|dk7  rt        j                  |d      }|t        j                  ||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 )	aM  
        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.
            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   r4   r   )r#   r+   r   r   fullr   triur   rs   rr   clonerC   r   masked_fill)r}   rO  rP  r   r   rC  r   r   r   mask_lengthpadding_masks              r0   rR  zAGemma2Model._prepare_4d_causal_attention_mask_with_cache_positionS  s   < %.*<*<*>!*C(K* ' E*..I** -0Ye\j\q\qK !##jjqA5<<n>S>STWeWmWmnprsWtttK%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 r1   	NNNNNNNNN)F)rF   rG   rH   r   r(   r0  r3  r   r   r   r+   r   r   r   r   r   r   r   r   r@   r  r   r?  staticmethodrI   r   rR  rJ   rK   s   @r0   r!  r!    s   |  !"  1515371559$(,0/359s
E,,-s
 !.s
 u//0	s

 "+.s
   1 12s
 D>s
 $D>s
 'tns
 !!1!12s
 $$89s
 
!s
  s
j U]]_ #($ellK78$ ll$ 	$
 %$  $ $L 444 4 {{	4
 4 4 4r1   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e	 	 	 	 	 	 	 	 	 	 	 ddeej"                     deej$                     deej"                     dee   deej(                     deej"                     dee   dee   dee   deej"                     deeej$                  f   defd              Z	 	 	 	 	 	 	 d fd	Z xZS )Gemma2ForCausalLMzlm_head.weightlm_headcolwise_reprn   logitsc                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y rO   )
r'   r(   r!  r  r$  r)   rU   rS   r`  r-  r[   s     r0   r(   zGemma2ForCausalLM.__init__  sU      (
 ++yy!3!3V5F5FUS 	r1   c                 .    | j                   j                  S r&   r  r%  rD   s    r0   r0  z&Gemma2ForCausalLM.get_input_embeddings      zz&&&r1   c                 &    || j                   _        y r&   re  r2  s     r0   r3  z&Gemma2ForCausalLM.set_input_embeddings      "'

r1   c                     | j                   S r&   r`  rD   s    r0   get_output_embeddingsz'Gemma2ForCausalLM.get_output_embeddings  s    ||r1   c                     || _         y r&   rj  )r.   new_embeddingss     r0   set_output_embeddingsz'Gemma2ForCausalLM.set_output_embeddings  s	    %r1   c                     || _         y r&   r  )r.   decoders     r0   set_decoderzGemma2ForCausalLM.set_decoder  s	    
r1   c                     | j                   S r&   rp  rD   s    r0   get_decoderzGemma2ForCausalLM.get_decoder  s    zzr1   r4  r}   ri   r	  r5  labelsr   r   r6  r   logits_to_keeprp   c                 .   | j                   rF| j                  j                  dk7  r-t        j	                  d| j                  j                   d       ||n| j                  j
                  }|	|	n| j                  j                  }	 | j                  d||||||||	|
d	|}|j                  }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 |}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]`.

        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)	r4  r}   ri   r	  r5  r   r   r6  r   lossrb  r	  rn   r<  r   )r   rR   r   r   r   r   r6  r  r;  r   rI   slicer`  final_logit_softcappingr+   r   loss_functionr$  r   r	  rn   r<  )r.   r4  r}   ri   r	  r5  ru  r   r   r6  r   rv  loss_kwargsr   rn   slice_indicesrb  ry  s                     r0   r@   zGemma2ForCausalLM.forward  s   P ==T[[==H#{{??@  Aqr 2C1N-TXT_T_TqTq$8$D $++JjJj 	 ,64:: ,
)%+'/!5),
 ,
  118B>SV8W~ot4]kmA}a,?@A;;..:dkkAAAFZZ'FdkkAAAF%4%%ffdooUUD%#33!//))
 	
r1   c	                    t        |   |f|||||||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	  r}   r5  r   ri   r   rv  rv  r3   r   r5  r4  rN  r}   )r'   prepare_inputs_for_generationpopr   r   ndimrR   r   rC   r   r  rR  rQ  r`  r-   r   )r.   r4  r	  r}   r5  r   ri   r   rv  r   model_inputsrD  rC  rO  r   r/   s                  r0   r  z/Gemma2ForCausalLM.prepare_inputs_for_generation   s5    w<

+)')%)

 

 !  !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)*r1   )NNNNNNNNNNr   )NNNNNTN)rF   rG   rH   _tied_weights_keys_tp_plan_pp_planr(   r0  r3  rk  rn  rr  rt  r   r   r   r+   r   r   r   r   r   r   rI   r   r@   r  rJ   rK   s   @r0   r_  r_    s   *+=)H_-z:;H'(&  1515371559-1$(,0/35934P
E,,-P
 !.P
 u//0	P

 "+.P
   1 12P
 ))*P
 D>P
 $D>P
 'tnP
 !!1!12P
 c5<</0P
 
 P
  P
j 4 4r1   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).
    )custom_introc                       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   dee	j                     d	ee	j                     d
ee   dee   dee   defd              Z xZS )Gemma2ForSequenceClassificationc                     t         |   |       |j                  | _        t        |      | _        t        j                  |j                  | j                  d      | _        | j                          y rO   )
r'   r(   
num_labelsr!  r  r)   rU   rS   scorer-  r[   s     r0   r(   z(Gemma2ForSequenceClassification.__init__F  sS      ++ (
YYv114??O
 	r1   c                 .    | j                   j                  S r&   re  rD   s    r0   r0  z4Gemma2ForSequenceClassification.get_input_embeddingsO  rf  r1   c                 &    || j                   _        y r&   re  r2  s     r0   r3  z4Gemma2ForSequenceClassification.set_input_embeddingsR  rh  r1   r4  r}   ri   r	  r5  ru  r   r   r6  rp   c
           
         | j                  ||||||||	      }
|
j                  }| 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                  
      }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).
        r}   ri   r	  r5  r   r   r6  Nr   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r4   )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  ru  pooled_logitsrR   rx  )r  r;  r  rC   rR   r#  r=  r   r   r+   int32r   argmaxr   r   r/   rF   r|  r   r	  rn   r<  )r.   r4  r}   ri   r	  r5  ru  r   r   r6  transformer_outputsrn   rb  rC  last_non_pad_tokennon_pad_masktoken_indicesr  ry  s                      r0   r@   z'Gemma2ForSequenceClassification.forwardU  s   * 8<zz)%+'/!5 8B 	8
 ,==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/ /??-;;*55
 	
r1   r\  )rF   rG   rH   r(   r0  r3  r   r   r   r+   r   r   r
   r   r   r   r@   rJ   rK   s   @r0   r  r  7  s    '(  151537+/59-1$(,0/3A
E,,-A
 !.A
 u//0	A

 "%A
   1 12A
 ))*A
 D>A
 $D>A
 'tnA
 
*A
  A
r1   r  c                       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   dee	j                     d	ee	j                     d
ee   dee   dee   de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~   rU   rS   r  r-  )r.   rR   r  r/   s      r0   r(   z%Gemma2ForTokenClassification.__init__  s      ++ (
6/6B!'!:!:V-t4@!'!6!6!$zz"45YYv1163D3DE
 	r1   c                 .    | j                   j                  S r&   re  rD   s    r0   r0  z1Gemma2ForTokenClassification.get_input_embeddings  rf  r1   c                 &    || j                   _        y r&   re  r2  s     r0   r3  z1Gemma2ForTokenClassification.set_input_embeddings  rh  r1   r4  r}   ri   r	  r5  ru  r   r   r6  rp   c
           
         | j                  ||||||||	      }
|
j                  }| j                  |      }| j                  |      }d}|| j	                  ||| j
                        }t        |||
j                  |
j                        S )r  r  N)ry  rb  rn   r<  )	r  r;  r~   r  r|  rR   r   rn   r<  )r.   r4  r}   ri   r	  r5  ru  r   r   r6  r   sequence_outputrb  ry  s                 r0   r@   z$Gemma2ForTokenClassification.forward  s    * ,0::)%+'/!5 ,6 	,
 "33,,7O,%%ffdkkBD$!//))	
 	
r1   r\  )rF   rG   rH   r(   r0  r3  r   r   r   r+   r   r   r
   r   r   r   r@   rJ   rK   s   @r0   r  r    s     '(  151537+/59-1$(,0/3*
E,,-*
 !.*
 u//0	*

 "%*
   1 12*
 ))**
 D>*
 $D>*
 'tn*
 
*
  *
r1   r  )r_  r!  r  r  r  )Nr   )r   NN)D	functoolsr   typingr   r   r   r   r+   torch.nnr)   activationsr	   cache_utilsr
   r   r   
generationr   modeling_flash_attention_utilsr   modeling_outputsr   r   r   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   utils.deprecationr   configuration_gemma2r   !torch.nn.attention.flex_attentionr   integrations.flex_attentionr    
get_loggerrF   r   Moduler"   rM   rb   rm   r   rI   rx   r=   r   r   r   r   r  r!  r_  r  r  __all__r   r1   r0   <module>r     s8  ,  3 3   ! : : ) B  L F & \ \ 0 .  !;J 
		H	%=BII =(		  (6	UU\\ 	U# 	U%,, 	U$ ## %II %<< % 
 % <<	 %
 U\\* %  % e_ % e_ % 5<<%& %FW)bii W)tU Up<BII <D *O * *8 j' j jZ h- h hV S
&; S
S
l C
#8 C
 C
Lr1   