
    qi                        d dl mZ d dlmZ d dlZd dlmc mZ d dlmZ ddl	m
Z ddlmZ ddlmZmZ dd	lmZ dd
lmZmZmZmZ ddlmZmZ ddlmZ ddlmZmZm Z m!Z! ddl"m#Z#m$Z$ ddl%m&Z&m'Z' ddl(m)Z)m*Z* ddl+m,Z, ddl-m.Z.m/Z/m0Z0 ddl1m2Z2m3Z3 ddl4m5Z5m6Z6 ddl7m8Z8  ed       G d dejr                               Z: G d de      Z; G d dejr                        Z< G d dejr                        Z=d  Z> ed!      dJd"       Z?d#ej                  d$eAd%ej                  fd&ZB	 dKd'ejr                  d(ej                  d)ej                  d*ej                  d+ej                  dz  d,eCd-eCd.e,e.   fd/ZD ee?       G d0 d1ejr                               ZE G d2 d3ejr                        ZFe G d4 d5ejr                               ZG G d6 d7ejr                        ZH G d8 d9e!      ZIe/ G d: d;e*             ZJe/ G d< d=eJ             ZK	 	 	 dLd>ej                  eLej                     z  dz  d?eAdz  d+ej                  dz  d%ej                  eAz  fd@ZMe/ G dA dBeJe             ZN G dC dDeeJ      ZO G dE dFe eJ      ZP G dG dHeeJ      ZQg dIZRy)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                   h     e Zd Zddeddf fdZdej                  dej                  fdZd Z xZ	S )	MiniMaxRMSNormepsreturnNc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z=
        MiniMaxRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parametertorchonesweightvariance_epsilon)selfhidden_sizer*   	__class__s      ^/opt/pipecat/venv/lib/python3.12/site-packages/transformers/models/minimax/modeling_minimax.pyr.   zMiniMaxRMSNorm.__init__;   s1     	ll5::k#:; #    hidden_statesc                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )N   T)keepdim)	dtypetor0   float32powmeanrsqrtr3   r2   )r4   r9   input_dtypevariances       r7   forwardzMiniMaxRMSNorm.forwardC   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r8   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler2   shaper3   )r4   s    r7   
extra_reprzMiniMaxRMSNorm.extra_reprJ   s*    ))*+6$2G2G1HIIr8   )gư>)
__name__
__module____qualname__floatr.   r0   TensorrF   rJ   __classcell__r6   s   @r7   r)   r)   9   s7    $ $$ $;U\\ ;ell ;Jr8   r)   c                   r     e Zd Z fdZd ZdefdZ fdZdefdZde	j                  fd	Zd
efdZ xZS )MiniMaxCachec                 0    t         |           g | _        y N)r-   r.   linear_cacher4   r6   s    r7   r.   zMiniMaxCache.__init__O   s    02r8   c                     t        t        | j                        |dz         D ]  }| j                  j                  g         || j                  |<   y )Nr%   )rangelenrV   append)r4   	layer_idxrV   _s       r7   set_linear_cachezMiniMaxCache.set_linear_cacheS   sK    s4,,-y1}= 	)A$$R(	)'3)$r8   r\   c                 >    |t        |       k  r| j                  |   S y rU   )rZ   rV   )r4   r\   s     r7   get_linear_cachezMiniMaxCache.get_linear_cacheY   s"    s4y $$Y//r8   c                 Z    t        t        | 	         t        | j                              S rU   )maxr-   __len__rZ   rV   rW   s    r7   rc   zMiniMaxCache.__len__^   s"    57?$c$*;*;&<==r8   repeatsc                     t        t        |             D ]`  }| j                  |   g k7  r.| j                  |   j                  |d      | j                  |<   C| j                  |   j                  |       b y )Nr   dim)rY   rZ   rV   repeat_interleavelayersbatch_repeat_interleave)r4   rd   r\   s      r7   rj   z$MiniMaxCache.batch_repeat_interleavea   ss    s4y) 	HI  +r1/3/@/@/K/]/]^ekl/]/m!!),I&>>wG		Hr8   indicesc                     t        t        |             D ]T  }| j                  |   g k7  r"| j                  |   |df   | j                  |<   7| j                  |   j	                  |       V y )N.)rY   rZ   rV   ri   batch_select_indices)r4   rk   r\   s      r7   rm   z!MiniMaxCache.batch_select_indicesh   sk    s4y) 	EI  +r1/3/@/@/KGUXL/Y!!),I&;;GD		Er8   
max_lengthc                     t        d      )Nz*MiniMaxCache doesnot support `crop` method)RuntimeError)r4   rn   s     r7   cropzMiniMaxCache.cropo   s    GHHr8   )rK   rL   rM   r.   r^   intr`   rc   rj   r0   rO   rm   rq   rP   rQ   s   @r7   rS   rS   N   sL    34# 
>Hs HEELL EIs Ir8   rS   c                   >    e Zd Zdedef fdZd Zd Z	 	 ddej                  de
ej                  ej                  f   d	ej                  dz  d
edz  dej                  dz  dee   de
ej                  ej                  dz  e
ej                     dz  f   fdZ xZS )MiniMaxLightningAttentionconfigr\   c                    t         |           || _        t        |dd       xs |j                  |j
                  z  | _        |j
                  | _        |j                  | _        |j                  | _        t        |j                     | _        t        | j                  | j
                  z        | _        t        j                  |j                  | j
                  | j                  z  dz  d      | _        t        j                  | j
                  | j                  z  |j                  d      | _        t        j                  |j                  | j
                  | j                  z  d      | _        | j'                         }| j)                  |      \  }}}| j+                  d|       | j+                  d|       | j+                  d|       | j+                  d|       y )	Nhead_dimr   Fbias
slope_ratequery_decay	key_decaydiagonal_decay)r-   r.   r\   getattrr5   num_attention_headsrw   num_hidden_layers
block_sizer   
hidden_actact_fnr)   normr   Linearqkv_projout_projoutput_gateget_slope_ratedecay_factorsregister_buffer)r4   ru   r\   rz   r{   r|   r}   r6   s          r7   r.   z"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.Y\:6]K8[)4-~>r8   c                     ddd| j                   z  z  z  }t        j                  | j                         dz   }d| j                  | j                  dz
  dz   z  z
  dz   }||z  }||z  }|d d d d f   }|S )Nr%   r;      gh㈵>)r   r0   aranger\   r   )r4   baseexponentfactorrates        r7   r   z(MiniMaxLightningAttention.get_slope_rate   s    A!d66678<< 8 89A=T^^t'='='AD'HIIDPX~f}AtTM"r8   c                    t        j                  | j                        dz   }t        j                  | |d d d f   z        }t        j                  | | j                  |d d d f   z
  z        }|d d d f   |d d d f   z
  }|d d d d d d f   }||z  }t        j                  |dk\  | t        d            }t        j                  |      }|||fS )Nr%   r   z-inf)r0   r   r   expwhererN   )r4   rz   block_size_ranger{   r|   r}   s         r7   r   z'MiniMaxLightningAttention.decay_factors   s     <<81<ii.>q$w.G GHIIzkT__?OPQSWPW?X-XYZ	)!T'25EdAg5NN'dAq(89#n4^q%8>/5QW=Y>2I~55r8   Nr9   position_embeddingsattention_maskpast_key_valuescache_positionkwargsr+   c                    |j                   \  }}}	|| j                  z   dz
  | j                  z  }
| j                  | j                  |            }|j	                  ||| j
                  d| j                  z        }t        j                  || j                  d      \  }}}|j                  dd      }|j                  dd      }|j                  dd      }d }||j                  | j                        }|t        j                  || j
                  | j                  | j                        j                  |      }|Q|j                  t        j                        }|j                  |j!                  d      j!                  d       d      }g }t#        |
      D ]b  }|| j                  z  }t%        || j                  z   |      }||z
  }|d d d d ||f   }|d d d d ||f   }|d d d d ||f   }| j&                  d d d |f   }| j(                  d d | d f   }| j*                  d d d d d |d |f   }t        j,                  | j.                   |z        }t        j0                  ||j                  dd            }t        j0                  ||z  |      }t        j0                  ||z  |      }||z   }|j3                  |       t        j0                  ||z  j                  dd      |      } ||z  | z   }e nt        j,                  | j.                         }!g }t#        |      D ]  }|d d d d ||dz   f   }|d d d d ||dz   f   }|d d d d ||dz   f   }t        j0                  |j                  dd      |      }"|!|z  |"z   }t        j0                  ||      }|j3                  |        t        j4                  |d      }|j                  dd      }|j	                  ||| j
                  | j                  z        }| j7                  |      }t9        j:                  | j=                  |            |z  }| j?                  |      }||jA                  | j                  |       ||fS )	Nr%   r   rf   r;   r>   r<   r   )!rI   r   r   r   reshaper   rw   r0   split	transposer`   r\   zerosr?   boolmasked_fill	unsqueezerY   minr{   r|   r}   r   rz   matmulr[   catr   Fsigmoidr   r   r^   )#r4   r9   r   r   r   r   r   
batch_sizeseq_lenr5   
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#                                      r7   rF   z!MiniMaxLightningAttention.forward   s    ,9+>+>(
G[/!3G
[[}!=>
''
GT=U=UWX[_[h[hWhi
16Z\]1^.j,#--a3))!Q/
#--a3 "&!0!A!A$..!Q%!&Z9Q9QSWS`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^ 	8'3Aq!a!e)O'D$%/1a!a%i%@"'3Aq!a!e)O'D$-2\\:L:V:VWY[]:^`t-u*%*-?%?B\%\"&+ll3GI[&\#""#67	8 ii4 "++Aq1!))*gt?W?WZ^ZgZg?ghii,ii 0 0 ?@;NmmK0 &,,T^^=OP...r8   NN)rK   rL   rM   r&   rr   r.   r   r   r0   rO   rH   r	   
LongTensorr   r   rF   rP   rQ   s   @r7   rt   rt   s   s    ?} ? ?,	6& )-26`/||`/ #5<<#=>`/ t+	`/
 `/ ((4/`/ -.`/ 
u||U\\D0%2E2LL	M`/r8   rt   c                        e Zd ZU ej                  ed<   ddef fdZe	 	 	 ddedz  de	d   de
dz  ded	ef   fd
       Z ej                         ed               Z xZS )MiniMaxRotaryEmbeddinginv_freqNru   c                    t         |           |j                  | _        |j                  | _        || _        | j
                  j                  d   | _        | j                  }| j                  dk7  rt        | j                     } || j
                  |      \  }| _
        | j                  d|d       | j                  d|j                         d       y )N	rope_typedefaultr   F)
persistentoriginal_inv_freq)r-   r.   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenru   rope_parametersr   compute_default_rope_parametersr   attention_scalingr   clone)r4   ru   devicerope_init_fnr   r6   s        r7   r.   zMiniMaxRotaryEmbedding.__init__	  s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L($(ZeD0(..2BuUr8   r   ztorch.devicer   r+   ztorch.Tensorc                    | j                   d   }t        | dd      xs | j                  | j                  z  }d}d|t	        j
                  d|dt        j                        j                  |t        j                        |z  z  z  }||fS )	a  
        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_thetarw   N      ?r   r;   r   )r   r>   )	r   r~   r5   r   r0   r   int64r?   rN   )ru   r   r   r   rg   attention_factorr   s          r7   r   z6MiniMaxRotaryEmbedding.compute_default_rope_parameters  s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 )))r8   c                 N   | j                   d d d d f   j                         j                  |j                  d   dd      j	                  |j
                        }|d d d d d f   j                         }t        |j
                  j                  t              r/|j
                  j                  dk7  r|j
                  j                  nd}t        |d      5  |j                         |j                         z  j                  dd      }t        j                  ||fd	      }|j                         | j                  z  }|j                         | j                  z  }	d d d        j	                  |j                   
      	j	                  |j                   
      fS # 1 sw Y   AxY w)Nr   r<   r%   mpscpuF)device_typeenabledr;   rf   r   )r   rN   expandrI   r?   r   
isinstancetypestrr!   r   r0   r   cosr   sinr>   )
r4   xposition_idsinv_freq_expandedposition_ids_expandedr   freqsembr   r   s
             r7   rF   zMiniMaxRotaryEmbedding.forward7  sR    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfkUC 	5&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')d444C'')d444C		5 vvAGGv$cff177f&;;;	5 	5s   BFF$rU   )NNN)rK   rL   rM   r0   rO   __annotations__r&   r.   staticmethodr   rr   rH   rN   r   no_gradr   rF   rP   rQ   s   @r7   r   r     s    llV} V  '++/"*$*(* t* 
~u$	%	* *: U]]_<  <r8   r   c                     | dd| j                   d   dz  f   }| d| j                   d   dz  df   }t        j                  | |fd      S )z*Rotates half the hidden dims of the input..Nr<   r;   rf   )rI   r0   r   )r   x1x2s      r7   rotate_halfr   G  sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r8   rotary_pos_embc                     |j                  |      }|j                  |      }| |z  t        |       |z  z   }||z  t        |      |z  z   }||fS )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.
        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          r7   apply_rotary_pos_embr   N  sY    & --
&C
--
&C3w;q>C/0G3w;q>C/0GGr8   r9   n_repr+   c                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      S )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)rI   r   r   )r9   r   batchnum_key_value_headsslenrw   s         r7   	repeat_kvr  h  so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr8   modulequerykeyvaluer   scalingdropoutr   c                    t        || j                        }t        || j                        }	t        j                  ||j	                  dd            |z  }
||
|z   }
t
        j                  j                  |
dt        j                        j                  |j                        }
t
        j                  j                  |
|| j                        }
t        j                  |
|	      }|j	                  dd      j                         }||
fS )Nr;   r   r<   )rg   r>   )ptrainingr%   )r  num_key_value_groupsr0   r   r   r   
functionalsoftmaxr@   r?   r>   r	  r  
contiguous)r  r  r  r  r   r  r	  r   r   r   attn_weightsr   s               r7   eager_attention_forwardr  t  s     3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL!#n4==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r8   c                       e Zd ZdZdedef fdZ	 	 ddej                  de	ej                  ej                  f   dej                  dz  d	e
dz  d
ej                  dz  dee   de	ej                  ej                  dz  f   fdZ xZS )MiniMaxAttentionz=Multi-headed attention from 'Attention Is All You Need' paperru   r\   c                    t         |           || _        || _        t	        |dd       xs |j
                  |j                  z  | _        |j                  |j                  z  | _	        | j                  dz  | _
        |j                  | _        d| _        t        j                  |j
                  |j                  | j                  z  d      | _        t        j                  |j
                  |j                  | j                  z  d      | _        t        j                  |j
                  |j                  | j                  z  d      | _        t        j                  |j                  | j                  z  |j
                  d      | _        y )Nrw   g      TFrx   )r-   r.   ru   r\   r~   r5   r   rw   r  r  r  attention_dropout	is_causalr   r   q_projk_projv_projo_projr4   ru   r\   r6   s      r7   r.   zMiniMaxAttention.__init__  s2   "
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r8   Nr9   r   r   r   r   r   r+   c           
      D   |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }	| j                  |      j                  |      j	                  dd      }
| j                  |      j                  |      j	                  dd      }|\  }}t        |	|
||      \  }	}
|'|||d}|j                  |
|| j                  |      \  }
}t        j                  | j                  j                  t              } || |	|
||f| j                  sdn| j                   | j"                  t%        | j                  dd       d|\  }} |j&                  g |d j)                         }| j+                  |      }||fS )Nr<   r%   r;   )r   r   r           sliding_window)r	  r  r  )rI   rw   r  viewr   r  r  r   updater\   r   get_interfaceru   _attn_implementationr  r  r  r  r~   r   r  r  )r4   r9   r   r   r   r   r   input_shapehidden_shaper   r   r   r   r   cache_kwargsattention_interfacer   r  s                     r7   rF   z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&S#7jRUWZ#[ j&#&snUL'6'='=j,X\XfXfht'u$J(?(M(MKK,,.E)
 %8
%
  $}}C$2H2HLL"4;;0@$G
%
 
%
!\ *k));;;;FFHkk+.L((r8   r   )rK   rL   rM   __doc__r&   rr   r.   r0   rO   rH   r	   r   r   r   rF   rP   rQ   s   @r7   r  r    s    Gl} l l& )-26*)||*) #5<<#=>*) t+	*)
 *) ((4/*) -.*) 
u||U\\D00	1*)r8   r  c                   $     e Zd Z fdZd Z xZS )MiniMaxTopKRouterc                    t         |           |j                  | _        |j                  | _        |j                  | _        t        j                  t        j                  | j
                  | j                              | _        y rU   )r-   r.   num_experts_per_toktop_knum_local_expertsnum_expertsr5   
hidden_dimr   r/   r0   emptyr2   r4   ru   r6   s     r7   r.   zMiniMaxTopKRouter.__init__  s[    //
!33 ,,ll5;;t/?/?#QRr8   c                 p   |j                  d| j                        }t        j                  || j                        }t
        j                  j                  j                  |j                         d      }t        j                  || j                  d      \  }}||j                  dd      z  }|}|||fS )Nr<   rf   T)rg   r=   )r   r0  r   linearr2   r0   r   r  r  rN   topkr-  sum)r4   r9   router_logitsrouter_top_valuerouter_indicesrouter_scoress         r7   rF   zMiniMaxTopKRouter.forward  s    %--b$//B<++33M4G4G4Ir3R+0::mTZZUW+X(.,00R0FF(m^;;r8   )rK   rL   rM   r.   rF   rP   rQ   s   @r7   r*  r*    s    S<r8   r*  c                        e Zd ZdZdef fdZdej                  dej                  dej                  dej                  fdZ xZ	S )	MiniMaxExpertsz2Collection of expert weights stored as 3D tensors.ru   c                    t         |           |j                  | _        |j                  | _        |j                  | _        t        j                  t        j                  | j                  d| j                  z  | j
                              | _        t        j                  t        j                  | j                  | j
                  | j                              | _        t        |j                     | _        y )Nr;   )r-   r.   r.  r/  r5   r0  intermediate_sizeintermediate_dimr   r/   r0   r1  gate_up_proj	down_projr   r   r   r2  s     r7   r.   zMiniMaxExperts.__init__  s    !33 ,, & 8 8LLT5E5Eq4K`K`G`bfbqbq)rsekk$2B2BDOOUYUjUj&klV../r8   r9   top_k_indextop_k_weightsr+   c                 f   t        j                  |      }t        j                         5  t         j                  j                  j                  || j                        }|j                  ddd      }t        j                  |j                  d      d      j                         }d d d        D ]  }|d   }|| j                  k(  rt        j                  |         \  }}	||	   }
t        j                  j                  |
| j                  |         j                  dd      \  }}| j                  |      |z  }t        j                  j                  || j                   |         }|||	|d f   z  }|j#                  d|	|j%                  |j&                                |S # 1 sw Y   xY w)N)num_classesr;   r%   r   )r<   r   rf   r<   )r0   
zeros_liker   r   r  one_hotr/  permutegreaterr6  nonzeror   r4  r@  chunkr   rA  
index_add_r?   r>   )r4   r9   rB  rC  final_hidden_statesexpert_mask
expert_hit
expert_idx	top_k_pos	token_idxcurrent_stategateupcurrent_hidden_statess                 r7   rF   zMiniMaxExperts.forward  s    $..}=]]_ 	S((--55ktO_O_5`K%--aA6K{8'DaHPPRJ	S
 % 
	nJ#AJT---#(;;{:/F#G Iy))4M}}++M4;L;LZ;XY__`agi_jHD"$(KK$5$:!$&MM$8$89NPTP^P^_iPj$k!$9M)U^`dJd<e$e!**1i9N9Q9QReRkRk9lm
	n #"#	S 	Ss   A=F&&F0)
rK   rL   rM   r(  r&   r.   r0   rO   rF   rP   rQ   s   @r7   r<  r<    sM    <0} 0#||# \\# ||	#
 
#r8   r<  c                   t     e Zd Z fdZdej
                  deej
                  ej
                  f   fdZ xZS )MiniMaxSparseMoeBlockc                     t         |           |j                  | _        |j                  | _        t        |      | _        t        |      | _	        y rU   )
r-   r.   r,  r-  router_jitter_noisejitter_noiser*  rT  r<  expertsr2  s     r7   r.   zMiniMaxSparseMoeBlock.__init__  sA    //
"66%f-	%f-r8   r9   r+   c                    |j                   \  }}}| j                  rQ| j                  dkD  rB|t        j                  |      j                  d| j                  z
  d| j                  z         z  }|j                  d|j                   d         }| j                  |      \  }}}| j                  |||      }|j                  |||      }|S )Nr   r   r<   )
rI   r  r[  r0   
empty_likeuniform_r   rT  r\  r   )r4   r9   r   sequence_lengthr0  r]   rC  rB  s           r7   rF   zMiniMaxSparseMoeBlock.forward  s    2?2E2E/
OZ==T..2U--m<EEcDL]L]F]_beievev_vwwM%**2}/B/B2/FG(,		-(@%=+]KO%--j/:Vr8   )	rK   rL   rM   r.   r0   rO   rH   rF   rP   rQ   s   @r7   rX  rX    s1    .U\\ eELL%,,<V6W r8   rX  c                   d    e Zd Zdedef fdZ	 	 	 	 	 	 ddej                  deej                  ej                  f   dz  dej                  dz  dej                  dz  d	e
dz  d
edz  dej                  dz  dee   deej                  eej                  ej                  f   dz  f   fdZ xZS )MiniMaxDecoderLayerru   r\   c                    t         |           |j                  | _        t        ||      | _        t        |j                  |j                        | _        t        |j                  |j                        | _        || _	        t        |d      r|j                  |   nd | _        |j                  | _        |j                  | _        t        |      | _        | j                  dk(  r4t#        ||      | _        |j$                  | _        |j(                  | _        y t        ||      | _        |j,                  | _        |j.                  | _        y )Nr*   layer_typeslinear_attention)r-   r.   r5   r  	self_attnr)   rms_norm_epsinput_layernormpost_attention_layernormr\   hasattrre  
layer_typemlp_alpha_factormlp_beta_factorrX  mlprt   linear_attn_alpha_factorattn_alpha_factorlinear_attn_beta_factorattn_beta_factorfull_attn_alpha_factorfull_attn_beta_factorr  s      r7   r.   zMiniMaxDecoderLayer.__init__  s   !--)&)<-f.@.@fFYFYZ(6v7I7IvObOb(c%";B6=;Y&,,Y7_c & 7 7%55(0??006vyIDN%+%D%DD"$*$B$BD!-fi@DN%+%B%BD"$*$@$@D!r8   Nr9   r   r   r   r   	use_cacher   r   r+   c                 *   | j                  |      }|}	 | j                  d|||||||d|\  }}
|	| j                  z  || j                  z  z   }| j	                  |      }|}	| j                  |      }|	| j                  z  || j                  z  z   }|S )N)r9   r   r   r   r   rv  r    )ri  rg  rq  rs  rj  ro  rm  rn  )r4   r9   r   r   r   r   rv  r   r   residualr]   s              r7   rF   zMiniMaxDecoderLayer.forward0  s     ,,]; )4>> 	
' 3)%+)	
 	
q !4#9#99MDLaLa<aa55mD / 4#8#88=4K_K_;__r8   )NNNNFN)rK   rL   rM   r&   rr   r.   r0   rO   rH   r   r	   r   r   r   FloatTensorrF   rP   rQ   s   @r7   rb  rb    s    A} A A2 IM.204(,!&26|| #5<<#=>E t+	
 &&-  $; ((4/ -. 
u  %(9(95;L;L(L"MPT"TT	Ur8   rb  c                        e Zd ZU eed<   dZdZdgZdgZdZ	dZ
dZdZdZ eedd	      eeegd
Z ej*                          fd       Z xZS )MiniMaxPreTrainedModelru   modelTrb  r   Fzmlp.gater   )
layer_nameindex)r7  r9   
attentionsc                    t         |   |       | j                  j                  }t	        |t
              rEt        j                  |j                  d|       t        j                  |j                  d|       n2t	        |t              r"t        j                  |j                  d|       t	        |t              r|j                         }|j                  |      \  }}}t        j                  |j                   |       t        j                  |j"                  |       t        j                  |j$                  |       t        j                  |j&                  |       y y )Nr  )rB   std)r-   _init_weightsru   initializer_ranger   r<  initnormal_r@  rA  r*  r2   rt   r   r   copy_rz   r{   r|   r}   )r4   r  r  rz   r{   r|   r}   r6   s          r7   r  z$MiniMaxPreTrainedModel._init_weightsb  s    f%kk++fn-LL,,3C@LL))= 12LLSc:f78..0J5;5I5I*5U2KNJJv((*5JJv));7JJv''3JJv,,n= 9r8   )rK   rL   rM   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*  rb  r  rt   _can_record_outputsr0   r   r  rP   rQ   s   @r7   r|  r|  P  s    &*#./#4"5N""&'(9jXYZ,')BC U]]_> >r8   r|  c                       e Zd Zdef fdZee	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  de
dz  dej                  dz  d	edz  d
ej                  dz  dee   deez  fd              Z xZS )MiniMaxModelru   c           	         t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        t#        |      | _        d| _        | j)                          y c c}w )Nrd  )ru   F)r-   r.   pad_token_idpadding_idx
vocab_sizer   	Embeddingr5   embed_tokens
ModuleListrY   r   rb  ri   r)   rh  r   r   
rotary_embgradient_checkpointing	post_initr  s      r7   r.   zMiniMaxModel.__init__v  s     !.. ++LL):):F<N<NPTP`P`ammEJ6KcKcEde	 3e
 #6#5#56;N;NO	0?&+# 	 fs   DN	input_idsr   r   r   inputs_embedsrv  r   r   r+   c                    |d u |d uz  rt        d      |r|t               }n*|r(t        |t              st        dt        |       d      || j	                  |      }|F||j                         nd}	t        j                  |	|	|j                  d   z   |j                        }||j                  d      }| j                  j                  t        nt        }
 |
| j                  |||||      }|}| j                  ||      }| j                   D ]&  }|j"                  dk(  r|}n|} ||f||||||d	|}( | j%                  |      }t'        ||
      S )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   )ru   r  r   r   r   r   full_attention)r   r   r   r   rv  r   )last_hidden_stater   )
ValueErrorrS   r   r   r  get_seq_lengthr0   r   rI   r   r   ru   r  r   r   r  ri   rl  r   r   )r4   r  r   r   r   r  rv  r   r   past_seen_tokensmask_functioncausal_maskr9   r   decoder_layerinput_attention_masks                   r7   rF   zMiniMaxModel.forward  s    -t";<YZZ0*nOz/<Hefjkzf{e||}~    --i8M!CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L.2kk.H.H.P*Vw#;;'))+%
 &"oom\J![[ 	M''+;;'2$ (6$)	3$7) /#-	 	M	$ 		-0%++
 	
r8   )NNNNNNN)rK   rL   rM   r&   r.   r"   r$   r0   r   rO   rS   rz  r   r   r   rH   r   rF   rP   rQ   s   @r7   r  r  t  s    }     .2.204/326!%26D
##d*D
 t+D
 &&-	D

 &,D
 ((4/D
 $;D
 ((4/D
 +,D
 
'	'D
   D
r8   r  gate_logitsr/  c                    | t        | t              syt        | t              rC| d   j                  }t        j                  | D cg c]  }|j                  |       c}d      }t        j                  j                  j                  d      }t        j                  ||d      \  }}	t        j                  j                  j                  |	|      }
|>t        j                  |
j                         d      }t        j                  |d      }n|j                  \  }}|j                  d   ||z  z  }|dddddddf   j                  |||||f      j                  d||      j                        }t        j                   |
j                         |z  d      t        j                   |d      z  }|ddddddf   j                  ||||f      j                  d|      j                  |      }t        j                   ||z  d      t        j                   |d      z  }t        j                   ||j#                  d      z        }||z  S c c}w )a  
    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   rf   r<   )r   rH   r   r0   r   r?   r   r  r  r5  rG  rB   rN   rI   r   r   r6  r   )r  r/  r-  r   compute_device
layer_gateconcatenated_gate_logitsrouting_weightsr]   selected_expertsrN  tokens_per_expertrouter_prob_per_expertr   r`  r   expert_attention_mask router_per_expert_attention_maskoverall_losss                      r7   load_balancing_loss_funcr    s9   : *[%"@+u%$Q..#(99^i-jPZjmmN.K-jpq#r hh))112JPR1SO**_eDA((%%--.>LK!JJ{'8'8':B "'O!C&4&:&:#
O4::1=*B^_ 4AtT12V&
OUK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.1G1Q1QRS1TTUL+%%[ .ks   Ic                   n    e Zd ZddiZddiZddgdgfiZ fdZee	 	 	 	 	 	 	 	 	 	 dd	e	j                  dz  d
e	j                  dz  de	j                  dz  dedz  de	j                  dz  de	j                  dz  dedz  dedz  de	j                  dz  dee	j                  z  dee   defd              Z xZS )MiniMaxForCausalLMzlm_head.weightzmodel.embed_tokens.weightlm_headcolwise_gather_outputr9   logitsc                 N   t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        |j                  | _	        |j                  | _        |j                  | _        | j                          y )NFrx   )r-   r.   r  r}  r  r   r   r5   r  router_aux_loss_coefr.  r/  r,  r  r2  s     r7   r.   zMiniMaxForCausalLM.__init__'  s     !&)
 ++yy!3!3V5F5FUS$*$?$?!!33#)#=#=  	r8   Nr  r   r   r   r  labelsrv  output_router_logitsr   logits_to_keepr   r+   c                 l   ||n| j                   j                  } | j                  d||||||||	d|}|j                  }t	        |
t
              rt        |
 d      n|
}| j                  |dd|ddf         }d}| | j                  ||| j                  fi |}d}|rYt        |j                  | j                  | j                  |      }|+|| j                  |j                  |j                         z  z  }t#        ||||j$                  |j&                  |j(                  |j                        S )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  rv  r  r   )lossaux_lossr  r   r9   r  r7  rx  )ru   r  r}  r  r   rr   slicer  loss_functionr  r  r7  r/  r,  r  r?   r   r   r   r9   r  )r4   r  r   r   r   r  r  rv  r  r   r  r   outputsr9   slice_indicesr  r  r  s                     r7   rF   zMiniMaxForCausalLM.forward3  sX   P %9$D $++JjJj 	
 +5$** 
+
)%+'!5)
+
 
+
  118B>SV8W~ot4]kmA}a,?@A%4%%ffdooPPD/%%  ((	H !11HKK4LLL(#33!//))!//
 	
r8   )
NNNNNNNNNr   )rK   rL   rM   _tied_weights_keys_tp_plan_pp_planr.   r    r   r0   r   rO   r	   rz  r   rr   r   r   r   rF   rP   rQ   s   @r7   r  r  !  sN   *,GH23H_-z:;H
  .2.204(,26*.!%,026-.R
##d*R
 t+R
 &&-	R

 R
 ((4/R
   4'R
 $;R
 #TkR
 ((4/R
 ell*R
 +,R
 
#R
  R
r8   r  c                       e Zd Zy) MiniMaxForSequenceClassificationNrK   rL   rM   rx  r8   r7   r  r        r8   r  c                       e Zd Zy)MiniMaxForTokenClassificationNr  rx  r8   r7   r  r    r  r8   r  c                       e Zd Zy)MiniMaxForQuestionAnsweringNr  rx  r8   r7   r  r    r  r8   r  )r|  r  r  r  r  r  )r%   )r  )Nr;   N)Scollections.abcr   typingr   r0   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)   rS   rt   r   r   r   rO   rr   r  rN   r  r  r*  r<  rX  rb  r|  r  rH   r  r  r  r  r  __all__rx  r8   r7   <module>r     s  , %      & ! . )  S B  R K F & I I G E 0 Y'JRYY J (J("I< "IJP/		 P/f><RYY ><B( *+ ,2	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % % '(%2 )*;)ryy ;) +;)|<		 <$ $#RYY $# $#NBII &44 4n  >_  >  >F W
) W
 W
x #
*.	O&ell 33d:O&tO& LL4'	O&
 \\CO&d e
/ e
 e
P	'GI_ 		$ACY 		"=?U 	r8   