
    <hS                        S SK JrJrJr  S SKrS SKJs  Jr  S SKJr  SSK	J
r
  SSKJrJr  SSKJr  SSKJr  SS	KJr  SS
KJrJrJr  SSKJrJr  SSKJrJr  SSKJrJ r J!r!  SSK"J#r#  \ " 5       (       a  S SK$J%r%  SSK&J'r'  \!RP                  " \)5      r*   S8S\\RV                  \,\RV                     S4   S\\-   S\\RV                     S\\RV                  \-4   4S jjr. " S S\R^                  5      r0 " S S\R^                  5      r1S r2S9S jr3 " S S\R^                  5      r4 " S S \R^                  5      r5 " S! S"\R^                  5      r6S#\RV                  S$\-S\RV                  4S% jr7 " S& S'\R^                  5      r8 S:S(\R^                  S)\RV                  S*\RV                  S+\RV                  S\\RV                     S,\9S-\94S. jjr: " S/ S0\5      r;\ " S1 S2\5      5       r<\ " S3 S4\<5      5       r= " S5 S6\<\5      r>/ S7Qr?g);    )CallableOptionalUnionN)nn   )ACT2FN)CacheDynamicCache)GenerationMixin)AttentionMaskConverter)GradientCheckpointingLayer)BaseModelOutputWithPastMoeCausalLMOutputWithPastMoeModelOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)auto_docstringis_torch_flex_attn_availablelogging   )GraniteMoeConfig)	BlockMask)make_flex_block_causal_maskgate_logitsnum_expertsattention_maskreturnc                 d   U b  [        U [        5      (       d  g[        U [        5      (       aB  U S   R                  n[        R                  " U  Vs/ sH  oUR                  U5      PM     snSS9n[        R                  R                  R                  WSS9n[        R                  " XrSS9u  p[        R                  R                  R                  X5      n
Uc:  [        R                  " U
R                  5       SS9n[        R                  " USS9nGO"UR                  u  pUR                  S   X-  -  nUSSS2SS2SS4   R                  XXU45      R                  SX!5      R                  W5      n[        R                   " U
R                  5       U-  SS9[        R                   " USS9-  nUSSS2SS2S4   R                  XXR                  S   45      R                  SUR                  S   5      R                  U5      n[        R                   " UU-  SS9[        R                   " USS9-  nUR                  S   [#        UR                  R$                  5      -  n[        R                   " USS2UUUR                  S   -   24   UR'                  S5      -  5      nUU-  $ s  snf )ax  
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.

See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
experts is too unbalanced.

Args:
    gate_logits:
        Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
        shape [batch_size X sequence_length, num_experts].
    num_experts:
        Number of experts
    top_k:
        The number of experts to route per-token, can be also interpreted as the `top-k` routing
        parameter.
    attention_mask (`torch.Tensor`, *optional*):
        The attention_mask used in forward function
        shape [batch_size X sequence_length] if not None.

Returns:
    The auxiliary loss.
Nr   dimr   )
isinstancetupledevicetorchcattor   
functionalsoftmaxtopkone_hotmeanfloatshapeexpandreshapesumintindex	unsqueeze)r   r   top_kr   compute_device
layer_gateconcatenated_gate_logitsrouting_weights_selected_expertsexpert_masktokens_per_expertrouter_prob_per_expert
batch_sizesequence_lengthnum_hidden_layersexpert_attention_mask router_per_expert_attention_maskrankoverall_losss                       j/var/www/html/shao/venv/lib/python3.13/site-packages/transformers/models/granitemoe/modeling_granitemoe.pyload_balancing_loss_funcrI   ,   s   : *[%"@"@+u%%$Q..#(99^i-j^iPZmmN.K^i-jpq#r hh))112JPR1SO**_DA((%%--.>LK!JJ{'8'8':B "'O!C&4&:&:#
4::1=*B^_ 4AtT12V&OKXYWR,R	 	 "IIk&7&7&9<Q&QWXY\a\e\e!q]
 
 4At+,V&OEZEZ[\E]^_WR..q12R	 	) "'?=]+]cd!ehmhqhq,!i
 "
   #c/*@*@*F*F&GGD99!TD?+@+@+C$CCCDG]GgGghiGjjL +%%a .ks   J-c                   8   ^  \ rS rSrSU 4S jjrS rS rSrU =r$ )GraniteMoeRMSNorm   c                    > [         TU ]  5         [        R                  " [        R
                  " U5      5      U l        X l        g)z0
GraniteMoeRMSNorm is equivalent to T5LayerNorm
N)super__init__r   	Parameterr'   onesweightvariance_epsilon)selfhidden_sizeeps	__class__s      rH   rO   GraniteMoeRMSNorm.__init__   s/     	ll5::k#:; #    c                    UR                   nUR                  [        R                  5      nUR	                  S5      R                  SSS9nU[        R                  " X0R                  -   5      -  nU R                  UR                  U5      -  $ )N   r#   T)keepdim)	dtyper)   r'   float32powr.   rsqrtrS   rR   )rT   hidden_statesinput_dtypevariances       rH   forwardGraniteMoeRMSNorm.forward   sw    #))%((7 $$Q',,R,>%H?T?T4T(UU{{]--k:::rY   c                 ^    [        U R                  R                  5       SU R                   3$ )Nz, eps=)r%   rR   r0   rS   rT   s    rH   
extra_reprGraniteMoeRMSNorm.extra_repr   s*    ))*+6$2G2G1HIIrY   )rS   rR   )gư>)	__name__
__module____qualname____firstlineno__rO   rd   rh   __static_attributes____classcell__rW   s   @rH   rK   rK      s    $;J JrY   rK   c                   l   ^  \ rS rSrSS\4U 4S jjjr\R                  " 5       \S 5       5       r	Sr
U =r$ )GraniteMoeRotaryEmbedding   configc                   > [         TU ]  5         [        US5      (       aZ  [        UR                  [
        5      (       a;  UR                  R                  SUR                  R                  S5      5      U l        OSU l        UR                  U l	        UR                  U l
        Xl        [        U R                     U l        U R                  U R                  U5      u  o0l        U R                  SUSS9  U R                   U l        g )Nrope_scaling	rope_typetypedefaultinv_freqF)
persistent)rN   rO   hasattrr$   rv   dictgetrw   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrt   r   rope_init_fnattention_scalingregister_bufferrz   original_inv_freq)rT   rt   r&   rz   rW   s       rH   rO   "GraniteMoeRotaryEmbedding.__init__   s    6>**z&:M:Mt/T/T#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q((ZeD!%rY   c                 b   U R                   S S S 2S 4   R                  5       R                  UR                  S   SS5      R	                  UR
                  5      nUS S 2S S S 24   R                  5       n[        UR
                  R                  [        5      (       a0  UR
                  R                  S:w  a  UR
                  R                  OSn[        R                  " USS9   UR                  5       UR                  5       -  R                  SS5      n[        R                  " Xf4SS	9nUR                  5       U R                  -  nUR                  5       U R                  -  n	S S S 5        WR	                  UR                   S
9W	R	                  UR                   S
94$ ! , (       d  f       N@= f)Nr   r#   r   mpscpuF)device_typeenabledr[   r!   )r]   )rz   r/   r1   r0   r)   r&   r$   rx   strr'   autocast	transposer(   cosr   sinr]   )
rT   xposition_idsinv_freq_expandedposition_ids_expandedr   freqsembr   r   s
             rH   rd   !GraniteMoeRotaryEmbedding.forward   sR    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E'E!((--[`J`ahhmmfk^^UC&,,.1F1L1L1NNYYZ[]^_E))UN3C'')d444C'')d444C	 D vvAGGv$cff177f&;;; DCs   $BF  
F.)r   rt   r   r   r   r   rw   N)rj   rk   rl   rm   r   rO   r'   no_gradr   rd   rn   ro   rp   s   @rH   rr   rr      s7    // / /" ]]_<  <rY   rr   c                     U SSU R                   S   S-  24   nU SU R                   S   S-  S24   n[        R                  " U* U4SS9$ )z*Rotates half the hidden dims of the input..Nr#   r[   r!   )r0   r'   r(   )r   x1x2s      rH   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''rY   c                     UR                  U5      nUR                  U5      nX-  [        U 5      U-  -   nX-  [        U5      U-  -   nXg4$ )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.
)r6   r   )qkr   r   r   unsqueeze_dimq_embedk_embeds           rH   apply_rotary_pos_embr      sS    ( --
&C
--
&Cw;q>C/0Gw;q>C/0GrY   c                   B   ^  \ rS rSrS\S\S\SS4U 4S jjrS rS	rU =r$ )
GraniteMoeParallelExperts   r   
input_sizeoutput_sizer   Nc                    > [         TU ]  5         [        R                  " [        R
                  " XU5      5      U l        Xl        X l        X0l	        g)aW  
Initialize the GraniteMoeParallelExperts module.
The experts weights are stored in [num_experts, output_size, input_size] format. Such that it's compatible with
many MoE libraries, such as [Megablock](https://github.com/databricks/megablocks) and
[ScatterMoE](https://github.com/shawntan/scattermoe), as well as the
[MoE kernel](https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/fused_moe/fused_moe.py)
used in vllm.

Args:
    num_experts (int):
        Number of experts.
    input_size (int):
        Size of the input.
    output_size (int):
        Size of the output.
N)
rN   rO   r   rP   r'   emptyrR   r   r   r   )rT   r   r   r   rW   s       rH   rO   "GraniteMoeParallelExperts.__init__   s<    " 	ll5;;{#TU&$&rY   c                     UR                  USS9n/ n[        U R                  5       H8  nUR                  [        R
                  " X5   U R                  U   5      5        M:     [        R                  " USS9nU$ )z
Forward pass of the GraniteMoeParallelExperts module.

Args:
    inputs (Tensor):
        Input tensor.
    expert_size:
        Expert size information.

Returns:
    Tensor: Output tensor.
r   r!   )	splitranger   appendFlinearrR   r'   r(   )rT   inputsexpert_size
input_listoutput_listiresultss          rH   rd   !GraniteMoeParallelExperts.forward   sh     \\+1\5
t''(Aqxx
t{{1~FG )))KQ/rY   )r   r   r   rR   	rj   rk   rl   rm   r4   rO   rd   rn   ro   rp   s   @rH   r   r      s.    'C 'S 's 't '. rY   r   c                   >   ^  \ rS rSrS\S\S\4U 4S jjrS rSrU =r$ )GraniteMoeTopKGatingi  r   r   r7   c                 z   > [         TU ]  5         X l        Xl        X0l        [
        R                  " XSS9U l        g)z
Initialize the top-k gating mechanism.
Args:
    input_size (`int`):
        Size of the input.
    num_experts (`int`):
        Number of experts.
    top_k (`int`):
        Number of top experts to select.
FbiasN)rN   rO   r   r   r7   r   Linearlayer)rT   r   r   r7   rW   s       rH   rO   GraniteMoeTopKGating.__init__  s2     	&$
YYzUC
rY   c                 z   U R                  U5      R                  5       nUR                  U R                  SS9u  p4[        R
                  " USS9R                  U5      n[        R                  " UR                  S5      U R                  /UR                  UR                  S9nUR                  SUS5      nUR                  5       R                  S5      nUR                  5       nUR!                  5       n	U	R#                  S5      u  pUR%                  U R                  SS9nUR!                  5       nX[   nXXU4$ )Nr   r!   r   r]   r&   trunc)rounding_mode)r   r/   r,   r7   r'   r+   type_aszerossizer   r]   r&   scatterlongr3   tolistflattensortdiv)rT   ra   logitstop_k_logitstop_k_indicestop_k_gatesr   gatesr   top_k_expertsr<   index_sorted_expertsbatch_indexbatch_gatess                 rH   rd   GraniteMoeTopKGating.forward   s"   M*002&,kk$**!k&D#mmLa8@@O a $"2"23;;L;LU`UgUg
 a2jjl&&q) "((* &--/"/"4"4Q"7*..tzz.Q "))+!7#+FRRrY   )r   r   r   r7   r   rp   s   @rH   r   r     s-    D3 DS D D&S SrY   r   c                   :   ^  \ rS rSrSrS\4U 4S jjrS rSrU =r	$ )GraniteMoeMoEi<  z
A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.

Args:
    config:
        Configuration object with model hyperparameters.
rt   c                   > [         TU ]  5         UR                  U l        UR                  U l        [
        UR                     U l        [        UR                  U R                  U R                  S-  5      U l
        [        UR                  U R                  U R                  5      U l        [        U R                  UR                  UR                  S9U l        g )Nr[   )r   r   r7   )rN   rO   rU   r   intermediate_sizer   
hidden_act
activationr   num_local_expertsinput_linearoutput_linearr   num_experts_per_tokrouterrT   rt   rW   s     rH   rO   GraniteMoeMoE.__init__E  s     ,,!33 !2!235f6N6NPTP_P_aeaqaqtuauv6v7O7OQUQaQacgcrcrs*00,,
rY   c                    UR                  5       u  p#nUR                  SU5      nU R                  U5      u  pVpxn	X   n
U R                  X5      nUR	                  SSS9nU R                  US   5      US   -  nU R                  X5      nXSS2S4   -  n[        R                  " X#-  U R                  4UR                  UR                  S9nUR                  SXm5      nUR                  X#U R                  5      nX4$ )z
Forward pass of the mixture of experts layer.

Args:
    layer_input (Tensor):
        Input tensor.

Returns:
    Tensor:
        Output tensor.
    Tensor:
        Router logits.
r#   r[   r!   r   r   Nr   )r   r2   r   r   chunkr   r   r'   r   r   r]   r&   	index_addview)rT   layer_inputbszlengthemb_sizer<   r   r   r   router_logitsexpert_inputsra   chunked_hidden_statesexpert_outputsr   layer_outputs                   rH   rd   GraniteMoeMoE.forwardT  s    !, 0 0 2X!))"h7BF++kBZ?-#0))-E - 3 3A2 3 >(=a(@ADYZ[D\\++MG'ag*>>S\4??;>CWCW`n`u`uvq+F#((dooF**rY   )r   rU   r   r   r   r   )
rj   rk   rl   rm   __doc__r   rO   rd   rn   ro   rp   s   @rH   r   r   <  s    
/ 
+ +rY   r   ra   n_repc                     U R                   u  p#pEUS:X  a  U $ U SS2SS2SSS2SS24   R                  X#XU5      n U R                  X#U-  XE5      $ )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)r0   r1   r2   )ra   r   batchnum_key_value_headsslenhead_dims         rH   	repeat_kvr   u  s_    
 2?1D1D.Ez!!Qa"23::5W\dlmM  e(CTTTrY   c                   v  ^  \ rS rSrSrSS\S\\   4U 4S jjjr      SS\	R                  S\\	R                     S\\	R                     S	\\   S
\S\\	R                     S\\\	R                  \	R                  4      S\\	R                  \\	R                     \\\	R                        4   4S jjrSrU =r$ )GraniteMoeAttentioni  z=Multi-headed attention from 'Attention Is All You Need' paperrt   	layer_idxc                 z  > [         TU ]  5         Xl        X l        Uc-  [        R                  SU R                  R                   S35        UR                  U l        UR                  U l	        UR                  U l        U R                  U R                  -  U l        UR                  U l        U R                  U R                  -  U l        SU l        UR                   U l        U R                  U R                  -  U R                  :w  a&  [%        SU R                   SU R                   S35      e[&        R(                  " U R                  U R                  U R                  -  UR*                  S9U l        [&        R(                  " U R                  U R                  U R                  -  UR*                  S9U l        [&        R(                  " U R                  U R                  U R                  -  UR*                  S9U l        [&        R(                  " U R                  U R                  UR*                  S9U l        g )NzInstantiating z without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.Tz?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).r   )rN   rO   rt   r   loggerwarning_oncerW   rj   attention_dropoutrU   num_attention_heads	num_headsr   r   num_key_value_groups	is_causalattention_multiplierscaling
ValueErrorr   r   attention_biasq_projk_projv_projo_projrT   rt   r   rW   s      rH   rO   GraniteMoeAttention.__init__  s   " !8!8 9 :, , "(!9!9!--33((DNN:#)#=#= $(NNd6N6N$N!22MMDNN*t/?/??QRVRbRbQc$T^^$4B8 
 ii 0 0$..4==2PW]WlWlmii 0 0$2J2JT]]2Zagavavwii 0 0$2J2JT]]2Zagavavwii 0 0$2B2BI^I^_rY   ra   r   r   past_key_value	use_cachecache_positionposition_embeddingsr   c                    UR                  5       u  pnU R                  U5      nU R                  U5      nU R                  U5      nUR	                  XU R
                  U R                  5      R                  SS5      nUR	                  XU R                  U R                  5      R                  SS5      nUR	                  XU R                  U R                  5      R                  SS5      nUb  UOSu  nnUb  [        XUU5      u  pUb$  UXS.nUR                  XU R                  U5      u  p[        nU R                  R                  S:w  a  [        U R                  R                     nU" U UUUU4U R                   (       d  SOU R"                  U R$                  S.UD6u  nnUR	                  XS5      nU R'                  U5      nUU4$ )	Nr   r[   )NN)r   r   r  eager        )dropoutr	  r#   )r   r  r  r  r   r  r   r   r   r   updater   eager_attention_forwardrt   _attn_implementationr   trainingr  r	  r  )rT   ra   r   r   r  r  r  r  kwargsr   q_lenr<   query_states
key_statesvalue_statesr   r   cache_kwargsattention_interfaceattn_outputattn_weightss                        rH   rd   GraniteMoeAttention.forward  s    &**,A{{=1[[/
{{=1#((T^^T]]S]]^_abc__S1I1I4==Yccdeghi
#((T5M5Mt}}]gghiklm*=*I&|S*';LVY[^'_$L%#&sUL'5'<'<ZW[WeWegs't$J(?;;++w6"9$++:Z:Z"[$7	%
  $}}C$2H2HLL	%
 	%
!\ "&&s26kk+.L((rY   )r  rt   r   rU   r  r  r   r  r  r   r  r  r	  r  r   )NNNFNN)rj   rk   rl   rm   r   r   r   r4   rO   r'   Tensor
LongTensorr	   boolr%   rd   rn   ro   rp   s   @rH   r   r     s    G`/ `HSM ` `F 2637*.59KO0)||0) !.0) u//0	0)
 !0) 0) !!1!120) &eELL%,,,F&GH0) 
u||Xell3XeELL>Q5RR	S0) 0)rY   r   modulequerykeyvaluer	  r  c                 @   [        X R                  5      n[        X0R                  5      n	[        R                  " XR	                  SS5      5      U-  n
Ub"  US S 2S S 2S S 2S UR
                  S   24   nX-   n
[        R                  R                  U
S[        R                  S9R                  UR                  5      n
[        R                  R                  XU R                  S9n
[        R                  " X5      nUR	                  SS5      R                  5       nX4$ )Nr[   r   r#   )r"   r]   )pr  r   )r   r  r'   matmulr   r0   r   r*   r+   r^   r)   r]   r  r  
contiguous)r+  r,  r-  r.  r   r	  r  r  r!  r"  r&  causal_maskr%  s                rH   r  r    s     3 ; ;<JU$?$?@L<<';';Aq'ABWLL!$Q1.D
0@0@0D.D%DE#1 ==((2U]](SVVW\WbWbcL==((6??([L,,|:K''1-88:K$$rY   c                     ^  \ rS rSrS\S\4U 4S jjr        SS\R                  S\	\R                     S\	\R                     S\	\   S	\	\   S
\	\   S\	\R                     S\	\   S\	\\R                  \R                  4      S\\R                  \	\\R                  \R                  4      4   4S jjrSrU =r$ )GraniteMoeDecoderLayeri  rt   r   c                 N  > [         TU ]  5         UR                  U l        [        XS9U l        UR
                  S:  a  [        U5      U l        [        UR                  UR                  S9U l
        [        UR                  UR                  S9U l        UR                  U l        g )N)rt   r   r   rV   )rN   rO   rU   r   	self_attnr   r   block_sparse_moerK   rms_norm_epsinput_layernormpost_attention_layernormresidual_multiplierr  s      rH   rO   GraniteMoeDecoderLayer.__init__  s    !--,FP##a'$1&$9D!01C1CI\I\](9&:L:LRXReRe(f%#)#=#= rY   ra   r   r   r  output_attentionsr  r  output_router_logitsr  r   c
                 ,   UnU R                  U5      nU R                  " SUUUUUUUU	S.U
D6u  pXU R                  -  -   nUnU R                  U5      nU R	                  U5      u  pXU R                  -  -   nU4nU(       a  X4-  nU(       a  X4-  nU$ )aY  
Args:
    hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
    attention_mask (`torch.FloatTensor`, *optional*):
        attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
        query_sequence_length, key_sequence_length)` if default attention is used.
    output_attentions (`bool`, *optional*):
        Whether or not to return the attentions tensors of all attention layers. See `attentions` under
        returned tensors for more detail.
    use_cache (`bool`, *optional*):
        If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
        (see `past_key_values`).
    past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
    cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
        Indices depicting the position of the input sequence tokens in the sequence
    output_router_logits (`bool`, *optional*):
        Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
        should not be returned during inference.
    position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
        Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
        with `head_dim` being the embedding dimension of each attention head.
    kwargs (`dict`, *optional*):
        Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
        into the model
)ra   r   r   r  r@  r  r  r   )r<  r9  r>  r=  r:  )rT   ra   r   r   r  r@  r  r  rA  r  r  residualself_attn_weightsr   outputss                  rH   rd   GraniteMoeDecoderLayer.forward  s    L !,,]; ,0>> 
,
')%)/) 3
,
 
,
( !43K3K#KK !55mD'+'<'<]'K$ 43K3K#KK "++G''GrY   )r:  rU   r<  r=  r>  r9  )NNNFFNFN)rj   rk   rl   rm   r   r4   rO   r'   r(  r   r)  r	   r*  r%   FloatTensorrd   rn   ro   rp   s   @rH   r6  r6    s   
>/ 
>C 
> 2637*.,1$)59/4KOH||H !.H u//0	H
 !H $D>H D>H !!1!12H 'tnH &eELL%,,,F&GHH 
u  (51B1BEDUDU1U+V"WW	XH HrY   r6  c                   T   ^  \ rS rSr% \\S'   SrSrS/rS/r	Sr
SrSrU 4S jrS	rU =r$ )
GraniteMoePreTrainedModeliL  rt   modelTr6  past_key_valuesFc                    > [         TU ]  U5        [        U[        5      (       a9  UR                  R
                  R                  SU R                  R                  S9  g g )Nr  )r.   std)	rN   _init_weightsr$   r   rR   datanormal_rt   initializer_range)rT   r+  rW   s     rH   rO  'GraniteMoePreTrainedModel._init_weightsX  sJ    f%f788MM&&CT[[5R5R&S 9rY   rC  )rj   rk   rl   rm   r   __annotations__base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_can_compile_fullgraphrO  rn   ro   rp   s   @rH   rJ  rJ  L  sD    &*#12#4"5N"T TrY   rJ  c                   4  ^  \ rS rSrS\4U 4S jjr\           SS\\R                     S\\R                     S\\R                     S\\\\\R                     4      S\\R                     S	\\   S
\\   S\\   S\\   S\\   S\\R                     S\\\4   4S jj5       r SS\\R                  S4   S\R                  S\R                  S\S
\4
S jjr\S\R                  S\S\S\R,                  S\R                  S\4S j5       rSrU =r$ )GraniteMoeModeli^  rt   c           	      6  > [         TU ]  U5        UR                  U l        UR                  U l        [
        R                  " UR                  UR                  U R                  5      U l        [
        R                  " [        UR                  5       Vs/ sH  n[        X5      PM     sn5      U l        [        UR                  UR                  S9U l        SU l        UR$                  U l        UR                  U l        UR&                  U l        U R                  U R(                  -  U l        UR,                  U l        UR.                  U l        UR0                  U l        U R0                  S:X  a  [3        U5      OS U l        U R7                  5         g s  snf )Nr8  Frope)rN   rO   pad_token_idpadding_idx
vocab_sizer   	EmbeddingrU   embed_tokens
ModuleListr   rC   r6  layersrK   r;  normgradient_checkpointingembedding_multiplierr  r  r   r   
rope_thetaposition_embedding_typerr   
rotary_emb	post_initr  s      rH   rO   GraniteMoeModel.__init__`  sD    !.. ++LL):):F<N<NPTP`P`ammHMfNfNfHghHg9#F6Hgh
 &f&8&8f>Q>QR	&+#$*$?$?!!--33((DNN:'-'E'E$ ++'-'E'E$?C?[?[_e?e3F;ko 	! is   F	input_idsr   r   rL  inputs_embedsr  r@  output_hidden_statesrA  return_dictr  r   c                    Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nU
b  U
OU R                   R                  n
US L US L-  (       a  [        S5      eU R                  (       a/  U R                  (       a  U(       a  [        R                  S5        SnUc  U R                  U5      nXPR                  -  n[        U[        S 5      [        45      (       d  [        S5      eU(       a  Uc
  [        5       nUcD  Ub  UR!                  5       OSn["        R$                  " XUR&                  S   -   UR(                  S9nUc  UR+                  S5      nU R-                  X%XU5      nUnS nU R.                  b  U R/                  X5      nU(       a  SOS nU(       a  SOS nU	(       a  SOS nU R0                   HE  nU(       a  UU4-  nU" UUUUUUUU	US	9	nUS   nU(       a	  UUS   4-  nU	(       d  M<  UUS
   4-  nMG     U R3                  U5      nU(       a  UU4-  nU
(       d  [5        S XUU4 5       5      $ [7        UUUUUS9$ )Nz:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.FzBThe `past_key_values` should be either a `Cache` object or `None`.r   r   r&   rC  )r   r   r  r@  r  r  rA  r  r#   c              3   ,   #    U H  oc  M  Uv   M     g 7fr   rC  ).0vs     rH   	<genexpr>*GraniteMoeModel.forward.<locals>.<genexpr>  s      ^a^s   	)last_hidden_staterL  ra   
attentionsr   )rt   r@  rq  r  use_return_dictr
  rh  r  r  r  rd  ri  r$   rx   r	   r
   get_seq_lengthr'   aranger0   r&   r6   _update_causal_maskrl  rf  rg  r%   r   )rT   ro  r   r   rL  rp  r  r@  rq  rA  rr  r  r  past_seen_tokensr4  ra   r  all_hidden_statesall_self_attnsall_router_logitsdecoder_layerlayer_outputss                         rH   rd   GraniteMoeModel.forwardy  s     2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]-t";<YZZ&&4==Yj I  --i8M%(A(AA /DJ+>??abb0*nO!CRC^==?de"\\ ]5H5H5K"KTaThThN )33A6L..>L]

 &"??&"&//-"N #7BD0d"6BD![[M#!m%55!)*)."3#-%9$7
M *!,M =#3"55##!mB&7%99!- )0 		-0  -!11 )<M~^   &+++%+
 	
rY   r   input_tensorc           	         U R                   R                  S:X  a  Ub  US:H  R                  5       (       a  U$ g U R                   R                  S:X  a,  [        U[        R
                  5      (       a  [        U5      nU$ Ub  UR                  5       OSnUb  UR                  OSnU R                   R                  S:X  a5  U(       d.  U(       d'  [        R                  " UUUU R                  S9(       a  g UR                  nUR                  S   n	U(       a  UR                  5       n
O5[        U[        R
                  5      (       a  UR                  S	   OXi-   S-   n
U R                  UU	U
UUUR                  S   S
9nU R                   R                  S:X  aZ  UbW  UR                   R"                  S;   a=  U(       d6  [        R$                  " U5      R&                  n[        R(                  " X5      nU$ )Nflash_attention_2r  flex_attentionr   Fsdpa)rp  past_key_values_lengthis_trainingr   r#   )rB   target_lengthr]   r  rA   )cudaxpunpu)rt   r  anyr$   r'   r(  r   r}  is_compileabler   _ignore_causal_mask_sdpar  r]   r0   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr&   rx   finfomin_unmask_unattended)rT   r   r  r  rL  r@  r  using_compilable_cacher]   rB   r  r4  	min_dtypes                rH   r  #GraniteMoeModel._update_causal_mask  s    ;;++/BB)~/D.I.I.K.K%%;;++/??.%,,77!<^!L!!
 @O?Z?99;`aCRC^!?!?di ;;++v5>T]n%>>*'7 MM	 ""&,,Q/!+??AM nell;; $$R(%7!;  PP+')#))!, Q 
 KK,,6*%%**.DD%
 E*..I0CCK[KrY   rB   r  r]   rA   c                    U b  U R                  5       S:X  a  U nU$ [        R                  " U5      R                  n[        R                  " X4XUR
                  S9nUS:w  a  [        R                  " USS9nU[        R                  " X$R
                  S9UR                  SS5      :  -  nUSSSS2SS24   R                  USSS5      nU b  UR                  5       nU R                  S   n	USS2SS2SS2SU	24   U SS2SSSS24   R                  UR
                  5      -   n
U
S:H  n
USS2SS2SS2SU	24   R                  X5      USS2SS2SS2SU	24'   U$ )	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.
    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   )diagonalrt  r#   r   )r"   r'   r  r  fullr&   triur~  r2   r1   cloner0   r)   masked_fill)r   rB   r  r]   r  rA   r  r4  r  mask_lengthpadding_masks              rH   r  EGraniteMoeModel._prepare_4d_causal_attention_mask_with_cache_position-  s}   > %.*<*<*>!*C(K* ' E*..I** 0Y\j\q\qK !##jjqA5<<>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 rY   )rd  ri  rh  r   rU   rf  r   rg  r  ra  rk  rj  rl  rb  )NNNNNNNNNNN)F)rj   rk   rl   rm   r   rO   r   r   r'   r)  r(  r   r	   listrH  r*  r%   r   rd   r  staticmethodr4   r]   r  rn   ro   rp   s   @rH   r]  r]  ^  s   / 2  151537KO59$(,0/3/3&*59l
E,,-l
 !.l
 u//0	l

 "%tE4E4E/F(F"GHl
   1 12l
 D>l
 $D>l
 'tnl
 'tnl
 d^l
 !!1!12l
 
u--	.l
 l
j #(BellK78B llB 	B
 B  BH 444 4 {{	4
 4 4 4rY   r]  c                      ^  \ rS rSrS/rS\4U 4S jjrS rS r\	             SS\
\R                     S\
\R                     S	\
\R                     S
\
\\\\R"                     4      S\
\R"                     S\
\R                     S\
\   S\
\   S\
\   S\
\   S\
\   S\
\R                     S\\\R                  4   S\\\4   4S jj5       rSrU =r$ )GraniteMoeForCausalLMif  zlm_head.weightrt   c                 J  > [         TU ]  U5        [        U5      U l        UR                  U l        [
        R                  " UR                  UR                  SS9U l        UR                  U l	        UR                  U l        UR                  U l        U R                  5         g )NFr   )rN   rO   r]  rK  rb  r   r   rU   lm_headrouter_aux_loss_coefr   r   r   rm  r   s     rH   rO   GraniteMoeForCausalLM.__init__i  s     $V,
 ++yy!3!3V5F5FUS$*$?$?!!33#)#=#=  	rY   c                     Xl         g r   rK  )rT   decoders     rH   set_decoder!GraniteMoeForCausalLM.set_decoderv  s    
rY   c                     U R                   $ r   r  rg   s    rH   get_decoder!GraniteMoeForCausalLM.get_decodery  s    zzrY   ro  r   r   rL  rp  labelsr  r@  rq  rA  rr  r  logits_to_keepr   c                    Ub  UOU R                   R                  nU
b  U
OU R                   R                  n
U	b  U	OU R                   R                  n	Ub  UOU R                   R                  nU R
                  " SUUUUUUUU	U
UUS.UD6nUS   n[        U[        5      (       a  [        U* S5      OUnU R                  USS2USS24   5      nUU R                   R                  -  nSnUb:  UR                  5       nU R                  " UU4SU R                   R                  0UD6nSnU
(       af  [        U(       a  UR                  OUS   U R                   U R"                  U5      nUb+  UU R$                  UR'                  UR(                  5      -  -  nU(       d!  U4USS -   nU
(       a  U4U-   nUb  U4U-   $ U$ [+        UUUUR,                  UR.                  UR0                  UR                  S9$ )	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, GraniteMoeForCausalLM

>>> model = GraniteMoeForCausalLM.from_pretrained("ibm/PowerMoE-3b")
>>> tokenizer = AutoTokenizer.from_pretrained("ibm/PowerMoE-3b")

>>> prompt = "Hey, are you conscious? Can you talk to me?"
>>> 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]
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
```N)ro  r   r   rL  rp  r  r@  rq  rA  rr  r  r   rb  r#   r   )lossaux_lossr   rL  ra   r{  r   rC  )rt   r@  rA  rq  r|  rK  r$   r4   slicer  logits_scalingr/   loss_functionrb  rI   r   r   r   r  r)   r&   r   rL  ra   r{  )rT   ro  r   r   rL  rp  r  r  r@  rq  rA  rr  r  r  r  rF  ra   slice_indicesr   r  r  outputs                         rH   rd   GraniteMoeForCausalLM.forward|  s)   P 2C1N-TXT_T_TqTq$8$D $++JjJj 	 %9$D $++JjJj 	 &1%<k$++B]B] ** 
)%+'/!5!5#)
 
   
8B>SV8W8W~ot4]kmA}a,?@A$++444\\^F%%  ;;11 	D /)4%%'"+  ((	H !11HKK4LLLY,F#"v-'+'7D7V#CVC(#33!//))!//
 	
rY   )r  rK  r   r   r  rb  )NNNNNNNNNNNNr   )rj   rk   rl   rm   _tied_weights_keysr   rO   r  r  r   r   r'   r)  r(  r   r	   r  rH  r*  r4   r%   r   rd   rn   ro   rp   s   @rH   r  r  f  s   *+/   151537KO59-1$(,0/3/3&*5934k
E,,-k
 !.k
 u//0	k

 "%tE4E4E/F(F"GHk
   1 12k
 ))*k
 D>k
 $D>k
 'tnk
 'tnk
 d^k
 !!1!12k
 c5<</0k
  
u//	0!k
 k
rY   r  )r  r]  rJ  )Nr[   N)Nr   )r  )@typingr   r   r   r'   torch.nn.functionalr   r*   r   activationsr   cache_utilsr	   r
   
generationr   modeling_attn_mask_utilsr   modeling_layersr   modeling_outputsr   r   r   modeling_rope_utilsr   r   modeling_utilsr   r   utilsr   r   r   configuration_granitemoer   !torch.nn.attention.flex_attentionr   integrations.flex_attentionr   
get_loggerrj   r  r(  r%   r4   rI   ModulerK   rr   r   r   r   r   r   r   r   r/   r  r6  rJ  r]  r  __all__rC  rY   rH   <module>r     s6    - ,     ! . ) > 9 j j K F J J 6  !!;J 
		H	% "&
-1	R&u||U5<<%8$>?R&#R& U\\*	R&
 5<<R&lJ		 J*<		 <F(8*		 *\-S299 -S`5+BII 5+r	UU\\ 	U# 	U%,, 	US)")) S)z %II%<<% 
% <<	%
 U\\*% % %6U7 Up T T T" D/ D DNB
5 B
J TrY   