o
    ei                     @   s"  d dl mZ d dlmZ d dlZd dlm  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 dej9Z:G dd deZ;G dd dej9Z<G dd dej9Z=d d! Z>ed"dQd#d$Z?d%ej@d&eAd'ej@fd(d)ZB	*dRd+ej9d,ej@d-ej@d.ej@d/ej@dB d0eCd1eCd2e,e. fd3d4ZDee?G d5d6 d6ej9ZEG d7d8 d8ej9ZFeG d9d: d:ej9ZGG d;d< d<ej9ZHG d=d> d>e!ZIe/G d?d@ d@e*ZJe/G dAdB dBeJZK		C	dSdDej@eLej@ B dB dEeAdB d/ej@dB d'ej@eAB fdFdGZMe/G dHdI dIeJeZNG dJdK dKeeJZOG dLdM dMe eJZPG dNdO dOeeJZQg dPZRdS )T    )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                       sF   e Zd Zddeddf fddZdejdejfdd	Zd
d Z  Z	S )MiniMaxRMSNormư>epsreturnNc                    s&   t    tt|| _|| _dS )z=
        MiniMaxRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parametertorchonesweightvariance_epsilon)selfhidden_sizer)   	__class__ j/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/transformers/models/minimax/modeling_minimax.pyr,   ;   s   

zMiniMaxRMSNorm.__init__hidden_statesc                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )N   T)keepdim)	dtypetor.   float32powmeanrsqrtr1   r0   )r2   r8   input_dtypevariancer6   r6   r7   forwardC   s
   zMiniMaxRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)tupler0   shaper1   r2   r6   r6   r7   
extra_reprJ   s   zMiniMaxRMSNorm.extra_repr)r(   )
__name__
__module____qualname__floatr,   r.   TensorrD   rH   __classcell__r6   r6   r4   r7   r'   9   s    r'   c                       sj   e Zd Z fddZdd ZdefddZ fdd	Zd
efddZde	j
fddZdefddZ  ZS )MiniMaxCachec                    s   t    g | _d S N)r+   r,   linear_cacherG   r4   r6   r7   r,   O   s   

zMiniMaxCache.__init__c                 C   s4   t t| j|d D ]}| jg  q
|| j|< d S )Nr$   )rangelenrQ   append)r2   	layer_idxrQ   _r6   r6   r7   set_linear_cacheS   s   zMiniMaxCache.set_linear_cacherU   c                 C   s   |t | k r| j| S d S rP   )rS   rQ   )r2   rU   r6   r6   r7   get_linear_cacheY   s   
zMiniMaxCache.get_linear_cachec                    s   t t  t| jS rP   )maxr+   __len__rS   rQ   rG   r4   r6   r7   rZ   ^   s   zMiniMaxCache.__len__repeatsc                 C   sP   t t| D ]}| j| g kr| j| j|dd| j|< q| j| | qd S )Nr   dim)rR   rS   rQ   repeat_interleavelayersbatch_repeat_interleave)r2   r[   rU   r6   r6   r7   r`   a   s
   z$MiniMaxCache.batch_repeat_interleaveindicesc                 C   sN   t t| D ]}| j| g kr| j| |df | j|< q| j| | qd S )N.)rR   rS   rQ   r_   batch_select_indices)r2   ra   rU   r6   r6   r7   rb   h   s
   z!MiniMaxCache.batch_select_indices
max_lengthc                 C   s   t d)Nz*MiniMaxCache doesnot support `crop` method)RuntimeError)r2   rc   r6   r6   r7   cropo   s   zMiniMaxCache.crop)rI   rJ   rK   r,   rW   intrX   rZ   r`   r.   rM   rb   re   rN   r6   r6   r4   r7   rO   N   s    rO   c                       s   e Zd Zdedef fddZdd Zdd Z				dd
ej	de
ej	ej	f dej	d	B ded	B dejd	B dee de
ej	ej	d	B e
ej	 d	B f fddZ  ZS )MiniMaxLightningAttentionconfigrU   c                    s  t    || _t|dd p|j|j | _|j| _|j| _|j| _t	|j
 | _t| j| j | _tj|j| j| j d dd| _tj| j| j |jdd| _tj|j| j| j dd| _|  }| |\}}}| d| | d| | d| | d| d S )	Nhead_dimr   Fbias
slope_ratequery_decay	key_decaydiagonal_decay)r+   r,   rU   getattrr3   num_attention_headsri   num_hidden_layers
block_sizer   
hidden_actact_fnr'   normr   Linearqkv_projout_projoutput_gateget_slope_ratedecay_factorsregister_buffer)r2   rh   rU   rl   rm   rn   ro   r4   r6   r7   r,   t   s"   
 z"MiniMaxLightningAttention.__init__c                 C   sd   ddd| j    }t| j d }d| j| jd d   d }|| }|| }|d d d d f }|S )Nr$   r9      gh㈵>)rq   r.   arangerU   rr   )r2   baseexponentfactorrater6   r6   r7   r{      s   z(MiniMaxLightningAttention.get_slope_ratec                 C   s   t | jd }t | |d d d f  }t | | j|d d d f   }|d d d f |d d d f  }|d d d d d d f }|| }t |dk| td}t |}|||fS )Nr$   r   z-inf)r.   r   rs   expwhererL   )r2   rl   block_size_rangerm   rn   ro   r6   r6   r7   r|      s   " 

z'MiniMaxLightningAttention.decay_factorsNr8   position_embeddingsattention_maskpast_key_valuescache_positionkwargsr*   c           #      K   sl  |j \}}}	|| j d | j }
| | |}|||| jd| j }tj|| jdd\}}}|	dd}|	dd}|	dd}d }|d urN|
| j}|d u r!t|| j| j| j|}|d ury|jtjd}||dd d}g }t|
D ]}|| j }t|| j |}|| }|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 | }t||	dd}t|| |}t|| |}|| }|| t|| 	dd|} || |  }qnYt| j }!g }t|D ]K}|d d d d ||d f }|d d d d ||d f }|d d d d ||d f }t|	dd|}"|!| |" }t||}|| q.tj|dd}|	dd}|||| j| j }| |}t| || }| |}|d ur| | j| ||fS )	Nr$   r   r\   r9   r<   r:   r   )!rF   rs   ru   rx   reshaperq   ri   r.   split	transposerX   rU   zerosr=   boolmasked_fill	unsqueezerR   minrm   rn   ro   r   rl   matmulrT   catrv   Fsigmoidrz   ry   rW   )#r2   r8   r   r   r   r   r   
batch_sizeseq_lenr3   
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_interr6   r6   r7   rD      sv   	

"
 


z!MiniMaxLightningAttention.forwardNN)rI   rJ   rK   r%   rf   r,   r{   r|   r.   rM   rE   r   
LongTensorr   r   rD   rN   r6   r6   r4   r7   rg   s   s*    rg   c                       s~   e Zd ZU ejed< ddef fddZe			ddedB de	d de
dB d	ed
ef fddZe edd Z  ZS )MiniMaxRotaryEmbeddinginv_freqNrh   c                    s   t    |j| _|j| _|| _| jjd | _| j}| jdkr$t	| j }|| j|\}| _
| jd|dd | jd| dd d S )N	rope_typedefaultr   F)
persistentoriginal_inv_freq)r+   r,   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrh   rope_parametersr   compute_default_rope_parametersr   attention_scalingr}   clone)r2   rh   devicerope_init_fnr   r4   r6   r7   r,   	  s   


zMiniMaxRotaryEmbedding.__init__r   ztorch.devicer   r*   ztorch.Tensorc                 C   sZ   | j d }t| ddp| j| j }d}d|tjd|dtjdj|tjd|   }||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_thetari   N      ?r   r9   r   )r   r<   )	r   rp   r3   rq   r.   r   int64r=   rL   )rh   r   r   r   r]   attention_factorr   r6   r6   r7   r     s   
&z6MiniMaxRotaryEmbedding.compute_default_rope_parametersc           
      C   s   | j d d d d f  |jd dd|j}|d d d d d f  }t|jjtr6|jjdkr6|jjnd}t	|dd+ | |  
dd}tj||fdd	}| | j }| | j }	W d    n1 slw   Y  |j|jd
|	j|jd
fS )Nr   r:   r$   mpscpuF)device_typeenabledr9   r\   r   )r   rL   expandrF   r=   r   
isinstancetypestrr    r   r.   r   cosr   sinr<   )
r2   xposition_idsinv_freq_expandedposition_ids_expandedr   freqsembr   r   r6   r6   r7   rD   7  s   0&zMiniMaxRotaryEmbedding.forwardrP   )NNN)rI   rJ   rK   r.   rM   __annotations__r%   r,   staticmethodr   rf   rE   rL   r   no_gradr   rD   rN   r6   r6   r4   r7   r     s&   
 

r   c                 C   sH   | dd| j d d f }| d| j d d df }tj| |fddS )z*Rotates half the hidden dims of the input..Nr:   r9   r\   )rF   r.   r   )r   x1x2r6   r6   r7   rotate_halfG  s   r   rotary_pos_embc                 C   sD   | |}| |}| | t| |  }|| t||  }||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_embedr6   r6   r7   apply_rotary_pos_embN  s
   

r   r8   n_repr*   c                 C   s^   | j \}}}}|dkr| S | dddddddddf |||||} | ||| ||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)rF   r   r   )r8   r   batchnum_key_value_headsslenri   r6   r6   r7   	repeat_kvh  s
   0r           modulequerykeyvaluer   scalingdropoutr   c                 K   s   t || j}t || j}	t||dd| }
|d ur |
| }
tjj|
dtjd	|j
}
tjj|
|| jd}
t|
|	}|dd }||
fS )Nr9   r   r:   )r]   r<   )ptrainingr$   )r   num_key_value_groupsr.   r   r   r   
functionalsoftmaxr>   r=   r<   r   r   
contiguous)r   r   r   r   r   r   r   r   r   r   attn_weightsr   r6   r6   r7   eager_attention_forwardt  s   
r   c                       s   e Zd ZdZdedef fddZ		ddejde	ejejf d	ejdB d
e
dB dejdB dee de	ejejdB f fddZ  ZS )MiniMaxAttentionz=Multi-headed attention from 'Attention Is All You Need' paperrh   rU   c                    s   t    || _|| _t|dd p|j|j | _|j|j | _	| jd | _
|j| _d| _tj|j|j| j dd| _tj|j|j| j dd| _tj|j|j| j dd| _tj|j| j |jdd| _d S )Nri   g      TFrj   )r+   r,   rh   rU   rp   r3   rq   ri   r   r   r   attention_dropout	is_causalr   rw   q_projk_projv_projo_projr2   rh   rU   r4   r6   r7   r,     s   
 zMiniMaxAttention.__init__Nr8   r   r   r   r   r   r*   c                 K   s$  |j d d }g |d| jR }| ||dd}	| ||dd}
| ||dd}|\}}t|	|
||\}	}
|d urW|||d}||
|| j	|\}
}t
| jjt}|| |	|
||f| jskdn| j| jt| jdd d|\}}|jg |dR   }| |}||fS )Nr:   r$   r9   )r   r   r   r   sliding_window)r   r   r  )rF   ri   r   viewr   r   r   r   updaterU   r   get_interfacerh   _attn_implementationr   r   r   r   rp   r   r   r  )r2   r8   r   r   r   r   r   input_shapehidden_shaper   r   r   r   r   cache_kwargsattention_interfacer   r   r6   r6   r7   rD     s:   		

zMiniMaxAttention.forwardr   )rI   rJ   rK   __doc__r%   rf   r,   r.   rM   rE   r   r   r   r   rD   rN   r6   r6   r4   r7   r     s(    r   c                       s$   e Zd Z fddZdd Z  ZS )MiniMaxTopKRouterc                    s>   t    |j| _|j| _|j| _t	t
| j| j| _d S rP   )r+   r,   num_experts_per_toktop_knum_local_expertsnum_expertsr3   
hidden_dimr   r-   r.   emptyr0   r2   rh   r4   r6   r7   r,     s
   
zMiniMaxTopKRouter.__init__c                 C   sh   | d| j}t|| j}tjjj|	 dd}tj
|| jdd\}}||jddd }|}|||fS )Nr:   r\   T)r]   r;   )r   r  r   linearr0   r.   r   r   r   rL   topkr  sum)r2   r8   router_logitsrouter_top_valuerouter_indicesrouter_scoresr6   r6   r7   rD     s   
zMiniMaxTopKRouter.forward)rI   rJ   rK   r,   rD   rN   r6   r6   r4   r7   r    s    r  c                       sH   e Zd ZdZdef fddZdejdejdejdejfd	d
Z  Z	S )MiniMaxExpertsz2Collection of expert weights stored as 3D tensors.rh   c                    sn   t    |j| _|j| _|j| _t	t
| jd| j | j| _t	t
| j| j| j| _t|j | _d S )Nr9   )r+   r,   r  r  r3   r  intermediate_sizeintermediate_dimr   r-   r.   r  gate_up_proj	down_projr   rt   ru   r  r4   r6   r7   r,     s   
 zMiniMaxExperts.__init__r8   top_k_indextop_k_weightsr*   c                 C   s  t |}t  % t jjj|| jd}|ddd}t |j	ddd
 }W d    n1 s1w   Y  |D ]O}|d }|| jkrDq8t || \}}	||	 }
tj|
| j| jddd\}}| || }tj|| j| }|||	|d f  }|d|	||j q8|S )N)num_classesr9   r$   r   )r:   r   r\   r:   )r.   
zeros_liker   r   r   one_hotr  permutegreaterr  nonzeror   r  r  chunkru   r   
index_add_r=   r<   )r2   r8   r!  r"  final_hidden_statesexpert_mask
expert_hit
expert_idx	top_k_pos	token_idxcurrent_stategateupcurrent_hidden_statesr6   r6   r7   rD     s$   


"zMiniMaxExperts.forward)
rI   rJ   rK   r  r%   r,   r.   rM   rD   rN   r6   r6   r4   r7   r    s    	r  c                       s<   e Zd Z fddZdejdeejejf fddZ  ZS )MiniMaxSparseMoeBlockc                    s2   t    |j| _|j| _t|| _t|| _	d S rP   )
r+   r,   r  r  router_jitter_noisejitter_noiser  r2  r  expertsr  r4   r6   r7   r,     s
   

zMiniMaxSparseMoeBlock.__init__r8   r*   c                 C   s   |j \}}}| jr| jdkr|t|d| j d| j 9 }|d|j d }| |\}}}| |||}|	|||}|S )Nr   r   r:   )
rF   r   r7  r.   
empty_likeuniform_r  r2  r8  r   )r2   r8   r   sequence_lengthr  rV   r"  r!  r6   r6   r7   rD     s   "zMiniMaxSparseMoeBlock.forward)	rI   rJ   rK   r,   r.   rM   rE   rD   rN   r6   r6   r4   r7   r5    s    (r5  c                       s   e Zd Zdedef fddZ						ddejdeejejf dB d	ejdB d
ej	dB de
dB dedB dej	dB dee deejeejejf dB f fddZ  ZS )MiniMaxDecoderLayerrh   rU   c                    s   t    |j| _t||| _t|j|jd| _t|j|jd| _|| _	t
|dr.|j| nd | _|j| _|j| _t|| _| jdkrSt||| _|j| _|j| _d S t||| _|j| _|j| _d S )Nr)   layer_typeslinear_attention)r+   r,   r3   r   	self_attnr'   rms_norm_epsinput_layernormpost_attention_layernormrU   hasattrr>  
layer_typemlp_alpha_factormlp_beta_factorr5  mlprg   linear_attn_alpha_factorattn_alpha_factorlinear_attn_beta_factorattn_beta_factorfull_attn_alpha_factorfull_attn_beta_factorr  r4   r6   r7   r,     s"   


zMiniMaxDecoderLayer.__init__NFr8   r   r   r   r   	use_cacher   r   r*   c              
   K   sv   |  |}|}	| jd|||||||d|\}}
|	| j || j  }| |}|}	| |}|	| j || j  }|S )N)r8   r   r   r   r   rO  r   r6   )rB  r@  rJ  rL  rC  rH  rF  rG  )r2   r8   r   r   r   r   rO  r   r   residualrV   r6   r6   r7   rD   0  s&   




zMiniMaxDecoderLayer.forward)NNNNFN)rI   rJ   rK   r%   rf   r,   r.   rM   rE   r   r   r   r   r   FloatTensorrD   rN   r6   r6   r4   r7   r<    s6    	
r<  c                       sp   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d	eeegd
Ze  fddZ  ZS )MiniMaxPreTrainedModelrh   modelTr<  r   Fzmlp.gater   )
layer_nameindex)r  r8   
attentionsc                    s   t  | | jj}t|tr"tj|jd|d tj|j	d|d nt|t
r0tj|jd|d t|tr_| }||\}}}t|j| t|j| t|j| t|j| d S d S )Nr   )r@   std)r+   _init_weightsrh   initializer_ranger   r  initnormal_r  r   r  r0   rg   r{   r|   copy_rl   rm   rn   ro   )r2   r   rW  rl   rm   rn   ro   r4   r6   r7   rX  b  s   


z$MiniMaxPreTrainedModel._init_weights)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  r<  r   rg   _can_record_outputsr.   r   rX  rN   r6   r6   r4   r7   rR  P  s"   
 rR  c                       s   e Zd Zdef fddZee							ddejdB dej	dB dejdB de
dB d	ejdB d
edB dejdB dee deeB fddZ  ZS )MiniMaxModelrh   c                    s   t     j| _ j| _t j j| j| _t	 fddt
 jD | _t j jd| _t d| _d| _|   d S )Nc                    s   g | ]}t  |qS r6   )r<  ).0rU   rh   r6   r7   
<listcomp>}      z)MiniMaxModel.__init__.<locals>.<listcomp>r=  ri  F)r+   r,   pad_token_idpadding_idx
vocab_sizer   	Embeddingr3   embed_tokens
ModuleListrR   rr   r_   r'   rA  rv   r   
rotary_embgradient_checkpointing	post_initr  r4   ri  r7   r,   v  s   zMiniMaxModel.__init__N	input_idsr   r   r   inputs_embedsrO  r   r   r*   c              
   K   s8  |d u |d uA rt d|r|d u rt }n|r't|ts't dt| d|d u r0| |}|d u rL|d ur<| nd}	tj|	|	|jd  |j	d}|d u rU|
d}| jjd u r]tnt}
|
| j|||||d}|}| ||}| jD ]}|jdkr|}n|}||f||||||d	|}qu| |}t||d
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   )rh   rv  r   r   r   r   full_attention)r   r   r   r   rO  r   )last_hidden_stater   )
ValueErrorrO   r   r   rp  get_seq_lengthr.   r   rF   r   r   rh   r  r   r   rr  r_   rE  rv   r   )r2   ru  r   r   r   rv  rO  r   r   past_seen_tokensmask_functioncausal_maskr8   r   decoder_layerinput_attention_maskr6   r6   r7   rD     sb   

	


zMiniMaxModel.forward)NNNNNNN)rI   rJ   rK   r%   r,   r!   r#   r.   r   rM   rO   rQ  r   r   r   rE   r   rD   rN   r6   r6   r4   r7   rg  t  s<    	
rg  r9   gate_logitsr  c                    s  | du s	t | tsdS t | tr#| d j tj fdd| D dd}tjjj|dd}tj||dd\}}tjj	||}|du rStj
| dd}	tj
|dd}
ng|j\}}|jd ||  }|dddddddf |||||fd|| }tj| | ddtj|dd }	|ddddddf ||||fd| }tj|| ddtj|dd }
t|	|
d }|| S )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   c                    s   g | ]}|  qS r6   )r=   )rh  
layer_gatecompute_devicer6   r7   rj    rk  z,load_balancing_loss_func.<locals>.<listcomp>r\   r:   )r   rE   r   r.   r   r   r   r   r  r%  r@   rL   rF   r   r   r=   r  r   )r  r  r  r   concatenated_gate_logitsrouting_weightsrV   selected_expertsr,  tokens_per_expertrouter_prob_per_expertr   r;  rr   expert_attention_mask router_per_expert_attention_maskoverall_lossr6   r  r7   load_balancing_loss_func  s>   



r  c                       s   e Zd ZddiZddiZddgdgfiZ fddZee																			
dde	j
d	B de	jd	B de	j
d	B ded	B de	jd	B de	j
d	B ded	B ded	B de	j
d	B dee	jB dee defddZ  ZS )MiniMaxForCausalLMzlm_head.weightzmodel.embed_tokens.weightlm_headcolwise_gather_outputr8   logitsc                    sX   t  | t|| _|j| _tj|j|jdd| _|j	| _	|j
| _|j| _|   d S )NFrj   )r+   r,   rg  rS  rn  r   rw   r3   r  router_aux_loss_coefr  r  r  rt  r  r4   r6   r7   r,   '  s   
zMiniMaxForCausalLM.__init__Nr   ru  r   r   r   rv  labelsrO  output_router_logitsr   logits_to_keepr   r*   c                 K   s   |dur|n| j j}| jd||||||||	d|}|j}t|
tr)t|
 dn|
}| |dd|ddf }d}|durK| j||| j	fi |}d}|rht
|j| j| j|}|durh|| j||j 7 }t||||j|j|j|jd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)ru  r   r   r   rv  rO  r  r   )lossaux_lossr  r   r8   rV  r  r6   )rh   r  rS  ry  r   rf   slicer  loss_functionrn  r  r  r  r  r  r=   r   r   r   r8   rV  )r2   ru  r   r   r   rv  r  rO  r  r   r  r   outputsr8   slice_indicesr  r  r  r6   r6   r7   rD   3  sN   (	zMiniMaxForCausalLM.forward)
NNNNNNNNNr   )rI   rJ   rK   _tied_weights_keys_tp_plan_pp_planr,   r   r   r.   r   rM   r   rQ  r   rf   r   r   r   rD   rN   r6   r6   r4   r7   r  !  sT    	
r  c                   @      e Zd ZdS ) MiniMaxForSequenceClassificationNrI   rJ   rK   r6   r6   r6   r7   r        r  c                   @   r  )MiniMaxForTokenClassificationNr  r6   r6   r6   r7   r    r  r  c                   @   r  )MiniMaxForQuestionAnsweringNr  r6   r6   r6   r7   r    r  r  )rR  rg  r  r  r  r  )r$   )r   )Nr9   N)Scollections.abcr   typingr   r.   torch.nn.functionalr   r   r    r   rZ  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'   rO   rg   r   r   r   rM   rf   r   rL   r   r   r  r  r5  r<  rR  rg  rE   r  r  r  r  r  __all__r6   r6   r6   r7   <module>   s   % A
>'7#\
Rh