o
    wiB                     @   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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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' ddl(m)Z)m*Z*m+Z+m,Z, ddl-m.Z. e,/e0Z1G dd dej2Z3G dd dej2Z4edG dd dej2Z5dd Z6dIddZ7dej8de9d ej8fd!d"Z:	#dJd$ej2d%ej8d&ej8d'ej8d(eej8 d)e;d*e;fd+d,Z<G d-d. d.ej2Z=G d/d0 d0eZ>G d1d2 d2ej2Z?e*G d3d4 d4e%Z@e*G d5d6 d6e@ZAG d7d8 d8ee)ZB		9	dKd:eej8eCej8 df d;ee9 d(eej8 d eej8e9f fd<d=ZDe*G d>d? d?e@eZEe*d@dAG dBdC dCe@ZFe*G dDdE dEe@ZGe*G dFdG dGe@ZHg dHZIdS )L    )CallableOptionalUnionN)nn   )ACT2FN)CacheDynamicCache)GenerationMixin)use_kernel_forward_from_hub)create_causal_mask!create_sliding_window_causal_mask)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutputWithPastMoeCausalLMOutputWithPastMoeModelOutputWithPastQuestionAnsweringModelOutput SequenceClassifierOutputWithPastTokenClassifierOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)
LossKwargsauto_docstringcan_return_tuplelogging   )MixtralConfigc                       s*   e Zd Zdef fddZdd Z  ZS )MixtralBlockSparseTop2MLPconfigc                    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 NFbias)super__init__intermediate_sizeffn_dimhidden_size
hidden_dimr   Linearw1w2w3r   
hidden_actact_fnselfr"   	__class__ i/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/transformers/models/mixtral/modeling_mixtral.pyr'   ;   s   
z"MixtralBlockSparseTop2MLP.__init__c                 C   s(   |  | || | }| |}|S N)r1   r-   r/   r.   )r3   hidden_statescurrent_hidden_statesr6   r6   r7   forwardF   s   
z!MixtralBlockSparseTop2MLP.forward)__name__
__module____qualname__r    r'   r;   __classcell__r6   r6   r4   r7   r!   :   s    r!   c                       s6   e Zd ZdZ fddZdejdejfddZ  ZS )MixtralSparseMoeBlocka  
    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 )NFr$   c                    s   g | ]}t  qS r6   )r!   ).0_r"   r6   r7   
<listcomp>b   s    z2MixtralSparseMoeBlock.__init__.<locals>.<listcomp>)r&   r'   r*   r+   r(   r)   num_local_expertsnum_expertsnum_experts_per_toktop_kr   r,   gate
ModuleListrangeexpertsrouter_jitter_noisejitter_noiser2   r4   rC   r7   r'   X   s   
 zMixtralSparseMoeBlock.__init__r9   returnc                 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 ]3}| j| }t|	| d\}}|d|f d|}|||||df  }|d|||j qx||||}||fS ) r         ?r   dimdtyperT   T)rT   keepdim)rU   device)num_classes   )rR   N)shapetrainingrN   torch
empty_likeuniform_viewrI   FsoftmaxfloattopkrH   sumtorU   zerosrX   r   
functionalone_hotrF   permutegreaternonzerorL   wheresqueezereshape
index_add_)r3   r9   
batch_sizesequence_lengthr+   router_logitsrouting_weightsselected_expertsfinal_hidden_statesexpert_maskexpert_hitted
expert_idxexpert_layeridxtop_xcurrent_stater:   r6   r6   r7   r;   g   s,   "

zMixtralSparseMoeBlock.forward)	r<   r=   r>   __doc__r'   r^   Tensorr;   r?   r6   r6   r4   r7   r@   L   s    r@   RMSNormc                       s.   e Zd Zd fdd	Zdd Zdd Z  ZS )	MixtralRMSNormư>c                    s&   t    tt|| _|| _dS )z=
        MixtralRMSNorm is equivalent to T5LayerNorm
        N)r&   r'   r   	Parameterr^   onesweightvariance_epsilon)r3   r*   epsr4   r6   r7   r'      s   

zMixtralRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )NrZ   rR   T)rW   )	rU   rg   r^   float32powmeanrsqrtr   r   )r3   r9   input_dtypevariancer6   r6   r7   r;      s
   zMixtralRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)tupler   r\   r   r3   r6   r6   r7   
extra_repr   s   zMixtralRMSNorm.extra_repr)r   )r<   r=   r>   r'   r;   r   r?   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..NrR   rZ   rV   )r\   r^   cat)xx1x2r6   r6   r7   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.
    )	unsqueezer   )qkcossinposition_idsunsqueeze_dimq_embedk_embedr6   r6   r7   apply_rotary_pos_emb   s
   

r   r9   n_reprO   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\   expandrp   )r9   r   batchnum_key_value_headsslenhead_dimr6   r6   r7   	repeat_kv   s
   0r           modulequerykeyvalueattention_maskscalingdropoutc                 K   s   t || j}t || j}	t||dd| }
|d ur3|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 )NrZ   r   r[   rR   rS   )pr]   r   )r   num_key_value_groupsr^   matmul	transposer\   r   ri   rc   r   rg   rU   r   r]   
contiguous)r   r   r   r   r   r   r   kwargs
key_statesvalue_statesattn_weightscausal_maskattn_outputr6   r6   r7   eager_attention_forward   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
ej d
e
e de
ej dee de	eje
ej e
e	ej  f fddZ  ZS )MixtralAttentionz=Multi-headed attention from 'Attention Is All You Need' paperr"   	layer_idxc                    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 )Nr   g      TFr$   )r&   r'   r"   r   getattrr*   num_attention_headsr   r   r   r   attention_dropout	is_causalr   r,   q_projk_projv_projo_projr3   r"   r   r4   r6   r7   r'      s   
 zMixtralAttention.__init__Nr9   position_embeddingsr   past_key_valuecache_positionr   rO   c                 K   s0  |j d d }g |d| jR }| ||dd}	| ||dd}
| ||dd}|\}}t|	|
||\}	}
|d urW|||d}||
|| j	|\}
}t
}| jjdkret| jj }|| |	|
||f| jsqdn| j| jt| jdd d|\}}|jg |dR   }| |}||fS )	NrR   r   rZ   )r   r   r   eagerr   sliding_window)r   r   r   )r\   r   r   ra   r   r   r   r   updater   r   r"   _attn_implementationr   r]   r   r   r   rp   r   r   )r3   r9   r   r   r   r   r   input_shapehidden_shapequery_statesr   r   r   r   cache_kwargsattention_interfacer   r   r6   r6   r7   r;      s:   		

zMixtralAttention.forward)NN)r<   r=   r>   r   r    intr'   r^   r   r   r   r   
LongTensorr   r   r;   r?   r6   r6   r4   r7   r      s(    r   c                       s   e Zd Zdedef fddZ								ddejdeej d	eej	 d
ee
ej  dee dee dee deej	 dee
ejejf  dee de
ejee
ejejf  f fddZ  ZS )MixtralDecoderLayerr"   r   c                    sP   t    |j| _t||| _t|| _t|j|jd| _	t|j|jd| _
d S )Nr   )r&   r'   r*   r   	self_attnr@   block_sparse_moer   rms_norm_epsinput_layernormpost_attention_layernormr   r4   r6   r7   r'   +  s   

zMixtralDecoderLayer.__init__NFr9   r   r   r   output_attentionsoutput_router_logits	use_cacher   r   r   rO   c
                 K   s   |}|  |}| jd||	||||||d|
\}}|| }|}| |}| |\}}|| }|f}|r:||f7 }|rA||f7 }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
                `(batch, sequence_length)` where padding elements are indicated by 0.
            past_key_value (`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   Nr6   )r   r   r   r   )r3   r9   r   r   r   r   r   r   r   r   r   residualself_attn_weightsrt   outputsr6   r6   r7   r;   5  s2   #
	



zMixtralDecoderLayer.forward)NNNFFFNN)r<   r=   r>   r    r   r'   r^   r   r   r   r   boolr   r   FloatTensorr;   r?   r6   r6   r4   r7   r   *  sB    	
r   c                       s8   e Zd Zddef fddZe edd Z  Z	S )MixtralRotaryEmbeddingNr"   c                    s   t    t|dr|jd u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defaultinv_freqF)
persistent)r&   r'   hasattrr   getr   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr"   r   rope_init_fnattention_scalingregister_bufferr   original_inv_freq)r3   r"   rX   r   r4   r6   r7   r'   |  s   
zMixtralRotaryEmbedding.__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r6|jjdkr6|jjnd}t	j
|dd+ | |  dd}t	j||fdd	}| | j }| | j }	W d    n1 smw   Y  |j|jd
|	j|jd
fS )Nr   rR   r   mpscpuF)device_typeenabledrZ   rV   )rU   )r   rd   r   r\   rg   rX   
isinstancer   strr^   autocastr   r   r   r   r   rU   )
r3   r   r   inv_freq_expandedposition_ids_expandedr   freqsembr   r   r6   r6   r7   r;     s   0&zMixtralRotaryEmbedding.forwardr8   )
r<   r=   r>   r    r'   r^   no_gradr   r;   r?   r6   r6   r4   r7   r   {  s
    r   c                   @   sL   e Zd ZeZdZdZdgZdgZdZ	dZ
dZdZdZdZdZdZdd ZdS )	MixtralPreTrainedModelmodelTr   past_key_valuesFc                 C   s   | j j}t|tjr"|jjjd|d |jd ur |jj	  d S d S t|tj
rC|jjjd|d |jd urA|jj|j 	  d S d S t|trQ|jjd d S d S )Nr   )r   stdrQ   )r"   initializer_ranger   r   r,   r   datanormal_r%   zero_	Embeddingpadding_idxr   fill_)r3   r   r  r6   r6   r7   _init_weights  s   


z$MixtralPreTrainedModel._init_weightsN)r<   r=   r>   r    config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_3_supports_flash_attn_2_supports_sdpa_supports_flex_attn_supports_cache_class_supports_quantized_cache_supports_static_cache_supports_attention_backendr  r6   r6   r6   r7   r     s    r   c                       s   e Zd Zdef fddZdd Zdd Zee										dd	e	e
j d
e	e
j de	e
j de	ee
j  de	e
j de	e de	e de	e de	e de	e
j dee defddZ  ZS )MixtralModelr"   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   )rA   r   rC   r6   r7   rD         z)MixtralModel.__init__.<locals>.<listcomp>r   rC   F)r&   r'   pad_token_idr	  
vocab_sizer   r  r*   embed_tokensrJ   rK   num_hidden_layerslayersr   r   normr   
rotary_embgradient_checkpointing	post_initr2   r4   rC   r7   r'     s   zMixtralModel.__init__c                 C      | j S r8   r  r   r6   r6   r7   get_input_embeddings     z!MixtralModel.get_input_embeddingsc                 C   
   || _ d S r8   r%  r3   r   r6   r6   r7   set_input_embeddings     
z!MixtralModel.set_input_embeddingsN	input_idsr   r   r  inputs_embedsr   r   output_hidden_statesr   r   flash_attn_kwargsrO   c                 K   s  |d ur|n| j j}|	d ur|	n| j j}	|d ur|n| j j}|d ur$|n| j j}|d u |d uA r4td| jrC| jrC|rCt	d d}|rL|d u rLt
 }|d u rU| |}|
d u rq|d ura| nd}tj|||jd  |jd}
|d u rz|
d}| j jd u rtnt}|| j |||
||d}|}| ||}|rdnd }|rdnd }|	rdnd }| jD ]0}|r||f7 }||f|||||	||
|d	|}|d }|r||d f7 }|	r||d
 f7 }q| |}|r||f7 }t|||||dS )Nz:You must specify exactly one of input_ids or inputs_embedszZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   r   rX   )r"   input_embedsr   r   r  r   r6   )r   r   r   r   r   r   r   r   rR   )last_hidden_stater  r9   
attentionsrt   )r"   r   r   r.  r   
ValueErrorr"  r]   loggerwarning_oncer	   r  get_seq_lengthr^   aranger\   rX   r   r   r   r   r!  r  r   r   )r3   r,  r   r   r  r-  r   r   r.  r   r   r/  past_seen_tokensmask_functionr   r9   r   all_hidden_statesall_self_attnsall_router_logitsdecoder_layerlayer_outputsr6   r6   r7   r;     s   

	




zMixtralModel.forward)
NNNNNNNNNN)r<   r=   r>   r    r'   r&  r*  r   r   r   r^   r   r   listr   r   r   r   r   r;   r?   r6   r6   r4   r7   r    sR    	
r  c                   @   s   e Zd ZdS )KwargsForCausalLMN)r<   r=   r>   r6   r6   r6   r7   rA  @  s    rA  rZ   gate_logitsrF   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   )rg   )rA   
layer_gatecompute_devicer6   r7   rD   e  r  z,load_balancing_loss_func.<locals>.<listcomp>rV   rR   )r   r   rX   r^   r   r   ri   rc   re   rj   r   rd   r\   r   rp   rg   rf   r   )rB  rF   rH   r   concatenated_gate_logitsru   rB   rv   rx   tokens_per_expertrouter_prob_per_expertrr   rs   r  expert_attention_mask router_per_expert_attention_maskoverall_lossr6   rD  r7   load_balancing_loss_funcC  s>   



rL  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dd	 Zd
d Zdd Z	dd Z
dd Zdd Zee												d&deej deej deej deeej  deej deej dee dee dee dee d eej d!eeejf d"ee d#efd$d%Z  ZS )'MixtralForCausalLMzlm_head.weightlm_head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   r,   r*   rN  router_aux_loss_coefrE   rF   rG   r#  r2   r4   r6   r7   r'     s   
zMixtralForCausalLM.__init__c                 C      | j jS r8   r  r  r   r6   r6   r7   r&       z'MixtralForCausalLM.get_input_embeddingsc                 C      || j _d S r8   rS  r)  r6   r6   r7   r*       z'MixtralForCausalLM.set_input_embeddingsc                 C   r$  r8   rN  r   r6   r6   r7   get_output_embeddings  r'  z(MixtralForCausalLM.get_output_embeddingsc                 C   r(  r8   rW  )r3   new_embeddingsr6   r6   r7   set_output_embeddings  r+  z(MixtralForCausalLM.set_output_embeddingsc                 C   r(  r8   r  )r3   decoderr6   r6   r7   set_decoder  r+  zMixtralForCausalLM.set_decoderc                 C   r$  r8   r[  r   r6   r6   r7   get_decoder  r'  zMixtralForCausalLM.get_decoderNr   r,  r   r   r  r-  labelsr   r   r.  r   r   logits_to_keepr   rO   c                 K   s  |dur|n| j j}|
dur|
n| j j}
|	dur|	n| j j}	| jd||||||||	|
|d
|}|j}t|tr?t| dn|}| 	|dd|ddf }d}|dura| j
||| jfi |}d}|
r~t|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, MixtralForCausalLM

        >>> model = MixtralForCausalLM.from_pretrained("mistralai/Mixtral-8x7B-v0.1")
        >>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mixtral-8x7B-v0.1")

        >>> 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.  r   r   )lossaux_lossrP  r  r9   r3  rt   r6   )r"   r   r   r.  r  r2  r   r   slicerN  loss_functionr  rL  rt   rF   rG   rQ  rg   rX   r   r  r9   r3  )r3   r,  r   r   r  r-  r_  r   r   r.  r   r   r`  r   r   r9   slice_indicesrP  ra  rb  r6   r6   r7   r;     sX   )zMixtralForCausalLM.forward)NNNNNNNNNNNr   )r<   r=   r>   _tied_weights_keys_tp_plan_pp_planr'   r&  r*  rX  rZ  r]  r^  r   r   r   r^   r   r   r@  r   r   r   r   r   rA  r   r;   r?   r6   r6   r4   r7   rM    sl    	
rM  a  
    The Mixtral Model transformer with a sequence classification head on top (linear layer).

    [`MixtralForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT-2) do.

    Since it does classification on the last token, it requires to know the position of the last token. If a
    `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
    no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
    padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
    each row of the batch).
    )custom_introc                          e Zd Z fddZdd Zdd Zee									ddee	j
 d	ee	j d
ee	j
 dee dee	j dee	j
 dee dee dee defddZ  ZS ) MixtralForSequenceClassificationc                    s@   t  | |j| _t|| _tj|j| jdd| _| 	  d S r#   )
r&   r'   
num_labelsr  r  r   r,   r*   scorer#  r2   r4   r6   r7   r'   (  s
   
z)MixtralForSequenceClassification.__init__c                 C   rR  r8   rS  r   r6   r6   r7   r&  1  rT  z5MixtralForSequenceClassification.get_input_embeddingsc                 C   rU  r8   rS  r)  r6   r6   r7   r*  4  rV  z5MixtralForSequenceClassification.set_input_embeddingsNr,  r   r   r  r-  r_  r   r   r.  rO   c
              
   C   s(  | j ||||||||	d}
|
j}| |}|dur|jd }n|jd }| jjdu r2|dkr2td| jjdu r;d}n1|dur`|| jjk|jt	j
}t	j|jd |jt	j
d}|| d}nd}t| jj d |t	j||jd	|f }d}|dur| j|||| jd
}t|||
j|
j|
jdS )  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        r   r   r  r-  r   r   r.  Nr   r   z=Cannot handle batch sizes > 1 if no padding token is defined.rR   )rX   rU   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`r0  )rP  r_  pooled_logitsr"   )ra  rP  r  r9   r3  )r  r2  rm  r\   r"   r  r4  rg   rX   r^   int32r8  argmaxr5  r6  r5   r<   rd  r   r  r9   r3  )r3   r,  r   r   r  r-  r_  r   r   r.  transformer_outputsr9   rP  rr   last_non_pad_tokennon_pad_masktoken_indicesrp  ra  r6   r6   r7   r;   7  sL   


z(MixtralForSequenceClassification.forward	NNNNNNNNN)r<   r=   r>   r'   r&  r*  r   r   r   r^   r   r   r   r   r   r   r;   r?   r6   r6   r4   r7   rk    sH    		
rk  c                       rj  )MixtralForTokenClassificationc                    s|   t  | |j| _t|| _t|dd d ur|j}nt|dd d ur'|j}nd}t	|| _
t|j|j| _|   d S )Nclassifier_dropouthidden_dropoutg?)r&   r'   rl  r  r  r   ry  rz  r   Dropoutr   r,   r*   rm  r#  )r3   r"   ry  r4   r6   r7   r'     s   
z&MixtralForTokenClassification.__init__c                 C   rR  r8   rS  r   r6   r6   r7   r&    rT  z2MixtralForTokenClassification.get_input_embeddingsc                 C   rU  r8   rS  r)  r6   r6   r7   r*    rV  z2MixtralForTokenClassification.set_input_embeddingsNr,  r   r   r  r-  r_  r   r   r.  rO   c
              
   C   sd   | j ||||||||	d}
|
j}| |}| |}d}|dur(| ||| j}t|||
j|
jdS )rn  ro  N)ra  rP  r9   r3  )	r  r2  r   rm  rd  r"   r   r9   r3  )r3   r,  r   r   r  r-  r_  r   r   r.  r   sequence_outputrP  ra  r6   r6   r7   r;     s,   


z%MixtralForTokenClassification.forwardrw  )r<   r=   r>   r'   r&  r*  r   r   r   r^   r   r   r   r   r   r   r;   r?   r6   r6   r4   r7   rx  }  sH    	
rx  c                       s   e Zd ZdZ fddZdd Zdd Zee									dd	e	e
j d
e	e
j de	e
j de	eeee
j f  de	e
j de	e
j de	e
j de	e de	e defddZ  ZS )MixtralForQuestionAnsweringr  c                    s2   t  | t|jd| _t|| _|   d S )NrZ   )	r&   r'   r   r,   r*   
qa_outputsr  r  r#  r2   r4   r6   r7   r'     s   
z$MixtralForQuestionAnswering.__init__c                 C   rR  r8   rS  r   r6   r6   r7   r&    rT  z0MixtralForQuestionAnswering.get_input_embeddingsc                 C   rU  r8   rS  r)  r6   r6   r7   r*    rV  z0MixtralForQuestionAnswering.set_input_embeddingsNr,  r   r   r  r-  start_positionsend_positionsr   r.  rO   c
              	   K   s   | j |||||||	d}|j}| |}|jddd\}}|d }|d }d }|d urA|d urA| j||||fi |
}t||||j|j	dS )N)r   r   r  r-  r   r.  r   rR   rV   )ra  start_logits
end_logitsr9   r3  )
r  r2  r~  splitro   r   rd  r   r9   r3  )r3   r,  r   r   r  r-  r  r  r   r.  r   r   r|  rP  r  r  ra  r6   r6   r7   r;     s0   

z#MixtralForQuestionAnswering.forwardrw  )r<   r=   r>   r  r'   r&  r*  r   r   r   r^   r   r   r   r   r@  r   r   r   r;   r?   r6   r6   r4   r7   r}    sJ    	
r}  )rM  r}  r  r   rk  rx  )Nr   )r   )NrZ   N)Jtypingr   r   r   r^   torch.nn.functionalr   ri   rb   activationsr   cache_utilsr   r	   
generationr
   integrationsr   masking_utilsr   r   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   r   r   r   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   configuration_mixtralr    
get_loggerr<   r5  Moduler!   r@   r   r   r   r   r   r   rd   r   r   r   r   r   r  rA  r   rL  rM  rk  rx  r}  __all__r6   r6   r6   r7   <module>   s    
C

>Q" 
R VF>