
    fThS                     P   S SK JrJr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!  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+  \%RX                  " \-5      r.   S9S\\R^                  \\R^                     S4   S\\0   S\\R^                     S\\R^                  \04   4S jjr1 " S S\Rd                  5      r3\!Rh                  " \35         " S S\Rd                  5      r5S r6S:S jr7 " S S\Rd                  5      r8 " S  S!\Rd                  5      r9 " S" S#\Rd                  5      r:S$\R^                  S%\0S\R^                  4S& jr; " S' S(\Rd                  5      r< S;S)\Rd                  S*\R^                  S+\R^                  S,\R^                  S\\R^                     S-\=S.\=4S/ jjr> " S0 S1\5      r?\# " S2 S3\5      5       r@\# " S4 S5\@5      5       rA " S6 S7\@\5      rB/ S8QrCg)<    )CallableListOptionalTupleUnionN)nn   )ACT2FN)CacheDynamicCache)GenerationMixin)AttentionMaskConverter)GradientCheckpointingLayer)BaseModelOutputWithPastMoeCausalLMOutputWithPastMoeModelOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)ALL_LAYERNORM_LAYERS)auto_docstringis_torch_flex_attn_availablelogging   )GraniteMoeConfig)	BlockMask)make_flex_block_causal_maskgate_logitsnum_expertsattention_maskreturnc                    U b  [        U [        5      (       d  g[        U [        5      (       aC  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                  XX45      R                  SU5      R                  U5      n[        R                   " UU-  SS9[        R                   " USS9-  n[        R                   " XR#                  S5      -  5      nUU-  $ s  snf )ap  
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.

See Switch Transformer (https://arxiv.org/abs/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   dim)
isinstancetupledevicetorchcattor   
functionalsoftmaxtopkone_hotmeanfloatshapeexpandreshapesum	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overall_losss                      j/var/www/auris/envauris/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&OQRWR%R	 	) "'?=]+]cd!ehmhqhq,!i
 "
 99.1Q1QRS1TTUL+%%[ .ks   I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powr1   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   r3   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      (       aH  UR                  b;  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   hasattrrv   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>**v/B/B/N#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   r2   r4   r3   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$   )r3   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.
)r7   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   intrO   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    r8   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   r8   r   Linearlayer)rT   r   r    r8   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   r2   r/   r8   r*   r.   type_aszerossizer    r]   r)   scatterlongr6   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    r8   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                   > [         [        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    r8   )rN   r   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__F  s    mT+- ,,!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   r5   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.forwardU  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)r3   r4   r5   )ra   r   batchnum_key_value_headsslenhead_dims         rH   	repeat_kvr   v  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  ad  U R                  R                  S:X  a-  UR                  SS5      (       a  [         R#                  S	5        O[$        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U4$ )Nr   r[   )NN)r   r   r  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.        )dropoutr	  r&   )r   r  r  r  r   r  r   r   r   r   updater   eager_attention_forwardrt   _attn_implementationr}   r  r  r   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{{//69fjjI\^c>d>d##L
 '>dkk>^>^&_#$7	%
  $}}C$2H2HLL	%
 	%
!\ "&&s26kk+.L.88rY   )r  rt   r   rU   r  r  r   r  r  r   r  r  r	  r  r   )NNNFNN)rj   rk   rl   rm   r   r   r   r   rO   r*   Tensor
LongTensorr   boolr   rd   rn   ro   rp   s   @rH   r   r     s    G`/ `HSM ` `F 2637*.59KO69||69 !.69 u//0	69
 !69 69 !!1!1269 &eELL%,,,F&GH69 
u||Xell3XeELL>Q5RR	S69 69rY   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   r3   r   r-   r.   r^   r,   r]   r  r  
contiguous)r-  r.  r/  r0  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                 .  > [         TU ]  5         UR                  U l        [        XS9U l        [        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   rV   )rN   rO   rU   r   	self_attnr   block_sparse_moerK   rms_norm_epsinput_layernormpost_attention_layernormresidual_multiplierr  s      rH   rO   GraniteMoeDecoderLayer.__init__  sz    !--,FP -f 501C1CI\I\](9&:L:LRXReRe(f%#)#=#= rY   ra   r!   r   r  r  r  r  output_router_logitsr  r"   c
                 F   UnU R                  U5      nU R                  " SUUUUUUUU	S.U
D6u  pn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(       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>  r;  r@  r?  r<  )rT   ra   r!   r   r  r  r  r  rB  r  r   residualself_attn_weightspresent_key_valuer   outputss                   rH   rd   GraniteMoeDecoderLayer.forward  s    L !,,]; ?Cnn 
?
')%)/) 3
?
 
?
;*; !43K3K#KK !55mD'+'<'<]'K$ 43K3K#KK "++G++G''GrY   )r<  rU   r>  r?  r@  r;  )NNNFFNFN)rj   rk   rl   rm   r   r   rO   r*   r*  r   r+  r   r,  r   FloatTensorrd   rn   ro   rp   s   @rH   r8  r8    s   	>/ 	>C 	> 2637*.,1$)59/4KOK||K !.K u//0	K
 !K $D>K D>K !!1!12K 'tnK &eELL%,,,F&GHK 
u  (51B1BEDUDU1U+V"WW	XK KrY   r8  c                   F    \ rS rSr\rSrSrS/rS/r	Sr
SrSrSrSrS rSrg	)
GraniteMoePreTrainedModeliU  modelTr8  past_key_valuesFc                 X   [        U[        R                  5      (       ak  UR                  R                  R                  SU R                  R                  S9  UR                  b%  UR                  R                  R                  5         g g [        U[        R                  5      (       ax  UR                  R                  R                  SU R                  R                  S9  UR                  b2  UR                  R                  UR                     R                  5         g g [        U[        5      (       a&  UR                  R                  R                  S5        g [        U[        5      (       a9  UR                  R                  R                  SU R                  R                  S9  g g )Nr  )r1   stdg      ?)r'   r   r   rR   datanormal_rt   initializer_ranger   zero_	Embeddingpadding_idxrK   fill_r   )rT   r-  s     rH   _init_weights'GraniteMoePreTrainedModel._init_weightsb  s)   fbii((MM&&CT[[5R5R&S{{&  &&( '--MM&&CT[[5R5R&S!!-""6#5#56<<> . 122MM$$S) 9::MM&&CT[[5R5R&S ;rY   rD  N)rj   rk   rl   rm   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_cache_class_supports_quantized_cache_supports_static_cacherX  rn   rD  rY   rH   rL  rL  U  sH    #L&*#12#4"5!N  $"TrY   rL  c                   @  ^  \ 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\	\   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\
R0                  S\
R                  S\4S j5       rSrU =r$ )GraniteMoeModeliq  rt   c           	      8  > [         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 )Nr:  Frope)rN   rO   pad_token_idrV  
vocab_sizer   rU  rU   embed_tokens
ModuleListr   rD   r8  layersrK   r=  normgradient_checkpointingembedding_multiplierr  r  r   r~   
rope_thetaposition_embedding_typerr   
rotary_emb	post_initr  s      rH   rO   GraniteMoeModel.__init__s  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c                     U R                   $ r   rj  rg   s    rH   get_input_embeddings$GraniteMoeModel.get_input_embeddings  s       rY   c                     Xl         g r   rv  rT   r0  s     rH   set_input_embeddings$GraniteMoeModel.set_input_embeddings  s    !rY   	input_idsr!   r   rN  inputs_embedsr  r  output_hidden_statesrB  return_dictr  r"   c                 t   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SnU(       aB  [        U[        5      (       d-  Sn[        R                  " U5      n[        R                  S5        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S nU R0                   HZ  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(       a  SOS   nU(       a	  UUS   4-  nU	(       d  MQ  UUS   4-  nM\     U R3                  U5      nU(       a  UU4-  nU(       a  UOS nU(       a  UR5                  5       nU
(       d  [7        S UUUU4 5       5      $ [9        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`.FTzWe detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)r   r   r)   rD  )r!   r   r  r  r  r  rB  r  r[   r&   c              3   .   #    U  H  oc  M  Uv   M     g 7fr   rD  ).0vs     rH   	<genexpr>*GraniteMoeModel.forward.<locals>.<genexpr>  s     t$bq$bs   	)last_hidden_staterN  ra   
attentionsr   )rt   r  r  r  use_return_dictr
  rn  r  r  r  rj  ro  r'   r   r   from_legacy_cacheget_seq_lengthr*   aranger3   r)   r7   _update_causal_maskrr  rl  rm  to_legacy_cacher(   r   )rT   r}  r!   r   rN  r~  r  r  r  rB  r  r  return_legacy_cachepast_seen_tokensr6  ra   r  all_hidden_statesall_self_attnsall_router_logitsnext_decoder_cachedecoder_layerlayer_outputs
next_caches                           rH   rd   GraniteMoeModel.forward  s    2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]-t";<YZZ&&4==Yj I  --i8M%(A(AA#Z??"&*<<_MO]
 !CRC^==?de"\\ ]5H5H5K"KTaThThN )33A6L..>L]

 &"??&"&//-"N #7BD0d"6BD!![[M#!m%55!)*)."3#-%9$7
M *!,M%28I1q%Q" =#3"55##!mB&7%99!3 )6 		-0  -!11+4'$
#335Jt]J@QSa$bttt%+&+%+
 	
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   Fr  )r~  past_key_values_lengthis_trainingr   r&   )rC   target_lengthr]   r  rB   )cudaxpunpu)rt   r  anyr'   r*   r*  r   r  is_compileabler   _ignore_causal_mask_sdpar  r]   r3   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr)   rx   finfomin_unmask_unattended)rT   r!   r  r  rN  r  r  using_compilable_cacher]   rC   r  r6  	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   rC   r  r]   rB   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   )diagonalr  r&   r   )r%   r*   r  r  fullr)   triur  r5   r4   cloner3   r,   masked_fill)r!   rC   r  r]   r  rB   r   r6  r  mask_lengthpadding_masks              rH   r  EGraniteMoeModel._prepare_4d_causal_attention_mask_with_cache_positionM  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   )rj  ro  rn  r   rU   rl  r~   rm  r  rV  rq  rp  rr  ri  )NNNNNNNNNNN)F)rj   rk   rl   rm   r   rO   rw  r{  r   r   r*   r+  r*  r   r   r   rJ  r,  r   r   rd   r  staticmethodr   r]   r  rn   ro   rp   s   @rH   re  re  q  s   / 2!"  151537KO59$(,0/3/3&*59s
E,,-s
 !.s
 u//0	s

 "%tE4E4E/F(F"GHs
   1 12s
 D>s
 $D>s
 'tns
 'tns
 d^s
 !!1!12s
 
u--	.s
 s
x #(BellK78B llB 	B
 B  BH 444 4 {{	4
 4 4 4rY   re  c                      ^  \ rS rSrS/rS\4U 4S jjrS rS rS r	S 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 5       rSrU =r$ )GraniteMoeForCausalLMi  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   re  rM  ri  r   r   rU   lm_headrouter_aux_loss_coefr   r    r   rs  r   s     rH   rO   GraniteMoeForCausalLM.__init__  s     $V,
 ++yy!3!3V5F5FUS$*$?$?!!33#)#=#=  	rY   c                 .    U R                   R                  $ r   rM  rj  rg   s    rH   rw  *GraniteMoeForCausalLM.get_input_embeddings  s    zz&&&rY   c                 $    XR                   l        g r   r  rz  s     rH   r{  *GraniteMoeForCausalLM.set_input_embeddings  s    "'

rY   c                     U R                   $ r   r  rg   s    rH   get_output_embeddings+GraniteMoeForCausalLM.get_output_embeddings  s    ||rY   c                     Xl         g r   r  )rT   new_embeddingss     rH   set_output_embeddings+GraniteMoeForCausalLM.set_output_embeddings  s    %rY   c                     Xl         g r   rM  )rT   decoders     rH   set_decoder!GraniteMoeForCausalLM.set_decoder  s    
rY   c                     U R                   $ r   r  rg   s    rH   get_decoder!GraniteMoeForCausalLM.get_decoder  s    zzrY   r}  r!   r   rN  r~  labelsr  r  r  rB  r  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                  UUUUUUUU	U
UUS9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)r}  r!   r   rN  r~  r  r  r  rB  r  r  r   ri  r&   r   )lossaux_lossr   rN  ra   r  r   )rt   r  rB  r  r  rM  r'   r   slicer  logits_scalingr2   loss_functionri  rI   r   r    r   r  r,   r)   r   rN  ra   r  )rT   r}  r!   r   rN  r~  r  r  r  r  rB  r  r  r  r   rH  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   c                 P   ^ SnU  H  nU[        U4S jU 5       5      4-  nM     U$ )NrD  c              3   x   >#    U  H/  oR                  S TR                  UR                  5      5      v   M1     g7f)r   N)index_selectr,   r)   )r  
past_statebeam_idxs     rH   r  7GraniteMoeForCausalLM._reorder_cache.<locals>.<genexpr>  s1     ncmU_--aZ=N=N1OPPcms   7:)r(   )rN  r  reordered_past
layer_pasts    `  rH   _reorder_cache$GraniteMoeForCausalLM._reorder_cache  s8    )Jncmnn N * rY   )r  rM  r    r   r  ri  )NNNNNNNNNNNNr   )rj   rk   rl   rm   _tied_weights_keysr   rO   rw  r{  r  r  r  r  r   r   r*   r+  r*  r   r   r   rJ  r,  r   r   r   rd   r  r  rn   ro   rp   s   @rH   r  r    s   *+/ '(&  151537KO59-1$(,0/3/3&*5934j
E,,-j
 !.j
 u//0	j

 "%tE4E4E/F(F"GHj
   1 12j
 ))*j
 D>j
 $D>j
 'tnj
 'tnj
 d^j
 !!1!12j
 c5<</0j
  
u//	0!j
 j
X  rY   r  )r  re  rL  )Nr[   N)Nr   )r  )Dtypingr   r   r   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   pytorch_utilsr   utilsr   r   r   configuration_granitemoer   !torch.nn.attention.flex_attentionr   integrations.flex_attentionr   
get_loggerrj   r  r*  r   rI   ModulerK   r   rr   r   r   r   r   r   r   r   r2   r  r8  rL  re  r  __all__rD  rY   rH   <module>r     sJ    : 9     ! . ) > 9 j j K F 1 J J 6  !!;J 
		H	% "&
-1	O&u||U5<<%8$>?O&#O& U\\*	O&
 5<<O&fJ		 J(   - .<		 <F(8*		 *\-S299 -S`5+BII 5+r	UU\\ 	U# 	U%,, 	UY9")) Y9F %II%<<% 
% <<	%
 U\\*% % %6W7 Wt T T T6 Q/ Q QhV5 Vr TrY   