
    Z j                        S SK Jr  S SK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Jr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 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/J0r0  SSK1J2r2J3r3  SSK4J5r5J6r6  SSK7J8r8  \" S5       " S S\Rr                  5      5       r: " S S\5      r; " S S\Rr                  5      r< " S S\Rr                  5      r=S  r>\" S!5      SJS" j5       r?S#\R                  S$\AS%\R                  4S& jrB SKS'\Rr                  S(\R                  S)\R                  S*\R                  S+\R                  S-  S,\CS-\CS.\,\.   4S/ jjrD\" \?5       " S0 S1\Rr                  5      5       rE " S2 S3\Rr                  5      rF\ " S4 S5\Rr                  5      5       rG " S6 S7\Rr                  5      rH " S8 S9\!5      rI\/ " S: S;\*5      5       rJ\/ " S< S=\J5      5       rK   SLS>\R                  \L\R                     -  S-  S?\AS-  S+\R                  S-  S%\R                  \A-  4S@ jjrM\/ " SA SB\J\5      5       rN " SC SD\\J5      rO " SE SF\ \J5      rP " SG SH\\J5      rQ/ SIQrRg)M    )Callable)OptionalN)nn   )initialization)ACT2FN)CacheDynamicCache)GenerationMixin)use_experts_implementationuse_kernel_forward_from_hubuse_kernel_func_from_hubuse_kernelized_func)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)maybe_autocastmerge_with_config_defaults)OutputRecordercapture_outputs   )MiniMaxConfigRMSNormc                   x   ^  \ rS rSrS
S\SS4U 4S jjjrS\R                  S\R                  4S jrS r	S	r
U =r$ )MiniMaxRMSNorm9   epsreturnNc                    > [         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_sizer+   	__class__s      }/root/GenerationalWealth/GenerationalWealth/venv/lib/python3.13/site-packages/transformers/models/minimax/modeling_minimax.pyr/   MiniMaxRMSNorm.__init__;   s/     	ll5::k#:; #    hidden_statesc                    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tor1   float32powmeanrsqrtr4   r3   )r5   r;   input_dtypevariances       r8   forwardMiniMaxRMSNorm.forwardC   sw    #))%((7 $$Q',,R,>%H?T?T4T(UU{{]--k:::r:   c                 ^    [        U R                  R                  5       SU R                   3$ )Nz, eps=)tupler3   shaper4   )r5   s    r8   
extra_reprMiniMaxRMSNorm.extra_reprJ   s*    ))*+6$2G2G1HIIr:   )r4   r3   )gư>)__name__
__module____qualname____firstlineno__floatr/   r1   TensorrH   rM   __static_attributes____classcell__r7   s   @r8   r)   r)   9   sB    $ $$ $ $;U\\ ;ell ;J Jr:   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S jr	S	\
R                  4S
 jrS\4S jrSrU =r$ )MiniMaxCacheN   c                 0   > [         TU ]  5         / U l        g N)r.   r/   linear_cacher5   r7   s    r8   r/   MiniMaxCache.__init__O   s    02r:   c                     [        [        U R                  5      US-   5       H  nU R                  R                  / 5        M      X R                  U'   g )Nr%   )rangelenr]   append)r5   	layer_idxr]   _s       r8   set_linear_cacheMiniMaxCache.set_linear_cacheS   sD    s4,,-y1}=A$$R( >'3)$r:   rd   c                 @    U[        U 5      :  a  U R                  U   $ g r\   )rb   r]   )r5   rd   s     r8   get_linear_cacheMiniMaxCache.get_linear_cacheY   s"    s4y $$Y//r:   c                 Z   > [        [        TU ]	  5       [        U R                  5      5      $ r\   )maxr.   __len__rb   r]   r^   s    r8   rm   MiniMaxCache.__len__^   s"    57?$c$*;*;&<==r:   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)ra   rb   r]   repeat_interleavelayersbatch_repeat_interleave)r5   ro   rd   s      r8   ru   $MiniMaxCache.batch_repeat_interleavea   sl    s4y)I  +r1/3/@/@/K/]/]^ekl/]/m!!),I&>>wG	 *r:   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.)ra   rb   r]   rt   batch_select_indices)r5   rw   rd   s      r8   ry   !MiniMaxCache.batch_select_indicesh   sd    s4y)I  +r1/3/@/@/KGUXL/Y!!),I&;;GD	 *r:   
max_lengthc                     [        S5      e)Nz*MiniMaxCache doesnot support `crop` method)RuntimeError)r5   r{   s     r8   cropMiniMaxCache.cropo   s    GHHr:   )r]   )rO   rP   rQ   rR   r/   rf   intri   rm   ru   r1   rT   ry   r~   rU   rV   rW   s   @r8   rY   rY   N   sR    34# 
>Hs HEELL EIs I Ir:   rY   c                   .  ^  \ 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\S-  S\\   S\\	R                  \	R                  S-  \\	R                     S-  4   4S jjrSrU =r$ )MiniMaxLightningAttentions   configrd   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/   rd   getattrr6   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)r5   r   rd   r   r   r   r   r7   s          r8   r/   "MiniMaxLightningAttention.__init__t   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-~>r:   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%   r=      gh㈵>)r   r1   arangerd   r   )r5   baseexponentfactorrates        r8   r   (MiniMaxLightningAttention.get_slope_rate   s    A!d66678<< 8 89A=T^^t'='='AD'HIIDP~}AtTM"r:   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)r1   r   r   expwhererS   )r5   r   block_size_ranger   r   r   s         r8   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5r:   Nr;   position_embeddingsattention_maskpast_key_valueskwargsr,   c                  	   UR                   u  pgnXpR                  -   S-
  U R                  -  n	U R                  U R                  U5      5      n
U
R	                  XgU 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                  " X`R
                  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	                  XgU 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        X4$ )	Nr%   r   rq   r=   r@   r>   r   )!rL   r   r   r   reshaper   r   r1   split	transposeri   rd   zerosrA   boolmasked_fill	unsqueezera   minr   r   r   r   r   matmulrc   catr   Fsigmoidr   r   rf   )"r5   r;   r   r   r   r   
batch_sizeseq_lenr6   
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"                                     r8   rH   !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..r:   )
r   r   r   rd   r   r   r   r   r   r   r\   )rO   rP   rQ   rR   r&   r   r/   r   r   r1   rT   rK   r	   r   r   rH   rU   rV   rW   s   @r8   r   r   s   s    ?} ? ?,	6& )-_/||_/ #5<<#=>_/ t+	_/
 _/ -._/ 
u||U\\D0%2E2LL	M_/ _/r:   r   c                      ^  \ rS rSr% \R
                  \S'   SS\4U 4S jjjr\	   SS\S-  S\
S   S\S-  S	\S
\4   4S jj5       r\R                  " 5       \S 5       5       rSrU =r$ )MiniMaxRotaryEmbeddingi  inv_freqNr   c                   > [         TU ]  5         UR                  U l        UR                  U l        Xl        U R
                  R                  S   U l        U R                  nU R                  S:w  a  [        U R                     nU" U R
                  U5      u  o@l
        U R                  SUSS9  U R                  SUR                  5       SS9  g )N	rope_typedefaultr   F)
persistentoriginal_inv_freq)r.   r/   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr   rope_parametersr   compute_default_rope_parametersr   attention_scalingr   clone)r5   r   devicerope_init_fnr   r7   s        r8   r/   MiniMaxRotaryEmbedding.__init__  s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L((ZeD0(..2BuUr:   r   ztorch.devicer   r,   ztorch.Tensorc           	         U R                   S   n[        U SS5      =(       d    U R                  U R                  -  nSnSU[        R
                  " SUS[        R                  S9R                  U[        R                  S9U-  -  -  nXe4$ )	aH  
Computes the inverse frequencies according to the original RoPE implementation
Args:
    config ([`~transformers.PreTrainedConfig`]):
        The model configuration.
    device (`torch.device`):
        The device to use for initialization of the inverse frequencies.
    seq_len (`int`, *optional*):
        The current sequence length. Unused for this type of RoPE.
Returns:
    Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
    post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).

rope_thetar   N      ?r   r=   r   )r   r@   )	r   r   r6   r   r1   r   int64rA   rS   )r   r   r   r   rr   attention_factorr   s          r8   r   6MiniMaxRotaryEmbedding.compute_default_rope_parameters  s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 ))r:   c                 L   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[        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=   rq   r   )r   rS   expandrL   rA   r   
isinstancetypestrr!   r   r1   r   cosr   sinr@   )
r5   xposition_idsinv_freq_expandedposition_ids_expandedr   freqsembr   r   s
             r8   rH   MiniMaxRotaryEmbedding.forward6  sN    !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\   )NNN)rO   rP   rQ   rR   r1   rT   __annotations__r&   r/   staticmethodr   r   rK   rS   r   no_gradr   rH   rU   rV   rW   s   @r8   r   r     s    llV} V V  '++/"*$*(* t* 
~u$	%	* *: ]]_<  <r:   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..Nr>   r=   rq   )rL   r1   r   )r   x1x2s      r8   rotate_halfr  F  sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r:   rotary_pos_embc                     UR                  U5      nUR                  U5      nX-  [        U 5      U-  -   nX-  [        U5      U-  -   nXV4$ )aI  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.
    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kr   r   unsqueeze_dimq_embedk_embeds          r8   apply_rotary_pos_embr  M  sS    & --
&C
--
&Cw;q>C/0Gw;q>C/0Gr:   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)rL   r   r   )r;   r  batchnum_key_value_headsslenr   s         r8   	repeat_kvr  g  s_    
 2?1D1D.Ez!!Qa"23::5W\dlmM  e(CTTTr:   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  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>   )rr   r@   )ptrainingr%   )r  num_key_value_groupsr1   r   r   r   
functionalsoftmaxrB   rA   r@   r  r  
contiguous)r  r  r  r  r   r  r  r   r   r   attn_weightsr   s               r8   eager_attention_forwardr%  s  s     3 ; ;<JU$?$?@L<<';';Aq'ABWLL!#4==((2U]](SVVW\WbWbcL==((6??([L,,|:K''1-88:K$$r:   c                     ^  \ 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
\S-  S\\   S\
\R                  \R                  S-  4   4S jjrSrU =r$ )MiniMaxAttentioni  z=Multi-headed attention from 'Attention Is All You Need' paperr   rd   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   rd   r   r6   r   r   r  r   r  attention_dropout	is_causalr   r   q_projk_projv_projo_projr5   r   rd   r7   s      r8   r/   MiniMaxAttention.__init__  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r:   Nr;   r   r   r   r   r,   c           
      4   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  UR                  XU R                  5      u  p[        R                  " U R                  R                  [        5      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  pUR&                  " / UQSP76 R)                  5       nU R+                  U5      nX4$ )Nr>   r%   r=           sliding_window)r  r  r3  )rL   r   r+  viewr   r,  r-  r  updaterd   r   get_interfacer   _attn_implementationr%  r  r)  r  r   r   r#  r.  )r5   r;   r   r   r   r   input_shapehidden_shaper   r   r   r   r   attention_interfacer   r$  s                   r8   rH   MiniMaxAttention.forward  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#[ &'6'='=jX\XfXf'g$J(?(M(MKK,,.E)
 %8
%
  $}}C$2H2HLL"4;;0@$G
%
 
%
! "));;;;FFHkk+.((r:   )r)  r   r   r*  r,  rd   r   r.  r+  r  r-  r\   )rO   rP   rQ   rR   __doc__r&   r   r/   r1   rT   rK   r	   r   r   rH   rU   rV   rW   s   @r8   r'  r'    s    Gl} l l& )-')||') #5<<#=>') t+	')
 ') -.') 
u||U\\D00	1') ')r:   r'  c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )MiniMaxTopKRouteri  c                   > [         TU ]  5         UR                  U l        UR                  U l        UR                  U l        [        R                  " [        R                  " U R
                  U R                  5      5      U l        g r\   )r.   r/   num_experts_per_toktop_knum_local_expertsnum_expertsr6   
hidden_dimr   r0   r1   emptyr3   r5   r   r7   s     r8   r/   MiniMaxTopKRouter.__init__  s[    //
!33 ,,ll5;;t/?/?#QRr:   c                 X   UR                  SU R                  5      n[        R                  " XR                  5      n[
        R                  R                  R                  UR                  5       SS9n[
        R                  " X0R                  SS9u  pEXDR                  SSS9-  nUnX&U4$ )Nr>   rq   T)rr   r?   )r   rD  r   linearr3   r1   r   r!  r"  rS   topkrA  sum)r5   r;   router_logitsrouter_probsrouter_top_valuerouter_indicesrouter_scoress          r8   rH   MiniMaxTopKRouter.forward  s    %--b$//B<xx**22=3F3F3Hb2Q+0::lJJTV+W(00R0FF(^;;r:   )rD  rC  rA  r3   )rO   rP   rQ   rR   r/   rH   rU   rV   rW   s   @r8   r>  r>    s    S< <r:   r>  c                      ^  \ rS rSrSrS\4U 4S jjrS\R                  S\R                  S\R                  S\R                  4S	 jr	S
r
U =r$ )MiniMaxExpertsi  z2Collection of expert weights stored as 3D tensors.r   c                   > [         TU ]  5         UR                  U l        UR                  U l        UR                  U l        [        R                  " [        R                  " U R                  SU R                  -  U R
                  5      5      U l        [        R                  " [        R                  " U R                  U R
                  U R                  5      5      U l        [        UR                     U l        g )Nr=   )r.   r/   rB  rC  r6   rD  intermediate_sizeintermediate_dimr   r0   r1   rE  gate_up_proj	down_projr   r   r   rF  s     r8   r/   MiniMaxExperts.__init__  s    !33 ,, & 8 8LLT5E5Eq4K`K`G`bfbqbq)rsekk$2B2BDOOUYUjUj&klV../r:   r;   top_k_indextop_k_weightsr,   c                 X   [         R                  " U5      n[         R                  " 5          [         R                  R                  R                  X R                  S9nUR                  SSS5      n[         R                  " UR                  SS9S5      R                  5       nS S S 5        W H  nUS   nXpR                  :X  a  M  [         R                  " WU   5      u  pX   n
[        R                  R                  XR                  U   5      R                  SSS9u  pU R                  U5      U-  n[        R                  R                  XR                   U   5      nXXS 4   -  nUR#                  SXR%                  UR&                  5      5        M     U$ ! , (       d  f       N= f)N)num_classesr=   r%   r   )r>   r   rq   r>   )r1   
zeros_liker  r   r!  one_hotrC  permutegreaterrK  nonzeror   rI  rW  chunkr   rX  
index_add_rA   r@   )r5   r;   rZ  r[  final_hidden_statesexpert_mask
expert_hit
expert_idx	top_k_pos	token_idxcurrent_stategateupcurrent_hidden_statess                 r8   rH   MiniMaxExperts.forward  so    $..}=]]_((--55kO_O_5`K%--aA6K{8'DaHPPRJ 
 %J#AJ---#(;;{:/F#G I)4M}}++M;L;LZ;XY__`agi_jHD$(KK$5$:!$&MM$8$89NP^P^_iPj$k!$9)`dJd<e$e!**1i9Q9QReRkRk9lm % #"# _s   A7F
F))r   rX  rW  rD  rV  rC  )rO   rP   rQ   rR   r<  r&   r/   r1   rT   rH   rU   rV   rW   s   @r8   rS  rS    sR    <0} 0#||# \\# ||	#
 
# #r:   rS  c                      ^  \ rS rSrU 4S jrS\R                  S\\R                  \R                  4   4S jrSr	U =r
$ )MiniMaxSparseMoeBlocki  c                    > [         TU ]  5         UR                  U l        UR                  U l        [        U5      U l        [        U5      U l	        g r\   )
r.   r/   r@  rA  router_jitter_noisejitter_noiser>  rl  rS  expertsrF  s     r8   r/   MiniMaxSparseMoeBlock.__init__  sA    //
"66%f-	%f-r:   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R                   S   5      nU R                  U5      u  pVnU R                  XU5      nUR                  X#U5      nU$ )Nr   r   r>   )
rL   r  rt  r1   
empty_likeuniform_r4  rl  ru  r   )r5   r;   r   sequence_lengthrD  re   r[  rZ  s           r8   rH   MiniMaxSparseMoeBlock.forward
  s    2?2E2E/
Z==T..2U--m<EEcDL]L]F]_beievev_vwwM%**2}/B/B2/FG(,		-(@%+]O%--j:Vr:   )ru  rl  rt  rA  )rO   rP   rQ   rR   r/   r1   rT   rK   rH   rU   rV   rW   s   @r8   rq  rq    s6    .U\\ eELL%,,<V6W  r:   rq  c                   T  ^  \ rS rSrS\S\4U 4S jjr     SS\R                  S\	\R                  \R                  4   S-  S\R                  S-  S	\R                  S-  S
\S-  S\S-  S\\   S\	\R                  \	\R                  \R                  4   S-  4   4S jjrSrU =r$ )MiniMaxDecoderLayeri  r   rd   c                   > [         TU ]  5         UR                  U l        [        X5      U l        [        UR                  UR                  S9U l        [        UR                  UR                  S9U l        X l	        [        US5      (       a  UR                  U   OS U l        UR                  U l        UR                  U l        [        U5      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r+   layer_typeslinear_attention)r.   r/   r6   r'  	self_attnr)   rms_norm_epsinput_layernormpost_attention_layernormrd   hasattrr  
layer_typemlp_alpha_factormlp_beta_factorrq  mlpr   linear_attn_alpha_factorattn_alpha_factorlinear_attn_beta_factorattn_beta_factorfull_attn_alpha_factorfull_attn_beta_factorr/  s      r8   r/   MiniMaxDecoderLayer.__init__  s	   !--)&<-f.@.@fFYFYZ(6v7I7IvObOb(c%";B6=;Y;Y&,,Y7_c & 7 7%55(0??006vIDN%+%D%DD"$*$B$BD!-f@DN%+%B%BD"$*$@$@D!r:   Nr;   r   r   r   r   	use_cacher   r,   c           
         U R                  U5      nUnU R                  " S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      nXR                  -  XR                  -  -   nU$ )N)r;   r   r   r   r   r   )r  r  r  r  r  r  r  r  )
r5   r;   r   r   r   r   r  r   residualre   s
             r8   rH   MiniMaxDecoderLayer.forward,  s     ,,]; >> 
' 3)%+
 
 !#9#99MLaLa<aa55mD / #8#88=K_K_;__r:   )r  r  r6   r  rd   r  r  r  r  r  r  )NNNNF)rO   rP   rQ   rR   r&   r   r/   r1   rT   rK   
LongTensorr	   r   r   r   FloatTensorrH   rU   rV   rW   s   @r8   r}  r}    s    A} A A2 IM.204(,!&|| #5<<#=>E t+	
 &&-  $; -. 
u  %(9(95;L;L(L"MPT"TT	U r:   r}  c                      ^  \ 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	S
9\\\/S.r\R,                  " 5       U 4S j5       rSrU =r$ )MiniMaxPreTrainedModeliJ  r   modelTr}  r   Fzmlp.gater   )
layer_nameindex)rL  r;   
attentionsc                   > [         TU ]  U5        U R                  R                  n[	        U[
        5      (       aA  [        R                  " UR                  SUS9  [        R                  " UR                  SUS9  O5[	        U[        5      (       a   [        R                  " UR                  SUS9  [	        U[        5      (       a  UR                  5       nUR                  U5      u  pEn[        R                  " UR                   U5        [        R                  " UR"                  U5        [        R                  " UR$                  U5        [        R                  " UR&                  U5        g g )Nr2  )rD   std)r.   _init_weightsr   initializer_ranger   rS  initnormal_rW  rX  r>  r3   r   r   r   copy_r   r   r   r   )r5   r  r  r   r   r   r   r7   s          r8   r  $MiniMaxPreTrainedModel._init_weights\  s    f%kk++fn--LL,,3C@LL))= 122LLSc:f788..0J5;5I5I*5U2KNJJv((*5JJv));7JJv''3JJv,,n= 9r:   r  )rO   rP   rQ   rR   r&   r  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>  r}  r'  r   _can_record_outputsr1   r  r  rU   rV   rW   s   @r8   r  r  J  s    &*#./#4"5N""&'(9jXYZ,')BC ]]_> >r:   r  c                      ^  \ rS rSrS\4U 4S jjr\\      SS\R                  S-  S\R                  S-  S\R                  S-  S\S-  S	\R                  S-  S
\S-  S\\   S\\-  4S jj5       5       rSrU =r$ )MiniMaxModelin  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   	Embeddingr6   embed_tokens
ModuleListra   r   r}  rt   r)   r  r   r   
rotary_embgradient_checkpointing	post_initr/  s      r8   r/   MiniMaxModel.__init__p  s     !.. ++LL):):F<N<NPTP`P`ammEJ6KcKcEdeEd	 3Ede
 #6#5#56;N;NO	0?&+# 	 fs   C?N	input_idsr   r   r   inputs_embedsr  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cU  Ub  UR                  5       OSn[        R                  " UR                  S   UR                  S9U-   nUR                  S5      nU R                  R                  c  [        O[        n	U	" U R                  UUUUS9n
UnU R                  X5      n[!        U R"                  5       H6  u  pU R                  R$                  U   S:X  a  U
nOUnU" U4UUUUUS	.UD6nM8     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   r  r   r   r   full_attention)r   r   r   r   r  )last_hidden_stater   )
ValueErrorrY   r   r   r  get_seq_lengthr1   r   rL   r   r   r   r3  r   r   r  	enumeratert   r  r   r   )r5   r  r   r   r   r  r  r   past_seen_tokensmask_functioncausal_maskr;   r   r   decoder_layerinput_attention_masks                   r8   rH   MiniMaxModel.forward  s    -t";<YZZ0*nOz/<HHefjkzf{e||}~    --i8MCRC^==?de <<(;(;A(>}G[G[\_ooL'11!4L.2kk.H.H.P*Vw#;;')+%
 &"oomJ )$++ 6A{{&&q)-=='2$ (6$)3$7) /# M !7" 		-0%++
 	
r:   )r  r  rt   r   r  r  r  )NNNNNN)rO   rP   rQ   rR   r&   r/   r"   r$   r1   r  rT   rY   r  r   r   r   rK   r   rH   rU   rV   rW   s   @r8   r  r  n  s    }     .2.204/326!%>
##d*>
 t+>
 &&-	>

 &,>
 ((4/>
 $;>
 +,>
 
'	'>
   >
r:   r  gate_logitsrC  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   rq   r>   )r   rK   r   r1   r   rA   r   r!  r"  rJ  r_  rD   rS   rL   r   r   rK  r   )r  rC  rA  r   compute_device
layer_gateconcatenated_gate_logitsrouting_weightsre   selected_expertsrf  tokens_per_expertrouter_prob_per_expertr   rz  r   expert_attention_mask router_per_expert_attention_maskoverall_losss                      r8   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S0rSS0rSS/S/40rU 4S jr\\	         SS
\
R                  S	-  S\
R                  S	-  S\
R                  S	-  S\S	-  S\
R                  S	-  S\
R                  S	-  S\S	-  S\S	-  S\\
R                  -  S\\   S\4S jj5       5       rSrU =r$ )MiniMaxForCausalLMi  zlm_head.weightzmodel.embed_tokens.weightlm_headcolwise_gather_outputr;   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 )NFr   )r.   r/   r  r  r  r   r   r6   r  router_aux_loss_coefrB  rC  r@  r  rF  s     r8   r/   MiniMaxForCausalLM.__init__  s     !&)
 ++yy!3!3V5F5FUS$*$?$?!!33#)#=#=  	r:   Nr  r   r   r   r  labelsr  output_router_logitslogits_to_keepr   r,   c
                 z   Ub  UOU R                   R                  nU R                  " S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(       aY  [        UR                  U R                  U R                  U5      nUb*  XR                  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  r  r  )lossaux_lossr  r   r;   r  rL  r  )r   r  r  r  r   r   slicer  loss_functionr  r  rL  rC  r@  r  rA   r   r   r   r;   r  )r5   r  r   r   r   r  r  r  r  r  r   outputsr;   slice_indicesr  r  r  s                    r8   rH   MiniMaxForCausalLM.forward'  sP   N %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!//))!//
 	
r:   )r  r  rC  r@  r  r  )	NNNNNNNNr   )rO   rP   rQ   rR   _tied_weights_keys_tp_plan_pp_planr/   r    r   r1   r  rT   r	   r  r   r   r   r   r   rH   rU   rV   rW   s   @r8   r  r    s5   *,GH23H_-z:;H
  .2.204(,26*.!%,0-.P
##d*P
 t+P
 &&-	P

 P
 ((4/P
   4'P
 $;P
 #TkP
 ell*P
 +,P
 
#P
  P
r:   r  c                       \ rS rSrSrg) MiniMaxForSequenceClassificationi|  r  NrO   rP   rQ   rR   rU   r  r:   r8   r  r  |      r:   r  c                       \ rS rSrSrg)MiniMaxForTokenClassificationi  r  Nr  r  r:   r8   r  r    r  r:   r  c                       \ rS rSrSrg)MiniMaxForQuestionAnsweringi  r  Nr  r  r:   r8   r  r    r  r:   r  )r  r  r  r  r  r  )r%   )r2  )Nr=   N)Scollections.abcr   typingr   r1   torch.nn.functionalr   r!  r    r   r  activationsr   cache_utilsr	   r
   
generationr   integrationsr   r   r   r   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!   r"   utils.output_capturingr#   r$   configuration_minimaxr&   Moduler)   rY   r   r   r  r  rT   r   r  rS   r%  r'  r>  rS  rq  r}  r  r  rK   r  r  r  r  r  __all__r  r:   r8   <module>r     s  , %      & ! . )  S B  R K F & I I G E 0 Y'JRYY J (J("I< "IJO/		 O/d><RYY ><B( *+ ,2	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % % '(%2 )*8)ryy 8) +8)v<		 <$ $#RYY $# $#NBII &24 2j  >_  >  >F Q
) Q
 Q
l #
*.	O&ell 33d:O&tO& LL4'	O&
 \\CO&d c
/ c
 c
L	'GI_ 		$ACY 		"=?U 	r:   