a
    h                  
   @   s  d dl mZmZ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 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+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2 edG dd dej3Z4G dd deZ5G dd dej3Z6dd Z7dCdd Z8ej9e:ej9d!d"d#Z;dDej3ej9ej9ej9eej9 e<e<e(e* d%d&d'Z=G d(d) d)ej3Z>G d*d+ d+ej3Z?G d,d- d-ej3Z@G d.d/ d/eZAe+G d0d1 d1e&ZBG d2d3 d3ej3ZCe+G d4d5 d5eBZDdEeej9eEej9 df ee: eej9 eej9e:f d7d8d9ZFe+G d:d; d;eBeZGG d<d= d=eeBZHG d>d? d?eeBZIG d@dA dAeeBZJg dBZKdS )F    )CallableOptionalUnionN)nn)check_model_inputs   )ACT2FN)CacheDynamicCache)GenerationMixin)use_kernel_forward_from_hub)create_causal_mask!create_sliding_window_causal_mask)FlashAttentionKwargs)GenericForQuestionAnswering GenericForSequenceClassificationGenericForTokenClassificationGradientCheckpointingLayer)MoeCausalLMOutputWithPastMoeModelOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuple)deprecate_kwarg)OutputRecorder   )MiniMaxConfigZRMSNormc                       s.   e Zd Zd fdd	Zdd Zdd Z  ZS )	MiniMaxRMSNormư>c                    s&   t    tt|| _|| _dS )z=
        MiniMaxRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	ParametertorchZonesweightvariance_epsilon)selfhidden_sizeeps	__class__ h/var/www/html/assistant/venv/lib/python3.9/site-packages/transformers/models/minimax/modeling_minimax.pyr%   7   s    
zMiniMaxRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )N   T)keepdim)	dtypetor'   float32powmeanZrsqrtr)   r(   )r*   hidden_statesZinput_dtypeZvariancer/   r/   r0   forward?   s
    zMiniMaxRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)tupler(   shaper)   r*   r/   r/   r0   
extra_reprF   s    zMiniMaxRMSNorm.extra_repr)r#   )__name__
__module____qualname__r%   r:   r>   __classcell__r/   r/   r-   r0   r"   5   s   r"   c                       s   e Zd Z fddZdd ZedddZ fdd	Zed fd
dZdd Z	edddZ
ejdddZedddZ  ZS )MiniMaxCachec                    s   t    g | _d S N)r$   r%   linear_cacher=   r-   r/   r0   r%   K   s    
zMiniMaxCache.__init__c                 C   s4   t t| j|d D ]}| jg  q|| j|< d S )Nr    )rangelenrE   append)r*   	layer_idxrE   _r/   r/   r0   set_linear_cacheO   s    zMiniMaxCache.set_linear_cache)rI   c                 C   s   |t | k r| j| S d S rD   )rG   rE   r*   rI   r/   r/   r0   get_linear_cacheU   s    
zMiniMaxCache.get_linear_cachec                    s   t t  t| jS rD   )maxr$   __len__rG   rE   r=   r-   r/   r0   rO   Z   s    zMiniMaxCache.__len__c                    s4   |t | jk r(| j| g kr(| j| fS t |S rD   )rG   rE   r$   __getitem__rL   r-   r/   r0   rP   ]   s    zMiniMaxCache.__getitem__c                 c   s    t t| D ]}| | V  qd S rD   )rF   rG   rL   r/   r/   r0   __iter__b   s    zMiniMaxCache.__iter__)repeatsc                 C   sP   t t| D ]>}| j| g kr:| j| j|dd| j|< q| j| | qd S )Nr   dim)rF   rG   rE   Zrepeat_interleavelayersbatch_repeat_interleave)r*   rR   rI   r/   r/   r0   rV   f   s    z$MiniMaxCache.batch_repeat_interleave)indicesc                 C   sN   t t| D ]<}| j| g kr8| j| |df | j|< q| j| | qd S )N.)rF   rG   rE   rU   batch_select_indices)r*   rW   rI   r/   r/   r0   rX   m   s    z!MiniMaxCache.batch_select_indices)
max_lengthc                 C   s   t dd S )Nz*MiniMaxCache doesnot support `crop` method)RuntimeError)r*   rY   r/   r/   r0   cropt   s    zMiniMaxCache.crop)r?   r@   rA   r%   rK   intrM   rO   rP   rQ   rV   r'   TensorrX   r[   rB   r/   r/   r-   r0   rC   J   s   rC   c                       s   e Zd Zeed fddZdd Zdd Zedd	d
dde	j
ee	j
e	j
f ee	j
 ee ee	j ee ee	j
ee	j
 eee	j
  f dddZ  ZS )MiniMaxLightningAttentionconfigrI   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Zbias
slope_ratequery_decay	key_decaydiagonal_decay)r$   r%   rI   getattrr+   num_attention_headsra   num_hidden_layers
block_sizer   
hidden_actact_fnr"   normr   Linearqkv_projout_projoutput_gateget_slope_ratedecay_factorsregister_buffer)r*   r`   rI   rc   rd   re   rf   r-   r/   r0   r%   y   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    r1      gh㈵>)rh   r'   arangerI   ri   )r*   baseexponentfactorZrater/   r/   r0   rr      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'   rv   rj   expwherefloat)r*   rc   Zblock_size_rangerd   re   rf   r/   r/   r0   rs      s    " 
z'MiniMaxLightningAttention.decay_factorspast_key_valuepast_key_values4.58new_nameversionNr9   position_embeddingsattention_maskr~   cache_positionkwargsreturnc           #      K   sn  |j \}}}	|| j d | j }
| | |}|||| jd| j }tj|| jdd\}}}|	dd}|	dd}|	dd}d }|d ur|
| j}|d u rDt|| j| j| j|}|d ur|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|} || |  }qnt| j }!g }t|D ]}|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rf| | j| ||fS )	Nr    r   rS   r1   r4   r2   r   )!r<   rj   rl   ro   reshaperh   ra   r'   split	transposerM   rI   zerosr5   boolZmasked_fill	unsqueezerF   minrd   re   rf   rz   rc   matmulrH   catrm   FZsigmoidrq   rp   rK   )#r*   r9   r   r   r~   r   r   
batch_sizeZseq_lenr+   Z
num_blocksZ
qkv_statesquery_states
key_statesvalue_statesZattn_weights_interattn_outputiZ	start_idxZend_idxZcurrent_block_sizeZcurrent_query_statesZcurrent_key_statesZcurrent_value_statesZcurrent_query_decayZcurrent_key_decayZcurrent_diagonal_decayZblock_decayZattn_weights_intraZattn_output_intraZattn_output_interZcurrent_attn_outputZnext_attn_weights_interratioZcurrent_attn_weights_interr/   r/   r0   r:      st    


"



z!MiniMaxLightningAttention.forward)NN)r?   r@   rA   r!   r\   r%   rr   rs   r   r'   r]   r;   r   r	   
LongTensorr   r   r:   rB   r/   r/   r-   r0   r^   x   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..Nr2   r1   rS   )r<   r'   r   )xx1Zx2r/   r/   r0   rotate_half  s    r   c                 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.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )r   r   )qkcossinposition_idsZunsqueeze_dimZq_embedZk_embedr/   r/   r0   apply_rotary_pos_emb  s
    

r   )r9   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)r<   expandr   )r9   r   batchnum_key_value_headsslenra   r/   r/   r0   	repeat_kv.  s
    0r           )modulequerykeyvaluer   scalingdropoutr   c                 K   s   t || j}t || j}	t||dd| }
|d urf|d d d d d d d |jd f }|
| }
tjj|
dtj	d
|j}
tjj|
|| jd}
t|
|	}|dd }||
fS )Nr1   r   r   r2   rT   r4   )ptrainingr    )r   num_key_value_groupsr'   r   r   r<   r   
functionalsoftmaxr6   r5   r4   r   r   
contiguous)r   r   r   r   r   r   r   r   r   r   attn_weightscausal_maskr   r/   r/   r0   eager_attention_forward:  s    
&r   c                       s   e Zd ZdZeed fddZedddddej	e
ej	ej	f eej	 ee eej ee e
ej	eej	 f d
ddZ  ZS )MiniMaxAttentionz=Multi-headed attention from 'Attention Is All You Need' paperr_   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 )Nra   g      TFrb   )r$   r%   r`   rI   rg   r+   rh   ra   r   r   r   attention_dropoutZ	is_causalr   rn   q_projk_projv_projo_projr*   r`   rI   r-   r/   r0   r%   W  s    
zMiniMaxAttention.__init__r}   r~   r   r   Nr   c                 K   s0  |j d d }g |d| jR }| ||dd}	| ||dd}
| ||dd}|\}}t|	|
||\}	}
|d ur|||d}||
|| j	|\}
}t
}| jjdkrt| jj }|| |	|
||f| jsdn| j| jt| jdd d|\}}|jg |dR   }| |}||fS )	Nr2   r    r1   )r   r   r   eagerr   sliding_window)r   r   r   )r<   ra   r   viewr   r   r   r   updaterI   r   r`   Z_attn_implementationr   r   r   r   rg   r   r   r   )r*   r9   r   r   r~   r   r   Zinput_shapeZhidden_shaper   r   r   r   r   Zcache_kwargsZattention_interfacer   r   r/   r/   r0   r:   e  s:    
	

zMiniMaxAttention.forward)NN)r?   r@   rA   __doc__r!   r\   r%   r   r'   r]   r;   r   r	   r   r   r   r:   rB   r/   r/   r-   r0   r   T  s     r   c                       s*   e Zd Zed fddZdd Z  ZS )MiniMaxBlockSparseTop2MLPr`   c                    sl   t    |j| _|j| _tj| j| jdd| _tj| j| jdd| _	tj| j| jdd| _
t|j | _d S NFrb   )r$   r%   intermediate_sizeffn_dimr+   
hidden_dimr   rn   w1w2w3r   rk   rl   r*   r`   r-   r/   r0   r%     s    
z"MiniMaxBlockSparseTop2MLP.__init__c                 C   s(   |  | || | }| |}|S rD   )rl   r   r   r   )r*   r9   current_hidden_statesr/   r/   r0   r:     s    
z!MiniMaxBlockSparseTop2MLP.forward)r?   r@   rA   r!   r%   r:   rB   r/   r/   r-   r0   r     s   r   c                       s4   e Zd ZdZ fddZejejdddZ  ZS )MiniMaxSparseMoeBlocka  
    This implementation is
    strictly equivalent to standard MoE with full capacity (no
    dropped tokens). It's faster since it formulates MoE operations
    in terms of block-sparse operations to accommodate imbalanced
    assignments of tokens to experts, whereas standard MoE either
    (1) drop tokens at the cost of reduced performance or (2) set
    capacity factor to number of experts and thus waste computation
    and memory on padding.
    c                    sl   t     j| _ j| _ j| _ j| _	t
j| j| jdd| _t
 fddt| jD | _ j| _d S )NFrb   c                    s   g | ]}t  qS r/   )r   ).0rJ   r   r/   r0   
<listcomp>      z2MiniMaxSparseMoeBlock.__init__.<locals>.<listcomp>)r$   r%   r+   r   r   r   num_local_expertsnum_expertsnum_experts_per_toktop_kr   rn   gate
ModuleListrF   expertsZrouter_jitter_noisejitter_noiser   r-   r   r0   r%     s    
 zMiniMaxSparseMoeBlock.__init__)r9   r   c                 C   sn  |j \}}}| jr>| jdkr>|t|d| j d| j 9 }|d|}| |}tj	|dtj
d}tj|| jdd\}}||jddd }||j}tj|| |f|j|jd	}tjjj|| jd
ddd}	t|	jddd }
|
D ]f}| j| }t|	| d\}}|d|f d|}|||||df  }|d|||j q||||}||fS ) r   g      ?r2   r    r   rS   T)rT   r3   )r4   device)Znum_classesr1   )r2   r   N)r<   r   r   r'   Z
empty_likeZuniform_r   r   r   r   r|   topkr   sumr5   r4   r   r   r   r   one_hotr   ZpermuteZgreaterZnonzeror   r{   Zsqueezer   Z
index_add_)r*   r9   r   sequence_lengthr   router_logitsrouting_weightsselected_expertsZfinal_hidden_statesexpert_maskZ
expert_hitZ
expert_idxZexpert_layeridxZtop_xZcurrent_stater   r/   r/   r0   r:     s,    "

zMiniMaxSparseMoeBlock.forward)	r?   r@   rA   r   r%   r'   r]   r:   rB   r/   r/   r-   r0   r     s   r   c                       s   e Zd Zeed fddZedddddeje	ejejf e
ej e
ej e
e	ej  e
e e
e e
e e
ej ee e	eje
e	ejejf  f d
ddZ  ZS )MiniMaxDecoderLayerr_   c                    s   t    |j| _t||| _t|| _t|j|jd| _	t|j|jd| _
|| _|j| | _|j| _|j| _| jdkrt||| _|j| _|j| _nt||| _|j| _|j| _d S )Nr,   Zlinear_attention)r$   r%   r+   r   	self_attnr   block_sparse_moer"   rms_norm_epsinput_layernormpost_attention_layernormrI   Zlayer_types
layer_typemlp_alpha_factormlp_beta_factorr^   Zlinear_attn_alpha_factorattn_alpha_factorZlinear_attn_beta_factorattn_beta_factorZfull_attn_alpha_factorZfull_attn_beta_factorr   r-   r/   r0   r%     s"    



zMiniMaxDecoderLayer.__init__r}   r~   r   r   NF)r9   r   r   r   r~   output_attentionsoutput_router_logits	use_cacher   r   r   c
                 K   s|   |  |}|}| jf ||||||||	d|
\}}|| j || j  }| |}|}| |\}}|| j || j  }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`):
                Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
                with `head_dim` being the embedding dimension of each attention head.
            attention_mask (`torch.Tensor`, *optional*): attention mask of size
                `(batch, sequence_length)` where padding elements are indicated by 0.
            past_key_values (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_router_logits (`bool`, *optional*):
                Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
                should not be returned during inference.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence.
            kwargs (`dict`, *optional*):
                Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
                into the model
        )r9   r   r   r   r~   r   r   r   )r   r   r   r   r   r   r   r   )r*   r9   r   r   r   r~   r   r   r   r   r   ZresidualrJ   r/   r/   r0   r:     s(    '
	

zMiniMaxDecoderLayer.forward)NNNFFFN)r?   r@   rA   r!   r\   r%   r   r'   r]   r;   r   r   r   r   r   FloatTensorr:   rB   r/   r/   r-   r0   r     s,          r   c                   @   sV   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d
S )MiniMaxPreTrainedModelr`   modelTr   r~   Fr    )index)r   r9   
attentionsN)r?   r@   rA   r!   __annotations__Zbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_skip_keys_device_placementZ_supports_flash_attnZ_supports_sdpaZ_supports_flex_attnZ_can_compile_fullgraphZ_supports_attention_backendr   r   r   r   r^   Z_can_record_outputsr/   r/   r/   r0   r   B  s   

r   c                       sD   e Zd ZU ejed< ded fddZe e	dd Z
  ZS )	MiniMaxRotaryEmbeddinginv_freqNr   c                    s   t    t|dr:t|jtr:|jd|jd| _nd| _|j| _	|j| _
|| _t| j | _| | j|\}| _| jd|dd | j| _d S )Nrope_scaling	rope_typetypedefaultr  F)
persistent)r$   r%   hasattr
isinstancer  dictgetr  Zmax_position_embeddingsZmax_seq_len_cachedZoriginal_max_seq_lenr`   r   Zrope_init_fnattention_scalingrt   r  Zoriginal_inv_freq)r*   r`   r   r  r-   r/   r0   r%   X  s    
zMiniMaxRotaryEmbedding.__init__c           
      C   s   | j d d d d f  |jd dd|j}|d d d d d f  }t|jjtrl|jjdkrl|jjnd}t	j
|ddV | |  dd}t	j||fdd	}| | j }| | j }	W d    n1 s0    Y  |j|jd
|	j|jd
fS )Nr   r2   r    ZmpscpuF)device_typeZenabledr1   rS   r   )r  r|   r   r<   r5   r   r  r  strr'   Zautocastr   r   r   r  r   r4   )
r*   r   r   Zinv_freq_expandedZposition_ids_expandedr  ZfreqsZembr   r   r/   r/   r0   r:   i  s    0&,zMiniMaxRotaryEmbedding.forward)N)r?   r@   rA   r'   r]   r   r!   r%   Zno_gradr   r:   rB   r/   r/   r-   r0   r   U  s
   

r   c                       sv   e Zd Zed fddZeedeje	ej
 e	ej e	e e	ej e	e e	e e	ej ee ed
ddZ  ZS )	MiniMaxModelr   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 r/   )r   )r   rI   r   r/   r0   r     r   z)MiniMaxModel.__init__.<locals>.<listcomp>r   r   F)r$   r%   Zpad_token_idZpadding_idx
vocab_sizer   Z	Embeddingr+   embed_tokensr   rF   ri   rU   r"   r   rm   r   
rotary_embZgradient_checkpointing	post_initr   r-   r   r0   r%   {  s    zMiniMaxModel.__init__N)
	input_idsr   r   r~   inputs_embedsr   r   r   r   r   c	              
   K   s8  |d u |d uA rt d|r,|d u r,t }n"|rNt|tsNt dt| d|d u r`| |}|d u r|d urx| nd}
tj|
|
|jd  |j	d}|d u r|
d}| jjd u rtnt}|| j|||||d}|}| ||}| jD ]6}|jdkr|}n|}||f||||||d	|	}q| |}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   )r`   Zinput_embedsr   r   r~   r   Zfull_attention)r   r   r   r~   r   r   )last_hidden_stater~   )
ValueErrorrC   r  r  r  Zget_seq_lengthr'   rv   r<   r   r   r`   r   r   r   r  rU   r   rm   r   )r*   r  r   r   r~   r  r   r   r   r   Zpast_seen_tokensZmask_functionr   r9   r   Zdecoder_layerZinput_attention_maskr/   r/   r0   r:     sb    

	


zMiniMaxModel.forward)NNNNNNNN)r?   r@   rA   r!   r%   r   r   r'   r   r   r]   rC   r   r   r   r   r   r:   rB   r/   r/   r-   r0   r  y  s.           r  r1   )gate_logitsr   r   r   c                    s  | du st | tsdS t | trF| 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 rtj
| dd}	tj
|dd}
n|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 r/   )r5   )r   Z
layer_gateZcompute_devicer/   r0   r     r   z,load_balancing_loss_func.<locals>.<listcomp>rS   r2   )r  r;   r   r'   r   r   r   r   r   r   r8   r|   r<   r   r   r5   r   r   )r  r   r   r   Zconcatenated_gate_logitsr   rJ   r   r   Ztokens_per_expertZrouter_prob_per_expertr   r   ri   Zexpert_attention_maskZ router_per_expert_attention_maskZoverall_lossr/   r  r0   load_balancing_loss_func  sJ    



r  c                       s   e Zd ZdgZddiZddgdgfiZ fddZeede	e
j e	e
j e	e
j e	e e	e
j e	e
j e	e e	e e	e
j eee
jf ee ed
ddZ  ZS )MiniMaxForCausalLMzlm_head.weightlm_headZcolwise_repr9   logitsc                    sX   t  | t|| _|j| _tj|j|jdd| _|j	| _	|j
| _|j| _|   d S r   )r$   r%   r  r   r  r   rn   r+   r  router_aux_loss_coefr   r   r   r  r   r-   r/   r0   r%   /  s    
zMiniMaxForCausalLM.__init__Nr   )r  r   r   r~   r  labelsr   r   r   logits_to_keepr   r   c                 K   s   |dur|n| j j}| jf ||||||||	d|}|j}t|
trRt|
 dn|
}| |dd|ddf }d}|dur| j||| j	fi |}d}|rt
|j| j| j|}|dur|| 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)r  r   r   r~   r  r   r   r   )lossaux_lossr  r~   r9   r   r   )r`   r   r   r  r  r\   slicer  Zloss_functionr  r  r   r   r   r  r5   r   r   r~   r9   r   )r*   r  r   r   r~   r  r   r   r   r   r!  r   outputsr9   Zslice_indicesr  r"  r#  r/   r/   r0   r:   ;  sN    (	zMiniMaxForCausalLM.forward)
NNNNNNNNNr   )r?   r@   rA   Z_tied_weights_keysZ_tp_planZ_pp_planr%   r   r   r   r'   r   r]   r	   r   r   r   r\   r   r   r   r:   rB   r/   r/   r-   r0   r  )  s<             r  c                   @   s   e Zd ZdS ) MiniMaxForSequenceClassificationNr?   r@   rA   r/   r/   r/   r0   r&    s   r&  c                   @   s   e Zd ZdS )MiniMaxForTokenClassificationNr'  r/   r/   r/   r0   r(    s   r(  c                   @   s   e Zd ZdS )MiniMaxForQuestionAnsweringNr'  r/   r/   r/   r0   r)    s   r)  )r   r  r  r&  r(  r)  )Nr    )r   )Nr1   N)Ltypingr   r   r   r'   Ztorch.nn.functionalr   r   r   Ztransformers.utils.genericr   Zactivationsr   Zcache_utilsr	   r
   Z
generationr   Zintegrationsr   Zmasking_utilsr   r   Zmodeling_flash_attention_utilsr   Zmodeling_layersr   r   r   r   Zmodeling_outputsr   r   Zmodeling_rope_utilsr   r   Zmodeling_utilsr   r   Zprocessing_utilsr   utilsr   r   r   Zutils.deprecationr   Zutils.genericr   Zconfiguration_minimaxr!   Moduler"   rC   r^   r   r   r]   r\   r   r|   r   r   r   r   r   r   r   r  r;   r  r  r&  r(  r)  __all__r/   r/   r/   r0   <module>   s|   . 
 ?CZ$_   Rh