
    rhCc                        d dl mZmZmZ d dlZd dlmZ ddlmZ ddl	m
Z
mZ ddlmZ ddlmZmZ ddlmZ dd	lmZmZmZ dd
lmZmZ ddlmZmZ ddlmZmZ ddl m!Z! ddl"m#Z#m$Z$m%Z%m&Z& ddl'm(Z( ddl)m*Z*  e&jV                  e,      Z- G d dej\                        Z/ G d dej\                        Z0d Z1d6dZ2dejf                  de4dejf                  fdZ5	 	 	 d7dej\                  dejf                  dejf                  dejf                  d eejf                     d!e6d"ee6   d#ee6   de7ejf                  ejf                  f   fd$Z8 G d% d&ej\                        Z9 G d' d(e      Z: G d) d*ej\                        Z;e$ G d+ d,e             Z<e$ G d- d.e<             Z=e$ G d/ d0e<e             Z> G d1 d2ee<      Z? G d3 d4ee<      Z@g d5ZAy)8    )CallableOptionalUnionN   )ACT2FN)CacheDynamicCache)GenerationMixin)create_causal_mask!create_sliding_window_causal_mask)FlashAttentionKwargs) GenericForSequenceClassificationGenericForTokenClassificationGradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuplelogging)check_model_inputs   )Gemma2Configc                   <     e Zd Zddedef fdZd Zd Zd Z xZ	S )Gemma2RMSNormdimepsc                     t         |           || _        t        j                  t        j                  |            | _        y N)super__init__r"   nn	Parametertorchzerosweight)selfr!   r"   	__class__s      }/var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/transformers/models/gemma2/modeling_gemma2.pyr&   zGemma2RMSNorm.__init__2   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._norm7   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.forward:   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_reprA   s'    ))*+6$((<<r/   )gư>)
__name__
__module____qualname__intr:   r&   r8   r=   rB   __classcell__r-   s   @r.   r    r    1   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__F   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.forwardP   s6    NN4;;t~~a/@#ADLLQRO#ST	r/   )rC   rD   rE   r&   r=   rG   rH   s   @r.   rJ   rJ   E   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_   U   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   \   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   w   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*                  | _        |j,                  |   dk(  r|j.                  | _        y d | _        y )Nrt   r   TrM   sliding_attention)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layer_types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#7=7I7I)7TXk7kf33qu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        |	|
||      \  }	}
|'|||d}|j                  |
|| j                  |      \  }
}t        }| j                  j                  dk7  rt        | j                  j                     } || |	|
||f| j                  r| j                  nd| j                   | j"                  | j$                  d|\  }} |j&                  g |d j)                         }| j+                  |      }||fS )Nr2   r   r1   )re   rd   r   eager        )r{   r|   r   r}   )r@   rt   r   viewr   r   r   rj   updater   r   rO   _attn_implementationr   r   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attention_interfacer   r   s                     r.   r=   zGemma2Attention.forward   s    $))#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%#&snUL'5'<'<ZW[WeWegs't$J(?;;++w6"9$++:Z:Z"[$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v| v v< +/59+)||+) #5<<#=>+) !.	+)
 !+) !!1!12+) -.+) 
u||Xell3XeELL>Q5RR	S+)r/   r   c                   ^    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ej                  e	eej                  ej                  f      f   fdZ xZS )Gemma2DecoderLayerrO   r   c                    t         |           |j                  | _        || _        |j                  |   | _        t        ||      | _        t        |      | _	        t        |j                  |j                        | _        t        |j                  |j                        | _        t        |j                  |j                        | _        t        |j                  |j                        | _        y )N)rO   r   r"   )r%   r&   rP   rO   r   attention_typer   	self_attnrJ   mlpr    rms_norm_epsinput_layernormpost_attention_layernormpre_feedforward_layernormpost_feedforward_layernormr   s      r.   r&   zGemma2DecoderLayer.__init__   s    !--$00;()LV$,V-?-?VEXEXY(5f6H6HfNaNa(b%)6v7I7IvObOb)c&*78J8JPVPcPc*d'r/   rk   r   rz   rf   r   output_attentions	use_cacher   rm   c	                    |}
| j                  |      } | j                  d||||||||d|	\  }}| j                  |      }|
|z   }|}
| j                  |      }| j	                  |      }| j                  |      }|
|z   }|f}|r||fz  }|S )N)rk   r   rz   rf   r   r   r   r    )r   r   r   r   r   r   )r,   rk   r   rz   rf   r   r   r   r   r   residualself_attn_weightsoutputss                r.   r=   zGemma2DecoderLayer.forward   s     !,,]; ,:4>> 
,
' 3)%)/)
,
 
,
(( 55mD =0 66}E/77F =0 ")++Gr/   )NNNFFN)rC   rD   rE   r   rF   r&   r)   r   r?   r   r   r   boolFloatTensorr=   rG   rH   s   @r.   r   r      s    e| e e" 2637*.,1$)59*||* #5<<#=>* !.	*
 u//0* !* $D>* D>* !!1!12* 
u  (51B1BEDUDU1U+V"WW	X*r/   r   c                   ^     e Zd Zddef fdZ ej                         ed               Z xZ	S )Gemma2RotaryEmbeddingrO   c                    t         |           t        |d      rUt        |j                  t
              r;|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&   hasattr
isinstancer   dictgetr   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>*z&:M:Mt/T#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q($(ZeD!%r/   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   r2   r   mpscpuF)device_typeenabledr1   r[   r   )r   r:   ro   r@   r   r   r   r   strr)   autocastr   r\   rd   r   re   r   )
r,   r7   rf   inv_freq_expandedposition_ids_expandedr   freqsembrd   re   s
             r.   r=   zGemma2RotaryEmbedding.forward=  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$   )
rC   rD   rE   r   r&   r)   no_gradr   r=   rG   rH   s   @r.   r   r   +  s3    /| /" U]]_<  <r/   r   c                   J    e Zd ZU eed<   dZdZdgZdgZdZ	dZ
dZdZdZeedZy)Gemma2PreTrainedModelrO   modelTr   past_key_values)rk   
attentionsN)rC   rD   rE   r   __annotations__base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraph_supports_attention_backendr   r   _can_record_outputsr   r/   r.   r   r   M  sQ    &*#-.#4"5N!"&+%r/   r   c                        e Zd Zdef fdZee	 	 	 	 	 	 	 	 	 ddeej                     deej                     deej                     dee   deej                     dee   d	ee   d
ee   deej                     dee   defd              Z xZS )Gemma2ModelrO   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_idpadding_idx
vocab_sizer'   	EmbeddingrP   embed_tokens
ModuleListrangenum_hidden_layersr   layersr    r   normr   
rotary_embgradient_checkpointing	post_initr   s      r.   r&   zGemma2Model.__init__b  s     !.. ++LL):):F<N<NPTP`P`ammDI&JbJbDcdy	2d
 "&"4"4&:M:MN	/v>&+# 	 es   D	input_idsrz   rf   r   inputs_embedsr   r   output_hidden_statesr   r   rm   c
                 x   ||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                  |      }|r|| j                  s
t               }|	F||j                         nd}t        j                  |||j                  d   z   |j                        }	||	j!                  d      }t#        |x}t$              s*| j                   |||	||d}t'        di |t)        di |d}|}| j+                  ||      }t        j,                  | j                   j.                  d	z  |j0                  
      }||z  }|rdnd }|rdnd }| j2                  d | j                   j4                   D ]9  }|r||fz  } ||f|||j6                     |||||	d|
}|d   }|s1||d   fz  }; | j9                  |      }|r||fz  }t;        ||||      S )Nz:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.Fr   r   )r   )rO   input_embedsrz   r   r   rf   )full_attentionr   g      ?r   r   )r   rz   rf   r   r   r   r   )last_hidden_stater   rk   r   )rO   r   r  r   
ValueErrorr  r   loggerwarning_oncer  r	   get_seq_lengthr)   aranger@   r   ra   r   r   r   r   r  tensorrP   r   r
  r	  r   r  r   )r,   r  rz   rf   r   r  r   r   r  r   r   past_seen_tokenscausal_mask_mappingmask_kwargsrk   r   
normalizerall_hidden_statesall_self_attnsdecoder_layerlayer_outputss                        r.   r=   zGemma2Model.forwardr  s    2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	-t";<YZZ&&4==Yj I  --i8M0*nO!CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L ?-F ++ -"0"0#2 ,K #5"C{"C%F%U%U# & #oom\J
 \\$++"9"93">mFYFYZ
%
2 #7BD0d![[)H4;;+H+HI 	6M#!m%55!)
$72=3O3OP)."3#-
 
M *!,M =#3"55'	6* 		-0-!11&+++%	
 	
r/   )	NNNNNNNNN)rC   rD   rE   r   r&   r   r   r   r)   r   r   r   r   r   r   r   r   r=   rG   rH   s   @r.   r   r   `  s   |    151537+/59$(,0/359k
E,,-k
 !.k
 u//0	k

 "%k
   1 12k
 D>k
 $D>k
 'tnk
 !!1!12k
 +,k
 
!k
  k
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e	e
	 	 	 	 	 	 	 	 	 	 	 dd	eej                     d
eej                     deej                     dee   deej                      deej                     dee   dee   dee   deej                     deeej                  f   defd              Z xZS )Gemma2ForCausalLMzlm_head.weightlm_headcolwise_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                     || _         y r$   r   )r,   decoders     r.   set_decoderzGemma2ForCausalLM.set_decoder  s	    
r/   c                     | j                   S r$   r+  rA   s    r.   get_decoderzGemma2ForCausalLM.get_decoder  s    zzr/   r  rz   rf   r   r  labelsr   r   r  r   logits_to_keeprm   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  
        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)	r  rz   rf   r   r  r   r   r  r   )lossr(  r   rk   r   r   )r   rO   r   r  r  r   r  r   r  r   rF   slicer&  final_logit_softcappingr)   r   loss_functionr  r   r   rk   r   )r,   r  rz   rf   r   r  r0  r   r   r  r   r1  r   r   rk   slice_indicesr(  r3  s                     r.   r=   zGemma2ForCausalLM.forward  s   F ==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PPD%#33!//))
 	
r/   )NNNNNNNNNNr   )rC   rD   rE   _tied_weights_keys_tp_plan_pp_planr&   r-  r/  r   r   r   r)   r   r   r   r   r   r   rF   r   r=   rG   rH   s   @r.   r%  r%    sZ   *+=)H_-z:;H  151537+/59-1$(,0/35934K
E,,-K
 !.K
 u//0	K

 "%K
   1 12K
 ))*K
 D>K
 $D>K
 'tnK
 !!1!12K
 c5<</0K
 
 K
  K
r/   r%  c                       e Zd Zy)Gemma2ForSequenceClassificationNrC   rD   rE   r   r/   r.   r<  r<  G      r/   r<  c                       e Zd Zy)Gemma2ForTokenClassificationNr=  r   r/   r.   r@  r@  K  r>  r/   r@  )r%  r   r   r<  r@  )Nr   )r   NN)Btypingr   r   r   r)   torch.nnr'   activationsr   cache_utilsr   r	   
generationr
   masking_utilsr   r   modeling_flash_attention_utilsr   modeling_layersr   r   r   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   utils.genericr   configuration_gemma2r   
get_loggerrC   r  Moduler    rJ   r_   rj   r   rF   ru   r:   r?   r   r   r   r   r   r   r%  r<  r@  __all__r   r/   r.   <module>rS     s  , - ,   ! . ) R B 
 P K F & R R / . 
		H	%=BII =(		  (6	UU\\ 	U# 	U%,, 	U$ ## %II %<< % 
 % <<	 %
 U\\* %  % e_ % e_ % 5<<%& %FG)bii G)T83 8v<BII <D O  $ ~
' ~
 ~
B a
- a
 a
H	&FH] 		#@BW 	r/   