
    iP                        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l1m2Z2m3Z3m4Z4 ddl5m6Z6  ed       G d dejn                               Z8 G d de      Z9 G d dejn                        Z: G d dejn                        Z;d Z< ed       dId!       Z=d"ej|                  d#e?d$ej|                  fd%Z@	 dJd&ejn                  d'ej|                  d(ej|                  d)ej|                  d*ej|                  dz  d+eAd,eAd-e,e.   fd.ZB ee=       G d/ d0ejn                               ZC G d1 d2ejn                        ZDe G d3 d4ejn                               ZE G d5 d6ejn                        ZF G d7 d8e!      ZGe/ G d9 d:e*             ZHe/ G d; d<eH             ZI	 	 	 dKd=ej|                  eJej|                     z  dz  d>e?dz  d*ej|                  dz  d$ej|                  e?z  fd?ZKe/ G d@ dAeHe             ZL G dB dCeeH      ZM G dD dEe eH      ZN G dF dGeeH      ZOg dHZPy)L    )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)OutputRecordercheck_model_inputsmaybe_autocast   )MiniMaxConfigRMSNormc                   ,     e Zd Zd fd	Zd Zd Z xZS )MiniMaxRMSNormc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z=
        MiniMaxRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parametertorchonesweightvariance_epsilon)selfhidden_sizeeps	__class__s      v/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/transformers/models/minimax/modeling_minimax.pyr+   zMiniMaxRMSNorm.__init__:   s1     	ll5::k#:; #    c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )N   T)keepdim)	dtypetor-   float32powmeanrsqrtr0   r/   )r1   hidden_statesinput_dtypevariances       r5   forwardzMiniMaxRMSNorm.forwardB   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r6   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler/   shaper0   )r1   s    r5   
extra_reprzMiniMaxRMSNorm.extra_reprI   s*    ))*+6$2G2G1HIIr6   )gư>)__name__
__module____qualname__r+   rD   rH   __classcell__r4   s   @r5   r(   r(   8   s    $;Jr6   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r1   r4   s    r5   r+   zMiniMaxCache.__init__N   s    02r6   c                     t        t        | j                        |dz         D ]  }| j                  j                  g         || j                  |<   y )Nr$   )rangelenrR   append)r1   	layer_idxrR   _s       r5   set_linear_cachezMiniMaxCache.set_linear_cacheR   sK    s4,,-y1}= 	)A$$R(	)'3)$r6   rX   c                 >    |t        |       k  r| j                  |   S y rQ   )rV   rR   )r1   rX   s     r5   get_linear_cachezMiniMaxCache.get_linear_cacheX   s"    s4y $$Y//r6   c                 Z    t        t        | 	         t        | j                              S rQ   )maxr*   __len__rV   rR   rS   s    r5   r_   zMiniMaxCache.__len__]   s"    57?$c$*;*;&<==r6   repeatsc                     t        t        |             D ]`  }| j                  |   g k7  r.| j                  |   j                  |d      | j                  |<   C| j                  |   j                  |       b y )Nr   dim)rU   rV   rR   repeat_interleavelayersbatch_repeat_interleave)r1   r`   rX   s      r5   rf   z$MiniMaxCache.batch_repeat_interleave`   ss    s4y) 	HI  +r1/3/@/@/K/]/]^ekl/]/m!!),I&>>wG		Hr6   indicesc                     t        t        |             D ]T  }| j                  |   g k7  r"| j                  |   |df   | j                  |<   7| j                  |   j	                  |       V y )N.)rU   rV   rR   re   batch_select_indices)r1   rg   rX   s      r5   ri   z!MiniMaxCache.batch_select_indicesg   sk    s4y) 	EI  +r1/3/@/@/KGUXL/Y!!),I&;;GD		Er6   
max_lengthc                     t        d      )Nz*MiniMaxCache doesnot support `crop` method)RuntimeError)r1   rj   s     r5   cropzMiniMaxCache.cropn   s    GHHr6   )rI   rJ   rK   r+   rZ   intr\   r_   rf   r-   Tensorri   rm   rL   rM   s   @r5   rO   rO   M   sL    34# 
>Hs HEELL EIs Ir6   rO   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configrX   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+   rX   getattrr2   num_attention_headsrt   num_hidden_layers
block_sizer   
hidden_actact_fnr(   normr   Linearqkv_projout_projoutput_gateget_slope_ratedecay_factorsregister_buffer)r1   rr   rX   rw   rx   ry   rz   r4   s          r5   r+   z"MiniMaxLightningAttention.__init__s   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-~>r6   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$   r8      gh㈵>)r|   r-   arangerX   r}   )r1   baseexponentfactorrates        r5   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"r6   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)r-   r   r~   expwherefloat)r1   rw   block_size_rangerx   ry   rz   s         r5   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5r6   NrA   position_embeddingsattention_maskpast_key_valuescache_positionkwargsreturnc                    |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   rb   r8   r;   r9   r   )!rG   r~   r   r   reshaper|   rt   r-   split	transposer\   rX   zerosr<   boolmasked_fill	unsqueezerU   minrx   ry   rz   r   rw   matmulrW   catr   Fsigmoidr   r   rZ   )#r1   rA   r   r   r   r   r   
batch_sizeseq_lenr2   
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#                                      r5   rD   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...r6   NN)rI   rJ   rK   r%   rn   r+   r   r   r-   ro   rF   r	   
LongTensorr   r   rD   rL   rM   s   @r5   rq   rq   r   s    ?} ? ?,	6& )-26`/||`/ #5<<#=>`/ t+	`/
 `/ ((4/`/ -.`/ 
u||U\\D0%2E2LL	M`/r6   rq   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_freqNrr   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_lenrr   rope_parametersr   compute_default_rope_parametersr   attention_scalingr   clone)r1   rr   devicerope_init_fnr   r4   s        r5   r+   zMiniMaxRotaryEmbedding.__init__  s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L($(ZeD0(..2BuUr6   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_thetart   N      ?r   r8   r   )r   r;   )	r   r{   r2   r|   r-   r   int64r<   r   )rr   r   r   r   rc   attention_factorr   s          r5   r   z6MiniMaxRotaryEmbedding.compute_default_rope_parameters  s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 )))r6   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   r9   r$   mpscpuF)device_typeenabledr8   rb   r   )r   r   expandrG   r<   r   
isinstancetypestrr#   r   r-   r   cosr   sinr;   )
r1   xposition_idsinv_freq_expandedposition_ids_expandedr   freqsembr   r   s
             r5   rD   zMiniMaxRotaryEmbedding.forward6  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$rQ   )NNN)rI   rJ   rK   r-   ro   __annotations__r%   r+   staticmethodr   rn   rF   r   r   no_gradr   rD   rL   rM   s   @r5   r   r     s    llV} V  '++/"*$*(* t* 
~u$	%	* *: U]]_<  <r6   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..Nr9   r8   rb   )rG   r-   r   )r   x1x2s      r5   rotate_halfr   F  sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r6   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          r5   apply_rotary_pos_embr   M  sY    & --
&C
--
&C3w;q>C/0G3w;q>C/0GGr6   rA   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)rG   r   r   )rA   r   batchnum_key_value_headsslenrt   s         r5   	repeat_kvr  g  so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr6   modulequerykeyvaluer   scalingdropoutr   c                 T   t        || j                        }t        || j                        }	t        j                  ||j	                  dd            |z  }
|#|d d d d d d d |j
                  d   f   }|
|z   }
t        j                  j                  |
dt        j                        j                  |j                        }
t        j                  j                  |
|| j                        }
t        j                  |
|	      }|j	                  dd      j                         }||
fS )Nr8   r   r   r9   )rc   r;   )ptrainingr$   )r  num_key_value_groupsr-   r   r   rG   r   
functionalsoftmaxr=   r<   r;   r  r  
contiguous)r  r  r  r  r   r  r  r   r   r   attn_weightscausal_maskr   s                r5   eager_attention_forwardr  s  s    3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL!$Q1.D
0@0@0D.D%DE#k1==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r6   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' paperrr   rX   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 )Nrt   g      TFru   )r*   r+   rr   rX   r{   r2   r|   rt   r   r  r  attention_dropout	is_causalr   r   q_projk_projv_projo_projr1   rr   rX   r4   s      r5   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r6   NrA   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 )Nr9   r$   r8   )r   r   r           sliding_window)r  r  r  )rG   rt   r  viewr   r  r  r   updaterX   r   get_interfacerr   _attn_implementationr  r  r  r  r{   r   r  r  )r1   rA   r   r   r   r   r   input_shapehidden_shaper   r   r   r   r   cache_kwargsattention_interfacer   r  s                     r5   rD   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((r6   r   )rI   rJ   rK   __doc__r%   rn   r+   r-   ro   rF   r	   r   r   r   rD   rL   rM   s   @r5   r  r    s    Gl} l l& )-26*)||*) #5<<#=>*) t+	*)
 *) ((4/*) -.*) 
u||U\\D00	1*)r6   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 rQ   )r*   r+   num_experts_per_toktop_knum_local_expertsnum_expertsr2   
hidden_dimr   r,   r-   emptyr/   r1   rr   r4   s     r5   r+   zMiniMaxTopKRouter.__init__  s[    //
!33 ,,ll5;;t/?/?#QRr6   c                 p   |j                  d| j                        }t        j                  || j                        }t
        j                  j                  j                  |j                         d      }t        j                  || j                  d      \  }}||j                  dd      z  }|}|||fS )Nr9   rb   T)rc   r:   )r   r0  r   linearr/   r-   r   r  r  r   topkr-  sum)r1   rA   router_logitsrouter_top_valuerouter_indicesrouter_scoress         r5   rD   zMiniMaxTopKRouter.forward  s    %--b$//B<++33M4G4G4Ir3R+0::mTZZUW+X(.,00R0FF(m^;;r6   )rI   rJ   rK   r+   rD   rL   rM   s   @r5   r*  r*    s    S<r6   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.rr   c                    t         |           |j                  | _        |j                  | _        |j                  | _        t        j                  t        j                  | j                  d| j                  z  | j
                              | _        t        j                  t        j                  | j                  | j
                  | j                              | _        t        |j                     | _        y )Nr8   )r*   r+   r.  r/  r2   r0  intermediate_sizeintermediate_dimr   r,   r-   r1  gate_up_proj	down_projr   r   r   r2  s     r5   r+   zMiniMaxExperts.__init__  s    !33 ,, & 8 8LLT5E5Eq4K`K`G`bfbqbq)rsekk$2B2BDOOUYUjUj&klV../r6   rA   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_classesr8   r$   r   )r9   r   rb   r9   )r-   
zeros_liker   r   r  one_hotr/  permutegreaterr6  nonzeror   r4  r@  chunkr   rA  
index_add_r<   r;   )r1   rA   rB  rC  final_hidden_statesexpert_mask
expert_hit
expert_idx	top_k_pos	token_idxcurrent_stategateupcurrent_hidden_statess                 r5   rD   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)
rI   rJ   rK   r(  r%   r+   r-   ro   rD   rL   rM   s   @r5   r<  r<    sM    <0} 0#||# \\# ||	#
 
#r6   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 rQ   )
r*   r+   r,  r-  router_jitter_noisejitter_noiser*  rT  r<  expertsr2  s     r5   r+   zMiniMaxSparseMoeBlock.__init__  sA    //
"66%f-	%f-r6   rA   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   r9   )
rG   r  r[  r-   
empty_likeuniform_r   rT  r\  r   )r1   rA   r   sequence_lengthr0  rY   rC  rB  s           r5   rD   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r6   )	rI   rJ   rK   r+   r-   ro   rF   rD   rL   rM   s   @r5   rX  rX    s1    .U\\ eELL%,,<V6W r6   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 )MiniMaxDecoderLayerrr   rX   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r3   layer_typeslinear_attention)r*   r+   r2   r  	self_attnr(   rms_norm_epsinput_layernormpost_attention_layernormrX   hasattrre  
layer_typemlp_alpha_factormlp_beta_factorrX  mlprq   linear_attn_alpha_factorattn_alpha_factorlinear_attn_beta_factorattn_beta_factorfull_attn_alpha_factorfull_attn_beta_factorr  s      r5   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!r6   NrA   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)rA   r   r   r   r   rv  r    )ri  rg  rq  rs  rj  ro  rm  rn  )r1   rA   r   r   r   r   rv  r   r   residualrY   s              r5   rD   zMiniMaxDecoderLayer.forward0  s     ,,]; )4>> 	
' 3)%+)	
 	
q !4#9#99MDLaLa<aa55mD / 4#8#88=4K_K_;__r6   )NNNNFN)rI   rJ   rK   r%   rn   r+   r-   ro   rF   r   r	   r   r   r   FloatTensorrD   rL   rM   s   @r5   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r6   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 )MiniMaxPreTrainedModelrr   modelTrb  r   Fzmlp.gater   )
layer_nameindex)r7  rA   
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  )r?   std)r*   _init_weightsrr   initializer_ranger   r<  initnormal_r@  rA  r*  r/   rq   r   r   copy_rw   rx   ry   rz   )r1   r  r  rw   rx   ry   rz   r4   s          r5   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= 9r6   )rI   rJ   rK   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  rq   _can_record_outputsr-   r   r  rL   rM   s   @r5   r|  r|  P  s    &*#./#4"5N""&'(9jXYZ,')BC U]]_> >r6   r|  c                       e Zd Zdef fdZ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 )MiniMaxModelrr   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  )rr   F)r*   r+   pad_token_idpadding_idx
vocab_sizer   	Embeddingr2   embed_tokens
ModuleListrU   r}   rb  re   r(   rh  r   r   
rotary_embgradient_checkpointing	post_initr  s      r5   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   )rr   input_embedsr   r   r   r   full_attention)r   r   r   r   rv  r   )last_hidden_stater   )
ValueErrorrO   r   r   r  get_seq_lengthr-   r   rG   r   r   rr   r  r   r   r  re   rl  r   r   )r1   r  r   r   r   r  rv  r   r   past_seen_tokensmask_functionr  rA   r   decoder_layerinput_attention_masks                   r5   rD   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%++
 	
r6   )NNNNNNN)rI   rJ   rK   r%   r+   r"   r-   r   ro   rO   rz  r   r   r   rF   r   rD   rL   rM   s   @r5   r  r  t  s    }    .2.204/326!%26D
##d*D
 t+D
 &&-	D

 &,D
 ((4/D
 $;D
 ((4/D
 +,D
 
'	'D
 D
r6   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   rb   r9   )r   rF   r   r-   r   r<   r   r  r  r5  rG  r?   r   rG   r   r   r6  r   )r  r/  r-  r   compute_device
layer_gateconcatenated_gate_logitsrouting_weightsrY   selected_expertsrN  tokens_per_expertrouter_prob_per_expertr   r`  r}   expert_attention_mask router_per_expert_attention_maskoverall_losss                      r5   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_outputrA   logitsc                 N   t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        |j                  | _	        |j                  | _        |j                  | _        | j                          y )NFru   )r*   r+   r  r}  r  r   r   r2   r  router_aux_loss_coefr.  r/  r,  r  r2  s     r5   r+   zMiniMaxForCausalLM.__init__&  s     !&)
 ++yy!3!3V5F5FUS$*$?$?!!33#)#=#=  	r6   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   rA   r  r7  rx  )rr   r  r}  r  r   rn   slicer  loss_functionr  r  r7  r/  r,  r  r<   r   r   r   rA   r  )r1   r  r   r   r   r  r  rv  r  r   r  r   outputsrA   slice_indicesr  r  r  s                     r5   rD   zMiniMaxForCausalLM.forward2  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!//))!//
 	
r6   )
NNNNNNNNNr   )rI   rJ   rK   _tied_weights_keys_tp_plan_pp_planr+   r    r   r-   r   ro   r	   rz  r   rn   r   r   r   rD   rL   rM   s   @r5   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
r6   r  c                       e Zd Zy) MiniMaxForSequenceClassificationNrI   rJ   rK   rx  r6   r5   r  r        r6   r  c                       e Zd Zy)MiniMaxForTokenClassificationNr  rx  r6   r5   r  r    r  r6   r  c                       e Zd Zy)MiniMaxForQuestionAnsweringNr  rx  r6   r5   r  r    r  r6   r  )r|  r  r  r  r  r  )r$   )r  )Nr8   N)Qcollections.abcr   typingr   r-   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"   r#   configuration_minimaxr%   Moduler(   rO   rq   r   r   r   ro   rn   r  r   r  r  r*  r<  rX  rb  r|  r  rF   r  r  r  r  r  __all__rx  r6   r5   <module>r     s  , %      & ! . )  S B  R K F & I I O O 0 Y'JRYY J (J("I< "IJP/		 P/f><RYY ><B( *+ ,2	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % % '(%4 )*;)ryy ;) +;)|<		 <$ $#RYY $# $#NBII &44 4n  >_  >  >F V
) V
 V
v #
*.	O&ell 33d:O&tO& LL4'	O&
 \\CO&d e
/ e
 e
P	'GI_ 		$ACY 		"=?U 	r6   