
    cCi;                     $   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#  SSK$J%r%  \ " 5       (       a  S SK&J'r'  SSK(J)r)  \!RT                  " \+5      r,   S9S\\RZ                  \.\RZ                     S4   S\\/   S\\RZ                     S\\RZ                  \/4   4S jjr0 " S S\Rb                  5      r2 " S S\Rb                  5      r3S r4S:S jr5 " S S\Rb                  5      r6 " S  S!\Rb                  5      r7 " S" S#\Rb                  5      r8S$\RZ                  S%\/S\RZ                  4S& jr9 " S' S(\Rb                  5      r: S;S)\Rb                  S*\RZ                  S+\RZ                  S,\RZ                  S\\RZ                     S-\;S.\;4S/ jjr< " S0 S1\5      r=\ " S2 S3\5      5       r>\ " S4 S5\>5      5       r? " S6 S7\>\5      r@/ S8QrAg)<    )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)deprecate_kwarg   )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                  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                  R"                  b  UR                  R"                  OSnUR                  S   [%        U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indexint	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device_indexrankoverall_losss                        l/home/james-whalen/.local/lib/python3.13/site-packages/transformers/models/granitemoe/modeling_granitemoe.pyload_balancing_loss_funcrK   -   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
 "
 4C3I3I3O3O3[?))//abL  #c,&77D99!TD?+@+@+C$CCCDG]GgGghiGjjL +%%c .ks   K	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      rJ   rQ   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/   rsqrtrU   rT   )rV   hidden_statesinput_dtypevariances       rJ   forwardGraniteMoeRMSNorm.forward   sw    #))%((7 $$Q',,R,>%H?T?T4T(UU{{]--k:::r[   c                 ^    [        U R                  R                  5       SU R                   3$ )Nz, eps=)r&   rT   r1   rU   )rV   s    rJ   
extra_reprGraniteMoeRMSNorm.extra_repr   s*    ))*+6$2G2G1HIIr[   )rU   rT   )gư>)	__name__
__module____qualname____firstlineno__rQ   rf   ri   __static_attributes____classcell__rY   s   @rJ   rM   rM      s    $;J Jr[   rM   c                      ^  \ rS rSr% \R
                  \S'   SS\4U 4S jjjr\R                  " 5       \
S 5       5       rSrU =r$ )GraniteMoeRotaryEmbedding   inv_freq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defaultru   F)
persistent)rP   rQ   hasattrr%   rx   dictgetry   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrv   r   rope_init_fnattention_scalingregister_bufferru   original_inv_freq)rV   rv   r'   ru   rY   s       rJ   rQ   "GraniteMoeRotaryEmbedding.__init__   s    6>**z&:M:Mt/T/T#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q((ZeD!%r[   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_   )ru   r0   r2   r1   r*   r'   r%   rz   strr(   autocast	transposer)   cosr   sinr_   )
rV   xposition_idsinv_freq_expandedposition_ids_expandedr   freqsembr   r   s
             rJ   rf   !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   rv   r   r   r   r   ry   N)rk   rl   rm   rn   r(   Tensor__annotations__r   rQ   no_gradr   rf   ro   rp   rq   s   @rJ   rs   rs      sA    ll// / /" ]]_<  <r[   rs   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"   )r1   r(   r)   )r   x1x2s      rJ   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r[   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           rJ   apply_rotary_pos_embr      sS    ( --
&C
--
&Cw;q>C/0Gw;q>C/0Gr[   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)
rP   rQ   r   rR   r(   emptyrT   r   r   r   )rV   r   r   r   rY   s       rJ   rQ   "GraniteMoeParallelExperts.__init__   s<    " 	ll5;;{#TU&$&r[   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linearrT   r(   r)   )rV   inputsexpert_size
input_listoutput_listiresultss          rJ   rf   !GraniteMoeParallelExperts.forward   sh     \\+1\5
t''(Aqxx
t{{1~FG )))KQ/r[   )r   r   r   rT   	rk   rl   rm   rn   r6   rQ   rf   ro   rp   rq   s   @rJ   r   r      s.    'C 'S 's 't '. r[   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)rP   rQ   r   r   r8   r   Linearlayer)rV   r   r   r8   rY   s       rJ   rQ   GraniteMoeTopKGating.__init__  s2     	&$
YYzUC
r[   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   r0   r-   r8   r(   r,   type_aszerossizer   r_   r'   scatterlongr4   tolistflattensortdiv)rV   rc   logitstop_k_logitstop_k_indicestop_k_gatesr   gatesr   top_k_expertsr=   index_sorted_expertsbatch_indexbatch_gatess                 rJ   rf   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Rr[   )r   r   r   r8   r   rq   s   @rJ   r   r     s-    D3 DS D D&S Sr[   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.
rv   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   r8   )rP   rQ   rW   r   intermediate_sizer   
hidden_act
activationr   num_local_expertsinput_linearoutput_linearr   num_experts_per_tokrouterrV   rv   rY   s     rJ   rQ   GraniteMoeMoE.__init__I  s     ,,!33 !2!235f6N6NPTP_P_aeaqaqtuauv6v7O7OQUQaQacgcrcrs*00,,
r[   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   r3   r   r   chunkr   r   r(   r   r   r_   r'   	index_addview)rV   layer_inputbszlengthemb_sizer=   r   r   r   router_logitsexpert_inputsrc   chunked_hidden_statesexpert_outputsr   layer_outputs                   rJ   rf   GraniteMoeMoE.forwardX  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**r[   )r   rW   r   r   r   r   )
rk   rl   rm   rn   __doc__r   rQ   rf   ro   rp   rq   s   @rJ   r   r   @  s    
/ 
+ +r[   r   rc   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)r1   r2   r3   )rc   r   batchnum_key_value_headsslenhead_dims         rJ   	repeat_kvr   y  s_    
 2?1D1D.Ez!!Qa"23::5W\dlmM  e(CTTTr[   c                     ^  \ rS rSrSrSS\S\\   4U 4S jjjr\	" SSSS	9      SS
\
R                  S\\
R                     S\\
R                     S\\   S\S\\
R                     S\\\
R                  \
R                  4      S\\
R                  \\
R                     \\\
R                        4   4S jj5       rSrU =r$ )GraniteMoeAttentioni  z=Multi-headed attention from 'Attention Is All You Need' paperrv   	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   )rP   rQ   rv   r  loggerwarning_oncerY   rk   attention_dropoutrW   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rV   rv   r  rY   s      rJ   rQ   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^_r[   past_key_valuepast_key_values4.58new_nameversionrc   r   r   	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_forwardrv   _attn_implementationr   trainingr  r  r  )rV   rc   r   r   r  r  r  r  kwargsr   q_lenr=   query_states
key_statesvalue_statesr   r   cache_kwargsattention_interfaceattn_outputattn_weightss                        rJ   rf   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'6'='=jX\XfXfht'u$J(?;;++w6"9$++:Z:Z"[$7	%
  $}}C$2H2HLL	%
 	%
!\ "&&s26kk+.L((r[   )r  rv   r   rW   r
  r  r  r  r	  r   r  r  r  r  r   )NNNFNN)rk   rl   rm   rn   r   r   r   r6   rQ   r   r(   r   
LongTensorr	   boolr&   rf   ro   rp   rq   s   @rJ   r  r    s   G`/ `HSM ` `@ %0A6R 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) S0)r[   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   r1   r   r+   r,   r`   r*   r_   r!  r%  
contiguous)r2  r3  r4  r5  r   r  r!  r&  r)  r*  r.  causal_maskr-  s                rJ   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$$r[   c                     ^  \ rS rSrS\S\4U 4S jjr\" SSSS9        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5       rSrU =r$ )GraniteMoeDecoderLayeri  rv   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)rv   r  r   rX   )rP   rQ   rW   r  	self_attnr   r   block_sparse_moerM   rms_norm_epsinput_layernormpost_attention_layernormresidual_multiplierr  s      rJ   rQ   GraniteMoeDecoderLayer.__init__  s    !--,FP##a'$1&$9D!01C1CI\I\](9&:L:LRXReRe(f%#)#=#= r[   r  r  r  r  rc   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$ )aG  
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_values (`Cache`, *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
)rc   r   r   r  rG  r  r  r   )rC  r@  rE  rD  rA  )rV   rc   r   r   r  rG  r  r  rH  r  r&  residualself_attn_weightsr   outputss                  rJ   rf   GraniteMoeDecoderLayer.forward  s    N !,,]; ,0>> 
,
')%+/) 3
,
 
,
( !43K3K#KK !55mD'+'<'<]'K$ 43K3K#KK "++G''Gr[   )rA  rW   rC  rD  rE  r@  )NNNFFNFN)rk   rl   rm   rn   r   r6   rQ   r   r(   r   r   r0  r	   r1  r&   FloatTensorrf   ro   rp   rq   s   @rJ   r=  r=    s4   
>/ 
>C 
> %0A6R 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 SHr[   r=  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$ )
GraniteMoePreTrainedModeliR  rv   modelTr=  r  Fc                    > [         TU ]  U5        [        U[        5      (       a9  UR                  R
                  R                  SU R                  R                  S9  g g )Nr   )r/   std)	rP   _init_weightsr%   r   rT   datanormal_rv   initializer_range)rV   r2  rY   s     rJ   rU  'GraniteMoePreTrainedModel._init_weights^  sJ    f%f788MM&&CT[[5R5R&S 9r[   rJ  )rk   rl   rm   rn   r   r   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_can_compile_fullgraphrU  ro   rp   rq   s   @rJ   rQ  rQ  R  sD    &*#12#4"5N"T Tr[   rQ  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$ )GraniteMoeModelid  rv   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)rP   rQ   pad_token_idpadding_idx
vocab_sizer   	EmbeddingrW   embed_tokens
ModuleListr   rD   r=  layersrM   rB  normgradient_checkpointingembedding_multiplierr  r  r   r   
rope_thetaposition_embedding_typers   
rotary_emb	post_initr  s      rJ   rQ   GraniteMoeModel.__init__f  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   r  inputs_embedsr  rG  output_hidden_statesrH  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(       a  Uc  [        U R                   S9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 R*                   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 R-                  U5      nU(       a  UU4-  nU
(       d  [/        S XUU4 5       5      $ [1        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`.F)rv   r   r   r'   rJ  )r   r   r  rG  r  r  rH  r  r$   c              3   .   #    U  H  oc  M  Uv   M     g 7fr   rJ  ).0vs     rJ   	<genexpr>*GraniteMoeModel.forward.<locals>.<genexpr>  s      ^a^s   	)last_hidden_stater  rc   
attentionsr   )rv   rG  rv  r  use_return_dictr  rm  r%  r  r  ri  rn  r
   get_seq_lengthr(   aranger1   r'   r7   _update_causal_maskrq  rk  rl  r&   r   )rV   rt  r   r   r  ru  r  rG  rv  rH  rw  r  r&  past_seen_tokensr;  rc   r  all_hidden_statesall_self_attnsall_router_logitsdecoder_layerlayer_outputss                         rJ   rf   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0*$++>O!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~^   &+++%+
 	
r[   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)ru  past_key_values_lengthis_trainingr   r$   )rC   target_lengthr_   r  rB   )cudaxpunpu)rv   r$  anyr%   r(   r   r   r  is_compileabler   _ignore_causal_mask_sdpar%  r_   r1   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr'   rz   finfomin_unmask_unattended)rV   r   r  r  r  rG  r  using_compilable_cacher_   rC   r  r;  	min_dtypes                rJ   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r[   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   )diagonalry  r$   r   )r#   r(   r  r  fullr'   triur  r3   r2   cloner1   r*   masked_fill)r   rC   r  r_   r  rB   r&  r;  r  mask_lengthpadding_masks              rJ   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 r[   )ri  rn  rm  r   rW   rk  r   rl  r  rf  rp  ro  rq  rg  )NNNNNNNNNNN)F)rk   rl   rm   rn   r   rQ   r   r   r(   r0  r   r   r	   listrO  r1  r&   r   rf   r  staticmethodr6   r_   r  ro   rp   rq   s   @rJ   rb  rb  d  s   / 2  151537KO59$(,0/3/3&*59h
E,,-h
 !.h
 u//0	h

 "%tE4E4E/F(F"GHh
   1 12h
 D>h
 $D>h
 'tnh
 'tnh
 d^h
 !!1!12h
 
u--	.h
 h
b #(BellK78B llB 	B
 B  BH 444 4 {{	4
 4 4 4r[   rb  c                      ^  \ rS 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
\\	R                     S\\   S\\   S\\   S\\   S\\   S\\	R                     S\\\	R                  4   S\\\4   4S jj5       rSrU =r$ )GraniteMoeForCausalLMih  zlm_head.weightrv   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   )rP   rQ   rb  rR  rg  r   r   rW   lm_headrouter_aux_loss_coefr   r   r   rr  r   s     rJ   rQ   GraniteMoeForCausalLM.__init__k  s     $V,
 ++yy!3!3V5F5FUS$*$?$?!!33#)#=#=  	r[   rt  r   r   r  ru  labelsr  rG  rv  rH  rw  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)rt  r   r   r  ru  r  rG  rv  rH  rw  r  r   rg  r$   r   )lossaux_lossr   r  rc   r  r   rJ  )rv   rG  rH  rv  r  rR  r%   r6   slicer  logits_scalingr0   loss_functionrg  rK   r   r   r   r  r*   r'   r   r  rc   r  )rV   rt  r   r   r  ru  r  r  rG  rv  rH  rw  r  r  r&  rM  rc   slice_indicesr   r  r  outputs                         rJ   rf   GraniteMoeForCausalLM.forwardx  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!//))!//
 	
r[   )r  rR  r   r   r  rg  )NNNNNNNNNNNNr   )rk   rl   rm   rn   _tied_weights_keysr   rQ   r   r   r(   r0  r   r   r	   r  rO  r1  r6   r&   r   rf   ro   rp   rq   s   @rJ   r  r  h  sw   *+/   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
r[   r  )r  rb  rQ  )Nr]   N)Nr   )r   )B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   utils.deprecationr   configuration_granitemoer   !torch.nn.attention.flex_attentionr   integrations.flex_attentionr   
get_loggerrk   r  r   r&   r6   rK   ModulerM   rs   r   r   r   r   r   r   r  r0   r#  r=  rQ  rb  r  __all__rJ  r[   rJ   <module>r     s9    - ,     ! . ) > 9 j j K F J J 0 6  !!;J 
		H	% "&
-1	S&u||U5<<%8$>?S&#S& U\\*	S&
 5<<S&nJ		 J*!<		 !<J(8*		 *\-S299 -S`5+BII 5+r	UU\\ 	U# 	U%,, 	UT)")) T)| %II%<<% 
% <<	%
 U\\*% % %6V7 Vr T T T" @/ @ @F|
5 |
~ Tr[   