
    Pic              *       t   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
mZ d dlmZ d dlmZmZmZ 	 	 	 	 d-d	ed
ededededededededede
fdZd.dedededefdZ	 	 d/ddddddddee         deded	ed
ededededededededededed ed!edede
f&d"Zdddddd#d$ee         dedededededededed ed!ededefd%Zdddd&dedededed ed!ededefd'Zdddd(d)ed	ed
ededededededededede
fd*Z	 	 d/ddddddddee         deded)ed	ed
ededededededededededed ed!edede
f(d+Zd,S )0    )List)nn)FeedForwardFrozenNF4LinearMultiHeadAttentionRMSNormRotaryPositionalEmbeddingsTransformerDecoderTransformerSelfAttentionLayer)(_register_reparametrize_state_dict_hooks)
DoRALinearLORA_ATTN_MODULES
LoRALinear        h㈵>'  
vocab_size
num_layers	num_headsnum_kv_heads	embed_dimintermediate_dimmax_seq_lenattn_dropoutnorm_eps	rope_basereturnc
                    ||z  }
|r|n|}t          |
||	          }t          j                    }t          |          D ]}t	          ||||
t          j        |||
z  d          t          j        |||
z  d          t          j        |||
z  d          t          j        ||d          |d||          }t          ||          }t          ||t          ||          t          ||                    }|	                    |           t          j
        | |          }t          j        || d          }t          |||||
t          ||	          |
          S )a  
    Build the decoder associated with the mistral model. This includes:
    - Token embeddings
    - num_layers number of TransformerSelfAttentionLayer blocks
    - RMS Norm layer applied to the output of the transformer
    - Final projection into token space

    This does NOT currently include inference-time optimizations such as
    sliding-window attention

    Args:
        vocab_size (int): number of tokens in vocabulary.
        num_layers (int): number of layers in the transformer decoder.
        num_heads (int): number of query heads. For MHA this is also the
            number of heads for key and value
        num_kv_heads (int): number of key and value heads. User should ensure
            `num_heads` % `num_kv_heads` == 0. For standard MHA set `num_kv_heads` == `num_heads`,
            for GQA `num_kv_heads` < `num_heads`, and for MQA set `num_kv_heads` == 1.
        embed_dim (int): embedding dimension for self-attention
        intermediate_dim (int): intermediate dimension for MLP
        max_seq_len (int): maximum sequence length the model will be run with,
        attn_dropout (float): dropout value passed onto scaled_dot_product_attention.
            Default: 0.0
        norm_eps (float): epsilon in RMS norms
        rope_base (int): base for the rotary positional embeddings. Default: 10_000

    Returns:
        TransformerDecoder: Instantiation of mistral model.
    dimr   baseFbiasNr   r   r   head_dimq_projk_projv_projoutput_projpos_embeddingskv_cacher   r   r    
hidden_dimr    epsattnmlpsa_normmlp_normr/   tok_embeddingslayersr   r   r%   normoutputr	   r   
ModuleListranger   Linearmistral_mlpr   r   append	Embeddingr
   )r   r   r   r   r   r   r   r   r   r   r%   roper8   _	self_attnr2   layerr7   r)   s                      /home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/torchtune/models/mistral/_component_builders.pymistralrG   %   s   R I%H#/><<YL%+I  D ]__F:  &%9Y	H(<5III9Yx(?eLLL9Yx(?eLLL	)YUCCC#%
 
 
	 i4DEEE-	x888999	
 
 
 	e\*i88N)Iz>>>K%YH---       Fr    r-   quantize_basec                 (   |st          j        | |d          nt          | |d          }|st          j        || d          nt          || d          }|st          j        | |d          nt          | |d          }t          |||          S )z@
    Build the MLP layer associated with the Mistral model.
    Fr"   	gate_proj	down_projup_proj)r   r>   r   r   )r    r-   rI   rL   rM   rN   s         rF   r?   r?   z   s     	:	#z....S*5999  	:	*c....Z5999  	:	#z....S*5999 
 iQQQQrH   )r   r   r   lora_dropoutuse_dorarI   lora_attn_modulesapply_lora_to_mlpapply_lora_to_output	lora_rank
lora_alpharO   rP   c                   t          j                    }t          |          D ]}t          | |||||
||||||          }|rt	          ||	|||||          }nt          ||	|          }t          ||t          ||          t          ||                    }|                    |           t          j	        ||          }|rt          nt          }|r |||||          nt          j        ||d          }t          ||||||z  t          ||	          |
          }|rt          ||j        j                   |S )ag	  
    Return a version of Mistral (an instance of :func:`~torchtune.modules.TransformerDecoder`)
    with LoRA applied based on the passed in configuration.

    Args:
        lora_attn_modules (List[LORA_ATTN_MODULES]): list of which linear layers
            LoRA should be applied to in each self-attention block. Options are
            ``{"q_proj", "k_proj", "v_proj", "output_proj"}``.
        apply_lora_to_mlp (bool): whether to apply LoRA to the MLP in each transformer layer.
            Default: False
        apply_lora_to_output (bool): whether to apply LoRA to the model's final output projection.
            Default: False
        vocab_size (int): number of tokens in vocabulary.
        num_layers (int): number of layers in the transformer decoder.
        num_heads (int): number of query heads. For MHA this is also the
            number of heads for key and value
        num_kv_heads (int): number of key and value heads. User should ensure
            `num_heads` % `num_kv_heads` == 0. For standard MHA set `num_kv_heads` == `num_heads`,
            for GQA `num_kv_heads` < `num_heads`, and for MQA set `num_kv_heads` == 1.
        embed_dim (int): embedding dimension for self-attention
        max_seq_len (int): maximum sequence length the model will be run with
        intermediate_dim (int): intermediate dimension for MLP.
        attn_dropout (float): dropout value passed onto scaled_dot_product_attention.
            Default: 0.0
        norm_eps (float): epsilon in RMS norms.
        rope_base (int): base for the rotary positional embeddings. Default: 10_000
        lora_rank (int): rank of each low-rank approximation
        lora_alpha (float): scaling factor for the low-rank approximation
        lora_dropout (float): LoRA dropout probability. Default: 0.0
        use_dora (bool): Decompose the LoRA weight into magnitude and direction, as
            introduced in "DoRA: Weight-Decomposed Low-Rank Adaptation" (https://arxiv.org/abs/2402.09353).
        quantize_base: (bool): Whether to quantize base model weights or not. Only applied to base
            weights within linear layers LoRA is applied to. The final output linear projection is not
            supported for quantization currently.

    Returns:
        TransformerDecoder: Instantiation of Mistral model with LoRA applied to
        a subset of the attention projections in each layer.

    lora_modulesr   r   r   r   r   r   rT   rU   rO   rP   rI   r    r-   rT   rU   rO   rP   rI   )r    r-   rI   r.   r0   )rankalphaFr"   r5   r6   dtyper   r<   r=   lora_mistral_self_attentionlora_mistral_mlpr?   r   r   r@   rA   r   r   r>   r
   r   weightr]   )rQ   rR   rS   r   r   r   r   r   r   r   r   r   r   rT   rU   rO   rP   rI   r8   rC   rD   r2   rE   r7   adapter_clsr)   models                              rF   lora_mistralrd      s   ~ ]__F: % %/*%#%!%'
 
 
	  	"+#%)!+  CC *:-  C .	x888999	
 
 
 	e\*i88N !)8**jK  	:Iz	LLLLYy*5999 
 %y(YH---  E  [
 	1n>S>YZZZZLrH   )r   r   rO   rP   rI   rX   c                   | st          dt           d          ||z  }|r|n|}|
rt          nt          }d| v r ||||z  |||	|          n0|st	          j        |||z  d          nt          |||z  d          }d| v r ||||z  |||	|          n0|st	          j        |||z  d          nt          |||z  d          }d| v r ||||z  |||	|          n0|st	          j        |||z  d          nt          |||z  d          }d	| v r ||||||	|          n*|st	          j        ||d          nt          ||d          }t          |||
          }t          |||||||||||          }|S )a  
    Return an instance of :func:`~torchtune.modules.MultiHeadAttention` with LoRA
    applied to a subset of its linear layers

    Args:
        lora_modules (List[LORA_ATTN_MODULES]): list of which linear layers
            LoRA should be applied to. Options are ``{"q_proj", "k_proj", "v_proj",
            "output_proj"}``.
        embed_dim (int): embedding dimension for self-attention
        num_heads (int): number of query heads. For MHA this is also the
            number of heads for key and value
        num_kv_heads (int): number of key and value heads. User should ensure
            `num_heads` % `num_kv_heads` == 0. For standard MHA set `num_kv_heads` == `num_heads`,
            for GQA `num_kv_heads` < `num_heads`, and for MQA set `num_kv_heads` == 1.
        max_seq_len (int): maximum sequence length the model will be run with
        attn_dropout (float): dropout value passed onto scaled_dot_product_attention.
            Default: 0.0
        rope_base (int): base for the rotary positional embeddings. Default: 10_000
        lora_rank (int): rank of each low-rank approximation
        lora_alpha (float): scaling factor for the low-rank approximation
        lora_dropout (float): LoRA dropout probability. Default: 0.0
        use_dora (bool): Decompose the LoRA weight into magnitude and direction, as
            introduced in "DoRA: Weight-Decomposed Low-Rank Adaptation" (https://arxiv.org/abs/2402.09353).
        quantize_base (bool): Whether to quantize base model parameters for linear layers
            LoRA is being applied to. Default is ``False``.

    Returns:
        MultiHeadAttention: instantiation of self-attention module with LoRA
        applied to a subset of Q, K, V, output projections.

    Raises:
        ValueError: If lora_modules arg is an empty list
    zMust pass one or more of z as lora_modulesr&   )rZ   r[   dropoutrI   Fr"   r'   r(   r)   r   )r   r   r   r%   r&   r'   r(   r)   r*   r   r   )	
ValueErrorr   r   r   r   r>   r   r	   r   )rX   r   r   r   r   r   r   rT   rU   rO   rP   rI   r%   rb   r&   r'   r(   r)   rB   rD   s                       rF   r_   r_     s   d  
K(9KKK
 
 	
 I%H#/><<YL (8**jK |## 	  '	
 	
 	
 	
 !NBIiX!5EBBBB I,@uMMM 2 |## 	8# '	
 	
 	
 	
 !QBIi!8uEEEE L8,C%PPP 2 |## 	8# '	
 	
 	
 	
 !QBIi!8uEEEE L8,C%PPP 2 L(( 	 '	
 	
 	
 	
 !CBIi7777 IEBBB   &+I  D #!!  I rH   )rO   rP   rI   c                     |rt           nt          } || |||||          } ||| ||||          }	 || |||||          }
t          ||	|
          S )N)in_dimout_dimrZ   r[   rf   rI   rK   )r   r   r   )r    r-   rT   rU   rO   rP   rI   rb   rL   rM   rN   s              rF   r`   r`     s     !)8**jK#  I #  I k#  G    rH   )r   r   r   num_classesc       
            ||z  }|r|n|}t          |||
          }t          j                    }t          |          D ]}t	          ||||t          j        |||z  d          t          j        |||z  d          t          j        |||z  d          t          j        ||d          |d||          }t          ||          }t          ||t          ||	          t          ||	                    }|	                    |           t          j
        ||          }t          j        || d          }t          |||||t          ||		          |
          S )a*  
    Build a base mistral model with an added classification layer.
    See :func:`~torchtune.models.mistral.mistral_classifier`
    for details on the base mistral classifier model.

    Args:
        num_classes (int): number of classes for the classification layer.
        vocab_size (int): number of tokens in vocabulary.
        num_layers (int): number of layers in the transformer decoder.
        num_heads (int): number of query heads. For MHA this is also the
            number of heads for key and value
        num_kv_heads (int): number of key and value heads. User should ensure
            `num_heads` % `num_kv_heads` == 0. For standard MHA set `num_kv_heads` == `num_heads`,
            for GQA `num_kv_heads` < `num_heads`, and for MQA set `num_kv_heads` == 1.
        embed_dim (int): embedding dimension for self-attention
        intermediate_dim (int): intermediate dimension for MLP
        max_seq_len (int): maximum sequence length the model will be run with,
        attn_dropout (float): dropout value passed onto scaled_dot_product_attention.
            Default: 0.0
        norm_eps (float): epsilon in RMS norms
        rope_base (int): base for the rotary positional embeddings. Default: 10_000

    Returns:
        TransformerDecoder: Instantiation of mistral classification model.
    r   Fr"   Nr$   r,   r.   r0   r5   r6   r;   )rk   r   r   r   r   r   r   r   r   r   r   r%   rB   r8   rC   rD   r2   rE   r7   r)   s                       rF   mistral_classifierrm     s   P I%H#/><<YL%+I  D ]__F:  &%9Y	H(<5III9Yx(?eLLL9Yx(?eLLL	)YUCCC#%
 
 
	 i4DEEE-	x888999	
 
 
 	e\*i88N)I{???K%YH---   rH   c                   t          j                    }t          |          D ]}t          | ||||	|||||||          }|rt	          ||
|||||          }nt          ||
          }t          ||t          ||          t          ||                    }|                    |           t          j	        ||          }|rt          nt          }|r ||||||          nt          j        ||d          }t          |||	|||z  t          ||	          |
          }|rt          ||j        j                   |S )a	  
    Return a version of Mistral classifier (an instance of :func:`~torchtune.modules.TransformerDecoder`)
    with LoRA applied to some of the linear layers in its self-attention modules.

    Args:
        lora_attn_modules (List[LORA_ATTN_MODULES]): list of which linear layers
            LoRA should be applied to in each self-attention block. Options are
            ``{"q_proj", "k_proj", "v_proj", "output_proj"}``.
        apply_lora_to_mlp (bool): whether to apply LoRA to the MLP in each transformer layer.
            Default: False
        apply_lora_to_output (bool): whether to apply LoRA to the model's final output projection.
            Default: False
        num_classes (int): number of classes for the classification layer.
        vocab_size (int): number of tokens in vocabulary.
        num_layers (int): number of layers in the transformer decoder.
        num_heads (int): number of query heads. For MHA this is also the
            number of heads for key and value
        num_kv_heads (int): number of key and value heads. User should ensure
            `num_heads` % `num_kv_heads` == 0. For standard MHA set `num_kv_heads` == `num_heads`,
            for GQA `num_kv_heads` < `num_heads`, and for MQA set `num_kv_heads` == 1.
        embed_dim (int): embedding dimension for self-attention
        max_seq_len (int): maximum sequence length the model will be run with
        intermediate_dim (int): intermediate dimension for MLP.
        attn_dropout (float): dropout value passed onto scaled_dot_product_attention.
            Default: 0.0
        norm_eps (float): epsilon in RMS norms.
        rope_base (int): base for the rotary positional embeddings. Default: 10_000
        lora_rank (int): rank of each low-rank approximation
        lora_alpha (float): scaling factor for the low-rank approximation
        lora_dropout (float): LoRA dropout probability. Default: 0.0
        use_dora (bool): Decompose the LoRA weight into magnitude and direction, as
            introduced in "DoRA: Weight-Decomposed Low-Rank Adaptation" (https://arxiv.org/abs/2402.09353).
        quantize_base: (bool): Whether to quantize base model weights or not. Only applied to base
            weights within linear layers LoRA is applied to. The final output linear projection is not
            supported for quantization currently.

    Returns:
        TransformerDecoder: Instantiation of Mistral classifier model with LoRA applied to
        a subset of the attention projections in each layer.

    rW   rY   r,   r.   r0   )rZ   r[   rf   Fr"   r5   r6   r\   r^   )rQ   rR   rS   rk   r   r   r   r   r   r   r   r   r   r   rT   rU   rO   rP   rI   r8   rC   rD   r2   rE   r7   rb   r)   rc   s                               rF   lora_mistral_classifierro      s   D ]__F: # #/*%#%!%'
 
 
	  	J"+#%)!+  CC )8HIIIC-	x888999	
 
 
 	e\*i88N !)8**jK  	; 	
 	
 	
 	
 Yy+E:::  %y(YH---  E  [
 	1n>S>YZZZZLrH   N)r   r   r   )F)FF)typingr   torchr   torchtune.modulesr   r   r   r   r	   r
   r   torchtune.modules.common_utilsr   torchtune.modules.peftr   r   r   intfloatrG   boolr?   rd   r_   r`   rm   ro    rH   rF   <module>ry      s                                T S S S S S L L L L L L L L L L
* R RRR R 	R
 R R R R R R R R R RjR RS Rc R$ R; R R R R0 $!&A  +A A A-.AA A A A A A A A A A A A" #A$ %A& 'A( )A* +A, -A A A AX  K K K()K 	K
 K K K K K K K K K K  !K K K Kh ' ' '	' ' 	'
 ' ' ' ' ' ' ' 'j Q Q QQ 	Q
 Q Q Q Q Q Q Q Q Q Q Q Q Ql $!&H  /H H H-.HH H H H H H H H H H H  !H" #H& 'H( )H* +H, -H. /H0 1H H H H H HrH   