
    <h                        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  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/J0r0  \" S5       " S S\Rb                  5      5       r2 " S S\5      r3 " S S\Rb                  5      r4S r5SES jr6S\Rn                  S\8S \Rn                  4S! jr9 SFS"\Rb                  S#\Rn                  S$\Rn                  S%\Rn                  S&\\Rn                     S'\:S(\:S)\(\*   4S* jjr; " S+ S,\Rb                  5      r< " S- S.\Rb                  5      r= " S/ S0\Rb                  5      r> " S1 S2\5      r?\+ " S3 S4\&5      5       r@ " S5 S6\Rb                  5      rA\+ " S7 S8\@5      5       rB   SGS9\\Rn                  \C\Rn                     S4   S:\\8   S&\\Rn                     S \\Rn                  \84   4S; jjrD\+ " S< S=\@\5      5       rE " S> S?\\@5      rF " S@ SA\\@5      rG " SB SC\\@5      rH/ SDQrIg)H    )CallableOptionalUnionN)nn)check_model_inputs   )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)OutputRecorder   )MiniMaxConfigRMSNormc                   8   ^  \ rS rSrSU 4S jjrS rS rSrU =r$ )MiniMaxRMSNorm4   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      d/var/www/html/shao/venv/lib/python3.13/site-packages/transformers/models/minimax/modeling_minimax.pyr(   MiniMaxRMSNorm.__init__6   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       r2   forwardMiniMaxRMSNorm.forward>   sw    #))%((7 $$Q',,R,>%H?T?T4T(UU{{]--k:::r4   c                 ^    [        U R                  R                  5       SU R                   3$ )Nz, eps=)tupler,   shaper-   r.   s    r2   
extra_reprMiniMaxRMSNorm.extra_reprE   s*    ))*+6$2G2G1HIIr4   )r-   r,   )gư>)	__name__
__module____qualname____firstlineno__r(   rB   rH   __static_attributes____classcell__r1   s   @r2   r$   r$   4   s    $;J Jr4   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$ )MiniMaxCacheI   c                 0   > [         TU ]  5         / U l        g N)r'   r(   linear_cacher.   r1   s    r2   r(   MiniMaxCache.__init__J   s    02r4   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       r2   set_linear_cacheMiniMaxCache.set_linear_cacheN   sD    s4,,-y1}=A$$R( >'3)$r4   r^   c                 @    U[        U 5      :  a  U R                  U   $ g rU   )r\   rV   r.   r^   s     r2   get_linear_cacheMiniMaxCache.get_linear_cacheT   s"    s4y $$Y//r4   c                 Z   > [        [        TU ]	  5       [        U R                  5      5      $ rU   )maxr'   __len__r\   rV   rW   s    r2   rh   MiniMaxCache.__len__Y   s"    57?$c$*;*;&<==r4   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^   r1   s     r2   rk   MiniMaxCache.__getitem__\   sM    s4,,--$2C2CI2NRT2T%%i022w"9--r4   c              #   N   #    [        [        U 5      5       H	  nX   v   M     g 7frU   )r[   r\   rc   s     r2   __iter__MiniMaxCache.__iter__a   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      r2   rv   $MiniMaxCache.batch_repeat_interleavee   sl    s4y)I  +r1/3/@/@/K/]/]^ekl/]/m!!),I&>>wG	 *r4   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      r2   rz   !MiniMaxCache.batch_select_indicesl   sd    s4y)I  +r1/3/@/@/KGUXL/Y!!),I&;;GD	 *r4   
max_lengthc                     [        S5      e)Nz*MiniMaxCache doesnot support `crop` method)RuntimeError)r.   r|   s     r2   cropMiniMaxCache.crops   s    GHHr4   )rV   )rJ   rK   rL   rM   r(   r`   intrd   rh   rk   rn   rv   r*   Tensorrz   r   rN   rO   rP   s   @r2   rR   rR   I   sc    34# 
>.S .
"Hs HEELL EIs I Ir4   rR   c                   N  ^  \ rS rSrS\S\4U 4S jjrS rS r  SS\	R                  S\\	R                  \	R                  4   S	\\	R                     S
\\   S\\	R                     S\\   S\\	R                  \\	R                     \\\	R                        4   4S jjrSrU =r$ )MiniMaxLightningAttentionw   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^   getattrr/   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   r1   s          r2   r(   "MiniMaxLightningAttention.__init__x   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-~>r4   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    r6      gh㈵>)r   r*   aranger^   r   )r.   baseexponentfactorrates        r2   r   (MiniMaxLightningAttention.get_slope_rate   s    A!d66678<< 8 89A=T^^t'='='AD'HIIDP~}AtTM"r4   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         r2   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5r4   r?   position_embeddingsattention_maskpast_key_value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   r6   r9   r7   r   )!rF   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_lenr/   
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#                                      r2   rB   !MiniMaxLightningAttention.forward   s    ,9+>+>(
[/!3G
[[}!=>
''
T=U=UWX[_[h[hWhi
16Z\]1^.,#--a3))!Q/
#--a3 "%!/!@!@!P%!&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 %++DNN<NO...r4   )
r   r   r   r^   r   r   r   r   r   r   NN)rJ   rK   rL   rM   r!   r   r(   r   r   r*   r   rE   r   r
   
LongTensorr   r   rB   rN   rO   rP   s   @r2   r   r   w   s    ?} ? ?,	6& +/59`/||`/ #5<<#=>`/ !.	`/
 !`/ !!1!12`/ -.`/ 
u||Xell3XeELL>Q5RR	S`/ `/r4   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..Nr7   r6   rr   )rF   r*   r   )xx1x2s      r2   rotate_halfr   
  sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r4   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           r2   apply_rotary_pos_embr     sS    ( --
&C
--
&Cw;q>C/0Gw;q>C/0Gr4   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)rF   expandr   )r?   r   batchnum_key_value_headsslenr   s         r2   	repeat_kvr   ,  s_    
 2?1D1D.Ez!!Qa"23::5W\dlmM  e(CTTTr4   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$ )Nr6   r   r   r7   rs   r9   )ptrainingr    )r   num_key_value_groupsr*   r   r   rF   r   
functionalsoftmaxr;   r:   r9   r   r   
contiguous)r   r   r   r   r   r   r   r   r   r   attn_weightscausal_maskr   s                r2   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$$r4   c                   F  ^  \ rS rSrSrS\S\4U 4S jjr  SS\R                  S\
\R                  \R                  4   S\\R                     S	\\   S
\\R                     S\\   S\
\R                  \\R                     \\
\R                        4   4S jj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   r/   r   r   r   r   r   attention_dropout	is_causalr   r   q_projk_projv_projo_projr.   r   r^   r1   s      r2   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r4   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$ )	Nr7   r    r6   )r   r   r   eager        sliding_window)r   r   r  )rF   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                     r2   rB   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'5'<'<ZW[WeWegs't$J(?;;++w6"9$++:Z:Z"[$7
%
  $}}C$2H2HLL"4;;0@$G
%
 
%
!\ "));;;;FFHkk+.L((r4   )r	  r   r   r
  r  r^   r   r  r  r   r  r   )rJ   rK   rL   rM   __doc__r!   r   r(   r*   r   rE   r   r
   r   r   r   rB   rN   rO   rP   s   @r2   r  r  R  s    Gl} l l& +/59*)||*) #5<<#=>*) !.	*)
 !*) !!1!12*) -.*) 
u||Xell3XeELL>Q5RR	S*) *)r4   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_dimr/   
hidden_dimr   r   w1w2w3r	   r   r   r.   r   r1   s     r2   r(   "MiniMaxBlockSparseTop2MLP.__init__  s    // ,,))DOOT\\F))DLL$//F))DOOT\\FV../r4   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      r2   rB   !MiniMaxBlockSparseTop2MLP.forward  s>     $DGGM,B CdggmF\ \ $(= >$$r4   )r   r#  r$  r%  r&  r'  )	rJ   rK   rL   rM   r!   r(   rB   rN   rO   rP   s   @r2   r  r    s    	0} 	0% %r4   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(   r/   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_   r1   s      r2   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      ?r7   r    r   rr   T)rs   r8   )r9   device)num_classesr6   )r7   r   N)rF   r   r8  r*   
empty_likeuniform_r  r4  r   r  r   topkr3  sumr:   r9   r   r<  r   r   one_hotr1  permutegreaternonzeror6  r   squeezer   
index_add_)r.   r?   r   sequence_lengthr$  router_logitsrouting_weightsselected_expertsfinal_hidden_statesexpert_maskexpert_hitted
expert_idxexpert_layeridxtop_xcurrent_stater+  s                    r2   rB   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koo(o&CQGOOQ'J<<
3L[%<%D%DQ%GHJC *$+6>>r:NM$0$?/Y\^bRbBc$c!  **1e5J5M5MmNaNa5bc ( 299*Wab"11r4   )r6  r#  r4  r$  r8  r1  r3  )rJ   rK   rL   rM   r  r(   r*   r   rB   rN   rO   rP   s   @r2   r.  r.    s-    	7%2U\\ %2ell %2 %2r4   r.  c                     ^  \ rS rSrS\S\4U 4S jjr       SS\R                  S\	\R                  \R                  4   S\
\R                     S\
\R                     S	\
\	\R                        S
\
\   S\
\   S\
\   S\
\R                     S\\   S\	\R                  \
\	\R                  \R                  4      4   4S jj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r0   linear_attention)r'   r(   r/   r  	self_attnr.  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      r2   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!r4   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_value (`Tuple(torch.FloatTensor)`, *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   rj  rl  r    )r]  rZ  rd  rf  r^  r[  ra  rb  )r.   r?   r   r   r   r   rj  rk  rl  r   r   residualr_   s                r2   rB   MiniMaxDecoderLayer.forward  s    L ,,];   >> 

' 3)%)/)

 

 !#9#99MLaLa<aa 55mD 00? #8#88=K_K_;__r4   )rd  rf  r[  r/   r]  r^   r`  ra  rb  r^  rZ  )NNNFFFN)rJ   rK   rL   rM   r!   r   r(   r*   r   rE   r   r   r   r   r   FloatTensorrB   rN   rO   rP   s   @r2   rV  rV    s&   A} A A8 26378<,1/4$)59=||= #5<<#=>= !.	=
 u//0= !u||!45= $D>= 'tn= D>= !!1!12= -.= 
u  (51B1BEDUDU1U+V"WW	X= =r4   rV  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   modelTrV  past_key_valuesFr    )index)rI  r?   
attentionsrn  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   r.  rV  r  r   _can_record_outputsrN   rn  r4   r2   rs  rs  >  sb    &*#./#4"5N""&'(=QG,')BCr4   rs  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$ )MiniMaxRotaryEmbeddingiQ  r   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defaultinv_freqF)
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   r<  r  r1   s       r2   r(   MiniMaxRotaryEmbedding.__init__R  s    6>**z&:M:Mt/T/T#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q((ZeD!%r4   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   r7   r    mpscpuF)device_typeenabledr6   rr   r   )r  r   r   rF   r:   r<  r  r  strr*   autocastr   r   r   r  r   r9   )
r.   r   r   inv_freq_expandedposition_ids_expandedr  freqsembr   r   s
             r2   rB   MiniMaxRotaryEmbedding.forwardc  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*   no_gradr   rB   rN   rO   rP   s   @r2   r  r  Q  s6    /} / /" ]]_<  <r4   r  c                     ^  \ rS rSrS\4U 4S jjr\\        SS\R                  S\
\R                     S\
\R                     S\
\   S\
\R                     S	\
\   S
\
\   S\
\R                     S\\   S\4S jj5       5       rSrU =r$ )MiniMaxModelis  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 )NrX  )r   F)r'   r(   pad_token_idpadding_idx
vocab_sizer   	Embeddingr/   embed_tokensr5  r[   r   rV  ru   r$   r\  r   r  
rotary_embgradient_checkpointing	post_initr  s      r2   r(   MiniMaxModel.__init__u  s     !.. ++LL):):F<N<NPTP`P`ammEJ6KcKcEdeEd	 3Ede
 #6#5#56;N;NO	0?&+# 	 fs   C>	input_idsr   r   ru  inputs_embedsrl  rj  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    )r<  )r   input_embedsr   r   ru  r   full_attention)r   r   r   r   rl  r   )last_hidden_stateru  )
ValueErrorrR   r  r  r  get_seq_lengthr*   r   rF   r<  r   r   r  r   r   r  ru   r`  r   r   )r.   r  r   r   ru  r  rl  rj  r   r   past_seen_tokensmask_functionr  r?   r   decoder_layerinput_attention_masks                    r2   rB   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%++
 	
r4   )r  r  ru   r   r  r  r  )NNNNNNNN)rJ   rK   rL   rM   r!   r(   r   r   r*   r   r   r   rR   rq  r   r   r   r   rB   rN   rO   rP   s   @r2   r  r  s  s    }    '+15372659$(,059G
##G
 !.G
 u//0	G

 ",/G
   1 12G
 D>G
 $D>G
 !!1!12G
 +,G
 
 G
  G
r4   r  gate_logitsr1  c                    U b  [        U [        5      (       d  g[        U [        5      (       aB  U S   R                  n[        R                  " U  Vs/ sH  oUR                  U5      PM     snSS9n[        R                  R                  R                  WSS9n[        R                  " XrSS9u  p[        R                  R                  R                  X5      n
Uc:  [        R                  " U
R                  5       SS9n[        R                  " USS9nGOUR                  u  pUR                  S   X-  -  nUSSS2SS2SS4   R                  XXU45      R                  SX!5      R                  W5      n[        R                   " U
R                  5       U-  SS9[        R                   " USS9-  nUSSS2SS2S4   R                  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   r7   )r  rE   r<  r*   r   r:   r   r   r  r@  rB  r=   r   rF   r   r   rA  r   )r  r1  r3  r   compute_device
layer_gateconcatenated_gate_logitsrJ  r_   rK  rM  tokens_per_expertrouter_prob_per_expertr   rH  r   expert_attention_mask router_per_expert_attention_maskoverall_losss                      r2   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 rS	 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  rt  r  r   r   r/   r  router_aux_loss_coefr0  r1  r2  r  r(  s     r2   r(   MiniMaxForCausalLM.__init__)  s     !&)
 ++yy!3!3V5F5FUS$*$?$?!!33#)#=#=  	r4   c                     Xl         g rU   rt  )r.   decoders     r2   set_decoderMiniMaxForCausalLM.set_decoder5  s    
r4   c                     U R                   $ rU   r  rG   s    r2   get_decoderMiniMaxForCausalLM.get_decoder8  s    zzr4   r  r   r   ru  r  labelsrl  rk  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   ru  r  rl  rk  r   )lossaux_lossr  ru  r?   rw  rI  rn  )r   rk  rt  r  r  r   slicer  loss_functionr  r  rI  r1  r2  r  r:   r<  r   ru  r?   rw  )r.   r  r   r   ru  r  r  rl  rk  r   r  r   outputsr?   slice_indicesr  r  r  s                     r2   rB   MiniMaxForCausalLM.forward;  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!//))!//
 	
r4   )r  rt  r1  r2  r  r  )
NNNNNNNNNr   )rJ   rK   rL   rM   _tied_weights_keys_tp_plan_pp_planr(   r  r  r   r   r   r*   r   r   r
   rq  r   r   r   r   r   r   rB   rN   rO   rP   s   @r2   r  r  #  sY   *+=)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
r4   r  c                       \ rS rSrSrg) MiniMaxForSequenceClassificationi  rn  NrJ   rK   rL   rM   rN   rn  r4   r2   r  r        r4   r  c                       \ rS rSrSrg)MiniMaxForTokenClassificationi  rn  Nr  rn  r4   r2   r  r    r  r4   r  c                       \ rS rSrSrg)MiniMaxForQuestionAnsweringi  rn  Nr  rn  r4   r2   r  r    r  r4   r  )rs  r  r  r  r  r  rZ   )r  )Nr6   N)Jtypingr   r   r   r*   torch.nn.functionalr   r   r   transformers.utils.genericr   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.genericr   configuration_minimaxr!   Moduler$   rR   r   r   r   r   r   r   r   r  r  r  r.  rV  rs  r  r  rE   r  r  r  r  r  __all__rn  r4   r2   <module>r     s  . - ,     9 ! . ) 7 R B  R K F & I I + 0 Y'JRYY J (J(+I< +I\P/		 P/f(6	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 U\\*% % % '(%4;)ryy ;)|%		 %$@2BII @2FV4 Vr _  $<RYY <D Z
) Z
 Z
~ "&
-1	O&u||U5<<%8$>?O&#O& U\\*	O&
 5<<O&d k
/ k
 k
\	'GI_ 		$ACY 		"=?U 	r4   