
    rhI                        d Z ddlmZmZ ddlZddlmc mZ ddl	ZddlmZ ddl
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 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"m#Z#m$Z$m%Z%m&Z&m'Z' ddl(m)Z)  ejT                  e+      Z,	 	 	 d0deejZ                  e.ejZ                     df   dee/   deejZ                     deejZ                  e/f   fdZ0 G d dejb                        Z2 G d dejb                        Z3 G d de&      Z4 G d de      Z5 G d d e      Z6 G d! d"e'      Z7 G d# d$e%      Z8 G d% d&e$      Z9 G d' d(e       Z: G d) d*e"      Z; G d+ d,e#      Z< G d- d.e!      Z=g d/Z>y)1zPyTorch Mixtral model.    )OptionalUnionN)nn   )ACT2FN)CacheDynamicCache)create_causal_mask!create_sliding_window_causal_mask)GradientCheckpointingLayer)MoeCausalLMOutputWithPastMoeModelOutputWithPast)Unpack)TransformersKwargslogging)OutputRecorder   )	MistralAttentionMistralForCausalLMMistralForQuestionAnswering MistralForSequenceClassificationMistralForTokenClassificationMistralModelMistralPreTrainedModelMistralRMSNormMistralRotaryEmbedding   )MixtralConfiggate_logitsnum_expertsattention_maskreturnc                    | 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   dim)
isinstancetupledevicetorchcattor   
functionalsoftmaxtopkone_hotmeanfloatshapeexpandreshapesum	unsqueeze)r   r    top_kr!   compute_device
layer_gateconcatenated_gate_logitsrouting_weights_selected_expertsexpert_masktokens_per_expertrouter_prob_per_expert
batch_sizesequence_lengthnum_hidden_layersexpert_attention_mask router_per_expert_attention_maskoverall_losss                      ~/var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/transformers/models/mixtral/modular_mixtral.pyload_balancing_loss_funcrI   6   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                   *     e Zd Zdef fdZd Z xZS )MixtralBlockSparseTop2MLPconfigc                    t         |           |j                  | _        |j                  | _        t        j                  | j
                  | j                  d      | _        t        j                  | j                  | j
                  d      | _	        t        j                  | j
                  | j                  d      | _
        t        |j                     | _        y NF)bias)super__init__intermediate_sizeffn_dimhidden_size
hidden_dimr   Linearw1w2w3r   
hidden_actact_fnselfrL   	__class__s     rH   rQ   z"MixtralBlockSparseTop2MLP.__init__   s    // ,,))DOOT\\F))DLL$//F))DOOT\\FV../    c                     | j                  | j                  |            | j                  |      z  }| j                  |      }|S N)r[   rW   rY   rX   )r]   hidden_statescurrent_hidden_statess      rH   forwardz!MixtralBlockSparseTop2MLP.forward   s>     $DGGM,B CdggmF\ \ $(= >$$r_   )__name__
__module____qualname__r   rQ   rd   __classcell__r^   s   @rH   rK   rK      s    	0} 	0%r_   rK   c                   Z     e Zd ZdZ fdZdej                  dej                  fdZ x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                    t         |           |j                  | _        |j                  | _        |j                  | _        |j                  | _	        t        j                  | j                  | j                  d      | _        t        j                  t        | j                        D cg c]  }t        |       c}      | _        |j"                  | _        y c c}w rN   )rP   rQ   rT   rU   rR   rS   num_local_expertsr    num_experts_per_tokr8   r   rV   gate
ModuleListrangerK   expertsrouter_jitter_noisejitter_noise)r]   rL   r=   r^   s      rH   rQ   zMixtralSparseMoeBlock.__init__   s     ,,//!33//
 IIdoot/?/?eL	}}QVW[WgWgQh%iA&?&G%ij #66 &js   +Crb   r"   c                    |j                   \  }}}| j                  rQ| j                  dkD  rB|t        j                  |      j                  d| j                  z
  d| j                  z         z  }|j                  d|      }| j                  |      }t        j                  |dt        j                        }t        j                  || j                  d      \  }}||j                  dd      z  }|j                  |j                        }t        j                   ||z  |f|j                  |j"                  	      }t        j$                  j&                  j)                  || j*                  
      j-                  ddd      }	t        j.                  |	j                  d      d      j1                         }
|
D ]  }| j2                  |   }t        j4                  |	|   j7                  d            \  }}|d|f   j9                  d|      } ||      |||df   z  }|j;                  d||j                  |j                                |j9                  |||      }||fS ) r   g      ?r&   r   )r%   dtyper$   T)r%   keepdim)rw   r)   )num_classesr   )r&   N)r3   trainingrt   r*   
empty_likeuniform_viewro   Fr.   r2   r/   r8   r6   r,   rw   zerosr)   r   r-   r0   r    permutegreaternonzerorr   wheresqueezer5   
index_add_)r]   rb   rB   rC   rU   router_logitsr<   r>   final_hidden_statesr?   expert_hitted
expert_idxexpert_layeridxtop_xcurrent_staterc   s                    rH   rd   zMixtralSparseMoeBlock.forward   s7   2?2E2E/
OZ==T..2U--m<EEcDL]L]F]_beievev_vwwM%**2z:		-0))MqL,1JJ

XZ,[))?..2t.DD),,]-@-@A#kk/):6m>Q>QZgZnZn
 hh))112BPTP`P`1aiijkmnpqrkoo(o&CQGOOQ' 	dJ<<
3L[%<%D%DQ%GHJC *$+6>>r:NM$0$?/RWY\^bRbBc$c!  **1e5J5M5MmNaNa5bc	d 299*oWab"M11r_   )	re   rf   rg   __doc__rQ   r*   Tensorrd   rh   ri   s   @rH   rk   rk      s(    	7%2U\\ %2ell %2r_   rk   c                       e Zd Zy)MixtralRMSNormNre   rf   rg    r_   rH   r   r          r_   r   c                       e Zd Zy)MixtralAttentionNr   r   r_   rH   r   r      r   r_   r   c                   (    e Zd Zdedef fdZ	 	 	 	 ddej                  deej                  ej                  f   de	ej                     de	ej                     de	eej                        d	e	ej                     d
ee   dej                  fdZ xZS )MixtralDecoderLayerrL   	layer_idxc                    t         |           |j                  | _        t        ||      | _        t        |      | _        t        |j                  |j                        | _	        t        |j                  |j                        | _
        y )N)eps)rP   rQ   rT   r   	self_attnrk   block_sparse_moer   rms_norm_epsinput_layernormpost_attention_layernorm)r]   rL   r   r^   s      rH   rQ   zMixtralDecoderLayer.__init__   sm    !--)&)< 5f =-f.@.@fFYFYZ(6v7I7IvObOb(c%r_   rb   position_embeddingsr!   position_idspast_key_valuecache_positionkwargsr"   c           
          |}| j                  |      } | j                  d||||||d|\  }}	||z   }|}| j                  |      }| j                  |      \  }}	||z   }|S )N)rb   r   r!   r   r   r   r   )r   r   r   r   )
r]   rb   r   r!   r   r   r   r   residualr=   s
             rH   rd   zMixtralDecoderLayer.forward   s     !,,]; *4>> 
' 3)%))
 
q !=0 !55mD00?q =0r_   )NNNN)re   rf   rg   r   intrQ   r*   r   r(   r   
LongTensorr   r   FloatTensorrd   rh   ri   s   @rH   r   r      s    d} d d 26378<59 ||  #5<<#=>  !.	 
 u//0  !u||!45  !!1!12  +,  
		 r_   r   c                       e Zd Zy)MixtralRotaryEmbeddingNr   r   r_   rH   r   r     r   r_   r   c                   ,    e Zd ZdZ eed      eedZy)MixtralPreTrainedModelFr   )index)r   rb   
attentionsN)	re   rf   rg   _can_compile_fullgraphr   rk   r   r   _can_record_outputsr   r_   rH   r   r     s!    "'(=QG,&r_   r   c                       e Zd Z	 	 	 	 	 	 	 ddeej
                     deej                     deej
                     dee   deej                     dee	   deej
                     d	e
e   d
efdZy)MixtralModelN	input_idsr!   r   past_key_valuesinputs_embeds	use_cacher   r   r"   c                 j   |d u |d uz  rt        d      |r|
t               }|| j                  |      }|F||j                         nd}	t	        j
                  |	|	|j                  d   z   |j                        }||j                  d      }| j                  j                  t        nt        }
 |
| j                  |||||      }|}| j                  ||      }| j                  d | j                  j                   D ]  } ||f||||||d|} | j!                  |      }t#        ||      S )Nz:You must specify exactly one of input_ids or inputs_embedsr   r   )r)   )rL   input_embedsr!   r   r   r   )r   r!   r   r   r   r   )last_hidden_stater   )
ValueErrorr	   embed_tokensget_seq_lengthr*   aranger3   r)   r7   rL   sliding_windowr
   r   
rotary_emblayersrD   normr   )r]   r   r!   r   r   r   r   r   r   past_seen_tokensmask_functioncausal_maskrb   r   decoder_layers                  rH   rd   zMixtralModel.forward!  sq    -t";<YZZ0*nO  --i8M!CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L.2kk.H.H.P*Vw#;;&))+%
 & #oom\J![[)H4;;+H+HI 
	M)	$7*).#-	 	M
	 		-0%++
 	
r_   )NNNNNNN)re   rf   rg   r   r*   r   r   r   r   boolr   r   r   rd   r   r_   rH   r   r      s     151537+/59$(59<
E,,-<
 !.<
 u//0	<

 "%<
   1 12<
 D><
 !!1!12<
 +,<
 
 <
r_   r   c                   D    e Zd ZdgZ fdZ	 	 	 	 	 	 	 	 	 	 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j                     deeej                  f   dee   defdZ xZS )MixtralForCausalLMzlm_head.weightc                     t         |   |       t        |      | _        |j                  | _        |j
                  | _        |j                  | _        y ra   )rP   rQ   r   modelrouter_aux_loss_coefrm   r    rn   r\   s     rH   rQ   zMixtralForCausalLM.__init__c  sF     !&)
$*$?$?!!33#)#=#= r_   r   r!   r   r   r   labelsr   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, 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   )lossaux_losslogitsr   rb   r   r   r   )rL   r   r   r   r'   r   slicelm_headloss_function
vocab_sizerI   r   r    rn   r   r,   r)   r   r   rb   r   )r]   r   r!   r   r   r   r   r   r   r   r   r   outputsrb   slice_indicesr   r   r   s                     rH   rd   zMixtralForCausalLM.forwardj  sX   L %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!//))!//
 	
r_   )
NNNNNNNNNr   )re   rf   rg   _tied_weights_keysrQ   r   r*   r   r   r   r   r   r   r   r   r   r   rd   rh   ri   s   @rH   r   r   `  s   *+> 151537+/59-1$(/35934R
E,,-R
 !.R
 u//0	R

 "%R
   1 12R
 ))*R
 D>R
 'tnR
 !!1!12R
 c5<</0R
 +,R
 
#R
r_   r   c                       e Zd Zy) MixtralForSequenceClassificationNr   r   r_   rH   r   r     r   r_   r   c                       e Zd Zy)MixtralForTokenClassificationNr   r   r_   rH   r   r     r   r_   r   c                       e Zd Zy)MixtralForQuestionAnsweringNr   r   r_   rH   r   r     r   r_   r   )r   r   r   r   r   r   )Nr   N)?r   typingr   r   r*   torch.nn.functionalr   r-   r   torch.utils.checkpointactivationsr   cache_utilsr   r	   masking_utilsr
   r   modeling_layersr   modeling_outputsr   r   processing_utilsr   utilsr   r   utils.genericr   mistral.modeling_mistralr   r   r   r   r   r   r   r   r   configuration_mixtralr   
get_loggerre   loggerr   r(   r   rI   ModulerK   rk   r   r   r   r   r   r   r   r   r   r   __all__r   r_   rH   <module>r      sy  (  "      ! . R 9 Q & 0 +
 
 
 1 
		H	%
 "&
-1	O&u||U5<<%8$>?O&#O& U\\*	O&
 5<<O&d%		 %$@2BII @2F	^ 		' 	+4 +\	3 	3 =
< =
@\
+ \
~	'G 		$A 		"= 	r_   