
    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Jr  SS
KJr  SSKJr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$  SSK%J&r&  SSK'J(r(J)r)J*r*  SSK+J,r,  SSK-J.r.J/r/  SSK0J1r1  \" S5       " S S\Rd                  5      5       r3 " S S\5      r4 " S S\Rd                  5      r5S r6SES jr7S\Rp                  S\9S \Rp                  4S! jr: SFS"\Rd                  S#\Rp                  S$\Rp                  S%\Rp                  S&\\Rp                     S'\;S(\;S)\&\(   4S* jjr< " S+ S,\Rd                  5      r= " S- S.\Rd                  5      r> " S/ S0\Rd                  5      r? " S1 S2\5      r@\) " S3 S4\$5      5       rA " S5 S6\Rd                  5      rB\) " S7 S8\A5      5       rC   SGS9\\Rp                  \D\Rp                     S4   S:\\9   S&\\Rp                     S \\Rp                  \94   4S; jjrE\) " S< S=\A\5      5       rF " S> S?\\A5      rG " S@ SA\\A5      rH " SB SC\\A5      rI/ SDQrJg)H    )CallableOptionalUnionN)nn   )ACT2FN)CacheDynamicCache)GenerationMixin)use_kernel_forward_from_hub)create_causal_mask!create_sliding_window_causal_mask)FlashAttentionKwargs)GenericForQuestionAnswering GenericForSequenceClassificationGenericForTokenClassificationGradientCheckpointingLayer)MoeCausalLMOutputWithPastMoeModelOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuple)deprecate_kwarg)OutputRecordercheck_model_inputs   )MiniMaxConfigRMSNormc                   8   ^  \ rS rSrSU 4S jjrS rS rSrU =r$ )MiniMaxRMSNorm3   c                    > [         TU ]  5         [        R                  " [        R
                  " U5      5      U l        X l        g)z-
MiniMaxRMSNorm is equivalent to T5LayerNorm
N)super__init__r   	Parametertorchonesweightvariance_epsilon)selfhidden_sizeeps	__class__s      f/home/james-whalen/.local/lib/python3.13/site-packages/transformers/models/minimax/modeling_minimax.pyr)   MiniMaxRMSNorm.__init__5   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   T)keepdim)	dtypetor+   float32powmeanrsqrtr.   r-   )r/   hidden_statesinput_dtypevariances       r3   forwardMiniMaxRMSNorm.forward=   sw    #))%((7 $$Q',,R,>%H?T?T4T(UU{{]--k:::r5   c                 ^    [        U R                  R                  5       SU R                   3$ )Nz, eps=)tupler-   shaper.   )r/   s    r3   
extra_reprMiniMaxRMSNorm.extra_reprD   s*    ))*+6$2G2G1HIIr5   )r.   r-   )gư>)	__name__
__module____qualname____firstlineno__r)   rC   rH   __static_attributes____classcell__r2   s   @r3   r%   r%   3   s    $;J Jr5   r%   c                      ^  \ rS rSrU 4S jrS rS\4S jrU 4S jrS\4U 4S jjr	S r
S	\4S
 jrS\R                  4S jrS\4S jrSrU =r$ )MiniMaxCacheH   c                 0   > [         TU ]  5         / U l        g N)r(   r)   linear_cacher/   r2   s    r3   r)   MiniMaxCache.__init__I   s    02r5   c                     [        [        U R                  5      US-   5       H  nU R                  R                  / 5        M      X R                  U'   g Nr!   )rangelenrV   append)r/   	layer_idxrV   _s       r3   set_linear_cacheMiniMaxCache.set_linear_cacheM   sD    s4,,-y1}=A$$R( >'3)$r5   r^   c                 @    U[        U 5      :  a  U R                  U   $ g rU   )r\   rV   r/   r^   s     r3   get_linear_cacheMiniMaxCache.get_linear_cacheS   s"    s4y $$Y//r5   c                 Z   > [        [        TU ]	  5       [        U R                  5      5      $ rU   )maxr(   __len__r\   rV   rW   s    r3   rh   MiniMaxCache.__len__X   s"    57?$c$*;*;&<==r5   c                    > U[        U R                  5      :  a#  U R                  U   / :w  a  U R                  U   4$ [        TU ]  U5      $ rU   )r\   rV   r(   __getitem__)r/   r^   r2   s     r3   rk   MiniMaxCache.__getitem__[   sM    s4,,--$2C2CI2NRT2T%%i022w"9--r5   c              #   N   #    [        [        U 5      5       H	  nX   v   M     g 7frU   )r[   r\   rc   s     r3   __iter__MiniMaxCache.__iter__`   s      s4y)I/! *s   #%repeatsc                     [        [        U 5      5       H`  nU R                  U   / :w  a,  U R                  U   R                  USS9U R                  U'   MB  U R                  U   R                  U5        Mb     g )Nr   dim)r[   r\   rV   repeat_interleavelayersbatch_repeat_interleave)r/   rp   r^   s      r3   rv   $MiniMaxCache.batch_repeat_interleaved   sl    s4y)I  +r1/3/@/@/K/]/]^ekl/]/m!!),I&>>wG	 *r5   indicesc                     [        [        U 5      5       HW  nU R                  U   / :w  a#  U R                  U   US4   U R                  U'   M9  U R                  U   R	                  U5        MY     g )N.)r[   r\   rV   ru   batch_select_indices)r/   rx   r^   s      r3   rz   !MiniMaxCache.batch_select_indicesk   sd    s4y)I  +r1/3/@/@/KGUXL/Y!!),I&;;GD	 *r5   
max_lengthc                     [        S5      e)Nz*MiniMaxCache doesnot support `crop` method)RuntimeError)r/   r|   s     r3   cropMiniMaxCache.cropr   s    GHHr5   )rV   )rJ   rK   rL   rM   r)   r`   intrd   rh   rk   rn   rv   r+   Tensorrz   r   rN   rO   rP   s   @r3   rR   rR   H   sc    34# 
>.S .
"Hs HEELL EIs I Ir5   rR   c                   d  ^  \ rS rSrS\S\4U 4S jjrS rS r\	" SSS	S
9  SS\
R                  S\\
R                  \
R                  4   S\\
R                     S\\   S\\
R                     S\\   S\\
R                  \\
R                     \\\
R                        4   4S jj5       rSrU =r$ )MiniMaxLightningAttentionv   configr^   c                   > [         TU ]  5         X l        [        USS 5      =(       d    UR                  UR
                  -  U l        UR
                  U l        UR                  U l        UR                  U l        [        UR                     U l        [        U R                  U R
                  -  5      U l        [        R                  " UR                  U R
                  U R                  -  S-  SS9U l        [        R                  " U R
                  U R                  -  UR                  SS9U l        [        R                  " UR                  U R
                  U R                  -  SS9U l        U R'                  5       nU R)                  U5      u  pEnU R+                  SU5        U R+                  SU5        U R+                  SU5        U R+                  SU5        g )	Nhead_dimr   Fbias
slope_ratequery_decay	key_decaydiagonal_decay)r(   r)   r^   getattrr0   num_attention_headsr   num_hidden_layers
block_sizer   
hidden_actact_fnr%   normr   Linearqkv_projout_projoutput_gateget_slope_ratedecay_factorsregister_buffer)r/   r   r^   r   r   r   r   r2   s          r3   r)   "MiniMaxLightningAttention.__init__w   s   "
D9mV=O=OSYSmSm=m#)#=#= !'!9!9 ++V../"4==43K3K#KL			&"4"4d6N6NQUQ^Q^6^ab6bino		$":":T]]"JFL^L^ejk99V%7%79Q9QTXTaTa9ahmn((*
151C1CJ1O.\:6]K8[)4-~>r5   c                     SSSU R                   -  -  -  n[        R                  " U R                   5      S-   nSU R                  U R                  S-
  S-   -  -
  S-   nX-  nXC-  nUS S 2S S 4   nU$ )Nr!   r7      gh㈵>)r   r+   aranger^   r   )r/   baseexponentfactorrates        r3   r   (MiniMaxLightningAttention.get_slope_rate   s    A!d66678<< 8 89A=T^^t'='='AD'HIIDP~}AtTM"r5   c                    [         R                  " U R                  5      S-   n[         R                  " U* US S 2S 4   -  5      n[         R                  " U* U R                  US S 2S 4   -
  -  5      nUS S 2S 4   US S S 24   -
  nUS S S S 2S S 24   nX-  n[         R                  " US:  U* [        S5      5      n[         R                  " U5      nX4U4$ )Nr!   r   z-inf)r+   r   r   expwherefloat)r/   r   block_size_ranger   r   r   s         r3   r   'MiniMaxLightningAttention.decay_factors   s     <<81<ii.>q$w.G GHIIzkT__?OPQSWPW?X-XYZ	)!T'25EdAg5NN'dAq(89#4^q%8>/5QW=Y>2~55r5   past_key_valuepast_key_values4.58new_nameversionr@   position_embeddingsattention_maskcache_positionkwargsreturnc                 	   UR                   u  pxn	XR                  -   S-
  U R                  -  n
U R                  U R                  U5      5      nUR	                  XxU R
                  SU R                  -  5      n[        R                  " XR                  SS9u  pnUR                  SS5      nUR                  SS5      nUR                  SS5      nS nUb  UR                  U R                  5      nUGc  [        R                  " XpR
                  U R                  U R                  5      R                  U5      nUbN  UR                  [        R                  S9nUR                  UR!                  S5      R!                  S5      ) S5      n/ n[#        U
5       GHh  nUU R                  -  n[%        UU R                  -   U5      nUU-
  nUS S 2S S 2UU24   nUS S 2S S 2UU24   nUS S 2S S 2UU24   nU R&                  S S 2S U24   nU R(                  S S 2U* S 24   nU R*                  S S 2S S 2S U2S U24   n[        R,                  " U R.                  * U-  5      n[        R0                  " UUR                  SS5      5      n[        R0                  " UU-  U5      n[        R0                  " UU-  U5      nUU-   nUR3                  U5        [        R0                  " UU-  R                  SS5      U5      n UU-  U -   nGMk     O[        R,                  " U R.                  * 5      n!/ n[#        U5       H  nUS S 2S S 2UUS-   24   nUS S 2S S 2UUS-   24   nUS S 2S S 2UUS-   24   n[        R0                  " UR                  SS5      U5      n"U!U-  U"-   n[        R0                  " UU5      nUR3                  U5        M     [        R4                  " USS9nUR                  SS5      nUR	                  XxU R
                  U R                  -  5      nU R7                  U5      n[8        R:                  " U R=                  U5      5      U-  nU R?                  U5      nUb  URA                  U R                  U5        UU4$ )	Nr!   r   rr   r7   r:   r8   r   )!rG   r   r   r   reshaper   r   r+   split	transposerd   r^   zerosr;   boolmasked_fill	unsqueezer[   minr   r   r   r   r   matmulr]   catr   Fsigmoidr   r   r`   )#r/   r@   r   r   r   r   r   
batch_sizeseq_lenr0   
num_blocks
qkv_statesquery_states
key_statesvalue_statesattn_weights_interattn_outputi	start_idxend_idxcurrent_block_sizecurrent_query_statescurrent_key_statescurrent_value_statescurrent_query_decaycurrent_key_decaycurrent_diagonal_decayblock_decayattn_weights_intraattn_output_intraattn_output_intercurrent_attn_outputnext_attn_weights_interratiocurrent_attn_weights_inters#                                      r3   rC   !MiniMaxLightningAttention.forward   s    ,9+>+>(
[/!3G
[[}!=>
''
T=U=UWX[_[h[hWhi
16Z\]1^.,#--a3))!Q/
#--a3 "&!0!A!A$..!Q%!&Z9Q9QSWS`S`bfbobo!p!s!s"
 )!/!2!2!2!D+779Q9QRS9T9^9^_a9b8bdefK:&/	i$//97C%,y%8"'3Aq)G:K4K'L$%/1i6G0G%H"'3Aq)G:K4K'L$&*&6&6q:M;M:M7M&N#$(NN17I6I6J3J$K!)-)<)<QCVDVCVXkYkXk=k)l&#ii(8;M(MN &+\\2FHZHdHdegikHl%m"$)LL1CF\1\^r$s! %*LL1EH[1[]o$p! '8:K&K#""#67 +0,,'*;;FFr2NPd+' &8+%EH_%_"; '@ IIt./EK7^'3Aq!a!e)O'D$%/1a!a%i%@"'3Aq!a!e)O'D$-2\\:L:V:VWY[]:^`t-u*%*-?%?B\%\"&+ll3GI[&\#""#67 $ ii4 "++Aq1!))*t?W?WZ^ZgZg?ghii,ii 0 0 ?@;NmmK0 &,,T^^=OP...r5   )
r   r   r   r^   r   r   r   r   r   r   NN)rJ   rK   rL   rM   r"   r   r)   r   r   r   r+   r   rF   r   r	   
LongTensorr   r   rC   rN   rO   rP   s   @r3   r   r   v   s    ?} ? ?,	6 %0A6R ,059`/||`/ #5<<#=>`/ !.	`/
 "%`/ !!1!12`/ -.`/ 
u||Xell3XeELL>Q5RR	S`/ S`/r5   r   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..Nr8   r7   rr   )rG   r+   r   )xx1x2s      r3   rotate_halfr   
  sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r5   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.
)r   r   )qkcossinposition_idsunsqueeze_dimq_embedk_embeds           r3   apply_rotary_pos_embr     sS    ( --
&C
--
&Cw;q>C/0Gw;q>C/0Gr5   r@   n_repr   c                     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)rG   expandr   )r@   r   batchnum_key_value_headsslenr   s         r3   	repeat_kvr   ,  s_    
 2?1D1D.Ez!!Qa"23::5W\dlmM  e(CTTTr5   modulequerykeyvaluer   scalingdropoutr   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$ )Nr7   r   r   r8   rs   r:   )ptrainingr!   )r   num_key_value_groupsr+   r   r   rG   r   
functionalsoftmaxr<   r;   r:   r   r  
contiguous)r   r   r   r   r   r   r   r   r   r   attn_weightscausal_maskr   s                r3   eager_attention_forwardr
  8  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$$r5   c                   :  ^  \ rS rSrSrS\S\4U 4S jjr\" SSSS	9  SS
\	R                  S\\	R                  \	R                  4   S\\	R                     S\\   S\\	R                     S\\   S\\	R                  \\	R                     4   4S jj5       rSrU =r$ )MiniMaxAttentioniR  z=Multi-headed attention from 'Attention Is All You Need' paperr   r^   c                   > [         TU ]  5         Xl        X l        [	        USS 5      =(       d    UR
                  UR                  -  U l        UR                  UR                  -  U l	        U R                  S-  U l
        UR                  U l        SU l        [        R                  " UR
                  UR                  U R                  -  SS9U l        [        R                  " UR
                  UR                  U R                  -  SS9U l        [        R                  " UR
                  UR                  U R                  -  SS9U l        [        R                  " UR                  U R                  -  UR
                  SS9U l        g )Nr   g      TFr   )r(   r)   r   r^   r   r0   r   r   r   r  r   attention_dropout	is_causalr   r   q_projk_projv_projo_projr/   r   r^   r2   s      r3   r)   MiniMaxAttention.__init__U  s.   "
D9mV=O=OSYSmSm=m$*$>$>&B\B\$\!}}d*!'!9!9ii 2 2F4N4NQUQ^Q^4^ejkii 2 2F4N4NQUQ^Q^4^ejkii 2 2F4N4NQUQ^Q^4^ejkii : :T]] JFL^L^ejkr5   r   r   r   r   r@   r   r   r   r   r   c           
      `   UR                   S S n/ UQSPU R                  P7nU R                  U5      R                  U5      R	                  SS5      n	U R                  U5      R                  U5      R	                  SS5      n
U R                  U5      R                  U5      R	                  SS5      nUu  p[        XX5      u  pUb$  XUS.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                   [#        U R                  SS 5      S.UD6u  nnUR$                  " / UQSP76 R'                  5       nU R)                  U5      nUU4$ )	Nr8   r!   r7   )r   r   r   eager        sliding_window)r   r   r  )rG   r   r  viewr   r  r  r   updater^   r
  r   _attn_implementationr   r  r  r   r   r   r  r  )r/   r@   r   r   r   r   r   input_shapehidden_shaper   r   r   r   r   cache_kwargsattention_interfacer   r  s                     r3   rC   MiniMaxAttention.forwardc  s    $))#2.88b8$--8{{=166|DNNqRST[[/44\BLLQPQR
{{=166|DNNqRST&#7RU#[ &#&nUL'6'='=jX\XfXfht'u$J(?;;++w6"9$++:Z:Z"[$7
%
  $}}C$2H2HLL"4;;0@$G
%
 
%
!\ "));;;;FFHkk+.L((r5   )r  r   r   r  r  r^   r  r  r  r   r  r   )rJ   rK   rL   rM   __doc__r"   r   r)   r   r+   r   rF   r   r	   r   r   r   rC   rN   rO   rP   s   @r3   r  r  R  s    Gl} l l %0A6R ,059*)||*) #5<<#=>*) !.	*)
 "%*) !!1!12*) -.*) 
u||Xell33	4*) S*)r5   r  c                   6   ^  \ rS rSrS\4U 4S jjrS rSrU =r$ )MiniMaxBlockSparseTop2MLPi  r   c                   > [         TU ]  5         UR                  U l        UR                  U l        [        R                  " U R
                  U R                  SS9U l        [        R                  " U R                  U R
                  SS9U l	        [        R                  " U R
                  U R                  SS9U l
        [        UR                     U l        g NFr   )r(   r)   intermediate_sizeffn_dimr0   
hidden_dimr   r   w1w2w3r   r   r   r/   r   r2   s     r3   r)   "MiniMaxBlockSparseTop2MLP.__init__  s    // ,,))DOOT\\F))DLL$//F))DOOT\\FV../r5   c                     U R                  U R                  U5      5      U R                  U5      -  nU R                  U5      nU$ rU   )r   r*  r,  r+  )r/   r@   current_hidden_statess      r3   rC   !MiniMaxBlockSparseTop2MLP.forward  s>     $DGGM,B CdggmF\ \ $(= >$$r5   )r   r(  r)  r*  r+  r,  )	rJ   rK   rL   rM   r"   r)   rC   rN   rO   rP   s   @r3   r$  r$    s    	0} 	0% %r5   r$  c                   f   ^  \ rS rSrSrU 4S jrS\R                  S\R                  4S jrSr	U =r
$ )MiniMaxSparseMoeBlocki  a  
This implementation is
strictly equivalent to standard MoE with full capacity (no
dropped tokens). It's faster since it formulates MoE operations
in terms of block-sparse operations to accommodate imbalanced
assignments of tokens to experts, whereas standard MoE either
(1) drop tokens at the cost of reduced performance or (2) set
capacity factor to number of experts and thus waste computation
and memory on padding.
c                   > [         TU ]  5         UR                  U l        UR                  U l        UR                  U l        UR                  U l	        [        R                  " U R                  U R                  SS9U l        [        R                  " [        U R                  5       Vs/ s H  n[        U5      PM     sn5      U l        UR"                  U l        g s  snf r&  )r(   r)   r0   r)  r'  r(  num_local_expertsnum_expertsnum_experts_per_toktop_kr   r   gate
ModuleListr[   r$  expertsrouter_jitter_noisejitter_noise)r/   r   r_   r2   s      r3   r)   MiniMaxSparseMoeBlock.__init__  s     ,,//!33//
 IIdoot/?/?eL	}}QVW[WgWgQh%iQhA&?&GQh%ij #66 &js   *Cr@   r   c                    UR                   u  p#nU R                  (       aS  U R                  S:  aC  U[        R                  " U5      R                  SU R                  -
  SU R                  -   5      -  nUR                  SU5      nU R                  U5      n[        R                  " US[        R                  S9n[        R                  " X`R                  SS9u  pgXfR                  SSS9-  nUR                  UR                  5      n[        R                   " X#-  U4UR                  UR"                  S	9n[        R$                  R&                  R)                  XpR*                  S
9R-                  SSS5      n	[        R.                  " U	R                  SS9S5      R1                  5       n
U
 H  nU R2                  U   n[        R4                  " X   R7                  S5      5      u  pUSU4   R9                  SU5      nU" U5      XnUS4   -  nUR;                  SUUR                  UR                  5      5        M     UR9                  X#U5      nX4$ ) r   g      ?r8   r!   r  rr   T)rs   r9   )r:   device)num_classesr7   )r8   r   N)rG   r  r=  r+   
empty_likeuniform_r  r9  r   r  r   topkr8  sumr;   r:   r   rA  r   r  one_hotr6  permutegreaternonzeror;  r   squeezer   
index_add_)r/   r@   r   sequence_lengthr)  router_logitsrouting_weightsselected_expertsfinal_hidden_statesexpert_mask
expert_hit
expert_idxexpert_layeridxtop_xcurrent_stater0  s                    r3   rC   MiniMaxSparseMoeBlock.forward  s   2?2E2E/
Z==T..2U--m<EEcDL]L]F]_beievev_vwwM%**2z:		-0))MqL,1JJ

XZ,[)..2t.DD),,]-@-@A#kk):6m>Q>QZgZnZn
 hh))112BP`P`1aiijkmnpqr]];??x?#@!DLLN
$J<<
3L[%<%D%DQ%GHJC *$+6>>r:NM$0$?/Y\^bRbBc$c!  **1e5J5M5MmNaNa5bc % 299*Wab"11r5   )r;  r(  r9  r)  r=  r6  r8  )rJ   rK   rL   rM   r"  r)   r+   r   rC   rN   rO   rP   s   @r3   r3  r3    s-    	7%2U\\ %2ell %2 %2r5   r3  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                  \R                  4   S\\R                     S\\R                     S\\   S\\   S\\   S\\   S\\R                     S\\   S\
\R"                  \\
\R"                  \R"                  4      4   4S jj5       rSrU =r$ )MiniMaxDecoderLayeri  r   r^   c                 r  > [         TU ]  5         UR                  U l        [        X5      U l        [        U5      U l        [        UR                  UR                  S9U l	        [        UR                  UR                  S9U l
        X l        UR                  U   U l        UR                  U l        UR                  U l        U R                  S:X  a3  [!        X5      U l        UR"                  U l        UR&                  U l        g [        X5      U l        UR*                  U l        UR,                  U l        g )Nr1   linear_attention)r(   r)   r0   r  	self_attnr3  block_sparse_moer%   rms_norm_epsinput_layernormpost_attention_layernormr^   layer_types
layer_typemlp_alpha_factormlp_beta_factorr   linear_attn_alpha_factorattn_alpha_factorlinear_attn_beta_factorattn_beta_factorfull_attn_alpha_factorfull_attn_beta_factorr  s      r3   r)   MiniMaxDecoderLayer.__init__  s    !--)&< 5f =-f.@.@fFYFYZ(6v7I7IvObOb(c%" ,,Y7 & 7 7%55??006vIDN%+%D%DD"$*$B$BD!-f@DN%+%B%BD"$*$@$@D!r5   r   r   r   r   r@   r   r   r   output_attentionsoutput_router_logits	use_cacher   r   r   c
                 &   U R                  U5      nUnU R                  " SUUUUUUUU	S.U
D6u  pXR                  -  XR                  -  -   nU R	                  U5      nUnU R                  U5      u  pXR                  -  XR                  -  -   nU$ )a  
Args:
    hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
    position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`):
        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.
    attention_mask (`torch.Tensor`, *optional*): attention mask of size
        `(batch, sequence_length)` where padding elements are indicated by 0.
    past_key_values (`Cache`, *optional*): cached past key and value projection states
    output_attentions (`bool`, *optional*):
        Whether or not to return the attentions tensors of all attention layers. See `attentions` under
        returned tensors for more detail.
    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.
    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`).
    cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
        Indices depicting the position of the input sequence tokens in the sequence.
    kwargs (`dict`, *optional*):
        Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
        into the model
)r@   r   r   r   r   ro  rq  r    )rb  r_  ri  rk  rc  r`  rf  rg  )r/   r@   r   r   r   r   ro  rp  rq  r   r   residualr_   s                r3   rC   MiniMaxDecoderLayer.forward  s    N ,,];   >> 

' 3)%+/)

 

 !#9#99MLaLa<aa 55mD 00? #8#88=K_K_;__r5   )ri  rk  r`  r0   rb  r^   re  rf  rg  rc  r_  )NNNFFFN)rJ   rK   rL   rM   r"   r   r)   r   r+   r   rF   r   r   r	   r   r   r   FloatTensorrC   rN   rO   rP   s   @r3   r[  r[    s2   A} A A0 %0A6R
 2637+/,1/4$)59=||= #5<<#=>= !.	=
 u//0= "%= $D>= 'tn= D>= !!1!12= -.= 
u  (51B1BEDUDU1U+V"WW	X= S=r5   r[  c                   b    \ rS rSr% \\S'   SrSrS/rS/r	Sr
SrSrSrSr\" \SS	9\\\/S
.rSrg)MiniMaxPreTrainedModeli@  r   modelTr[  r   Fr!   )index)rN  r@   
attentionsrs  N)rJ   rK   rL   rM   r"   __annotations__base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraph_supports_attention_backendr   r3  r[  r  r   _can_record_outputsrN   rs  r5   r3   rx  rx  @  sb    &*#./#4"5N""&'(=QG,')BCr5   rx  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$ )MiniMaxRotaryEmbeddingiS  inv_freqr   c                   > [         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defaultr  F)
persistent)r(   r)   hasattr
isinstancer  dictgetr  max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr   r   rope_init_fnattention_scalingr   r  original_inv_freq)r/   r   rA  r  r2   s       r3   r)   MiniMaxRotaryEmbedding.__init__V  s    6>**z&:M:Mt/T/T#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q((ZeD!%r5   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   r8   r!   mpscpuF)device_typeenabledr7   rr   r   )r  r   r   rG   r;   rA  r  r  strr+   autocastr   r   r   r  r   r:   )
r/   r   r   inv_freq_expandedposition_ids_expandedr  freqsembr   r   s
             r3   rC   MiniMaxRotaryEmbedding.forwardg  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  r   r  r  r  r  r  rU   )rJ   rK   rL   rM   r+   r   r|  r"   r)   no_gradr   rC   rN   rO   rP   s   @r3   r  r  S  s@    ll/} / /" ]]_<  <r5   r  c                   $  ^  \ rS rSrS\4U 4S jjr\" 5               SS\\R                     S\\R                     S\\R                     S\\   S\\R                     S	\\   S
\\   S\\R                     S\\   S\4S jj5       rSrU =r$ )MiniMaxModeliw  r   c           	        > [         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        [#        US9U l        SU l        U R)                  5         g s  snf )Nr]  )r   F)r(   r)   pad_token_idpadding_idx
vocab_sizer   	Embeddingr0   embed_tokensr:  r[   r   r[  ru   r%   ra  r   r  
rotary_embgradient_checkpointing	post_initr  s      r3   r)   MiniMaxModel.__init__y  s     !.. ++LL):):F<N<NPTP`P`ammEJ6KcKcEdeEd	 3Ede
 #6#5#56;N;NO	0?&+# 	 fs   C?	input_idsr   r   r   inputs_embedsrq  ro  r   r   r   c	                    US L US L-  (       a  [        S5      eU(       a  Uc  [        5       nO4U(       a-  [        U[        5      (       d  [        S[        U5       S35      eUc  U R	                  U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                  R                  c  [        O[        nU" U R                  UUUUUS9nUnU R                  X5      nU R                    H(  nUR"                  S:X  a  UnOUnU" U4UUUUUUS	.U	D6nM*     U R%                  U5      n['        UUS
9$ )Nz:You must specify exactly one of input_ids or inputs_embedszSMiniMax uses cache of its own and is not compatible with `past_key_values` of type .r   r!   )rA  )r   input_embedsr   r   r   r   full_attention)r   r   r   r   rq  r   )last_hidden_stater   )
ValueErrorrR   r  r  r  get_seq_lengthr+   r   rG   rA  r   r   r  r   r   r  ru   re  r   r   )r/   r  r   r   r   r  rq  ro  r   r   past_seen_tokensmask_functionr	  r@   r   decoder_layerinput_attention_masks                    r3   rC   MiniMaxModel.forward  s    -t";<YZZ0*nOz/<HHefjkzf{e||}~    --i8M!CRC^==?de"\\ ]5H5H5K"KTaThThN )33A6L.2kk.H.H.P*Vw#;;&))+%
 & #oomJ![[M''+;;'2$ (6$)	$73) /#-	 	M )$ 		-0%++
 	
r5   )r  r  ru   r   r  r  r  )NNNNNNNN)rJ   rK   rL   rM   r"   r)   r    r   r+   r   r   rR   rv  r   r   r   r   rC   rN   rO   rP   s   @r3   r  r  w  s    }    1515372659$(,059G
E,,-G
 !.G
 u//0	G

 ",/G
   1 12G
 D>G
 $D>G
 !!1!12G
 +,G
 
 G
 G
r5   r  gate_logitsr6  c                    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 )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   rr   r8   )r  rF   rA  r+   r   r;   r   r  r  rE  rG  r>   r   rG   r   r   rF  r   )r  r6  r8  r   compute_device
layer_gateconcatenated_gate_logitsrO  r_   rP  rR  tokens_per_expertrouter_prob_per_expertr   rM  r   expert_attention_mask router_per_expert_attention_maskoverall_losss                      r3   load_balancing_loss_funcr    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                   ~  ^  \ rS rSrS/rSS0rSS/S/40rU 4S jr\\	          SS\
\R                     S	\
\R                     S
\
\R                     S\
\   S\
\R                     S\
\R                     S\
\   S\
\   S\
\R                     S\\\R                  4   S\\   S\4S jj5       5       rSrU =r$ )MiniMaxForCausalLMi&  zlm_head.weightlm_headcolwise_repr@   logitsc                 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 r&  )r(   r)   r  ry  r  r   r   r0   r  router_aux_loss_coefr5  r6  r7  r  r-  s     r3   r)   MiniMaxForCausalLM.__init__,  s     !&)
 ++yy!3!3V5F5FUS$*$?$?!!33#)#=#=  	r5   r  r   r   r   r  labelsrq  rp  r   logits_to_keepr   r   c                 ~   Ub  UOU R                   R                  nU R                  " SUUUUUUUU	S.UD6nUR                  n[	        U
[
        5      (       a  [        U
* S5      OU
nU R                  USS2USS24   5      nSnUb  U R                  " XU R                  40 UD6nSnU(       aZ  [        UR                  U R                  U R                  U5      nUb+  UU R                  UR                  UR                   5      -  -  n[#        UUUUR$                  UR&                  UR(                  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, MiniMaxForCausalLM

>>> model = MiniMaxForCausalLM.from_pretrained("MiniMaxAI/MiniMax-Text-01-hf")
>>> tokenizer = AutoTokenizer.from_pretrained("MiniMaxAI/MiniMax-Text-01-hf")

>>> 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   r   r  rq  rp  r   )lossaux_lossr  r   r@   r{  rN  rs  )r   rp  ry  r  r  r   slicer  loss_functionr  r  rN  r6  r7  r  r;   rA  r   r   r@   r{  )r/   r  r   r   r   r  r  rq  rp  r   r  r   outputsr@   slice_indicesr  r  r  s                     r3   rC   MiniMaxForCausalLM.forward8  sU   P %9$D $++JjJj 	
 +/** 
+
)%+'!5)
+
 
+
  118B>SV8W8W~ot4]kmA}a,?@A%%fdooPPD/%%  ((	H !11HKK4LLL(#33!//))!//
 	
r5   )r  ry  r6  r7  r  r  )
NNNNNNNNNr   )rJ   rK   rL   rM   _tied_weights_keys_tp_plan_pp_planr)   r   r   r   r+   r   r   r	   rv  r   r   r   r   r   r   rC   rN   rO   rP   s   @r3   r  r  &  sO   *+=)H_-z:;H
  151537+/59-1$(/35934R
E,,-R
 !.R
 u//0	R

 "%R
   1 12R
 ))*R
 D>R
 'tnR
 !!1!12R
 c5<</0R
 +,R
 
#R
  R
r5   r  c                       \ rS rSrSrg) MiniMaxForSequenceClassificationi  rs  NrJ   rK   rL   rM   rN   rs  r5   r3   r  r        r5   r  c                       \ rS rSrSrg)MiniMaxForTokenClassificationi  rs  Nr  rs  r5   r3   r  r    r  r5   r  c                       \ rS rSrSrg)MiniMaxForQuestionAnsweringi  rs  Nr  rs  r5   r3   r  r    r  r5   r  )rx  r  r  r  r  r  rZ   )r  )Nr7   N)Ktypingr   r   r   r+   torch.nn.functionalr   r  r   activationsr   cache_utilsr	   r
   
generationr   integrationsr   masking_utilsr   r   modeling_flash_attention_utilsr   modeling_layersr   r   r   r   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   utils.deprecationr   utils.genericr   r    configuration_minimaxr"   Moduler%   rR   r   r   r   r   r   r   r   r
  r  r$  r3  r[  rx  r  r  rF   r  r  r  r  r  __all__rs  r5   r3   <module>r     s  . - ,     ! . ) 7 R B  R K F & I I 0 ? 0 Y'JRYY J (J(+I< +I\Q/		 Q/h(6	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 U\\*% % % '(%4<)ryy <)~%		 %$@2BII @2FW4 Wt _  $!<RYY !<H Y
) Y
 Y
| "&
-1	O&u||U5<<%8$>?O&#O& U\\*	O&
 5<<O&d e
/ e
 e
P	'GI_ 		$ACY 		"=?U 	r5   