o
    }oi6                     @   s   d dl mZmZ d dlmZmZmZ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 d dlmZmZ d d	lmZmZ d d
lmZ G dd dejZG dd deZG dd deZeG dd deeZdS )    )	dataclassfield)ListLiteralOptionalTupleN)ShardedStateDict)nn)LinearAdapter
LoRALinear)ModuleMatcher)"get_adapter_attributes_from_linearis_expert_linear)PEFTAdapterWrapper)loggingc                	   @   sD   e Zd ZdZ			ddedeeeeef  dee dd	fd
dZ	dS )
ModuleDictzR
    nn.ModuleDict with a sharded_state_dict implementation for checkpointing
      Nprefixsharded_offsetsmetadatareturnr   c                 C   s8   i }|   D ]\}}||| | d|| q|S )a  Retrieve the sharded state dictionary of the wrapped module and adapter.

        This method is used for distributed checkpointing, combining the sharded states
        of both the main module and the adapter.

        Args:
            prefix (str): A prefix added to parameter and buffer names. Defaults to ''.
            sharded_offsets (Tuple[Tuple[int, int, int]]): Offsets for sharded parameters.
                                                           Defaults to an empty tuple.
            metadata (Optional[dict]): Additional metadata for the sharded state.
                                       Defaults to None.

        Returns:
            ShardedStateDict: The combined sharded state dictionary.
        .)itemsupdatesharded_state_dict)selfr   r   r   r   keylayerr   r   \/home/ubuntu/.local/lib/python3.10/site-packages/nemo/collections/llm/peft/canonical_lora.pyr   "   s    zModuleDict.sharded_state_dict)r   r   N)
__name__
__module____qualname____doc__strr   intr   dictr   r   r   r   r    r      s    r   c                   @      e Zd ZdZdd ZdS )LoRALinearSplitQKVa  An adapter wrapper for `linear_qkv` where q, k, v are three separate adapters.
    This module that adds the output of the adapters to the output of the wrapped module while taking care of shape.

    This class is designed to be used with LoRA (Low-Rank Adaptation) and similar techniques
    where the adapter's output is added to the main module's output. It extends the AdapterWrapper
    class to provide a specific implementation of the forward method.
    c                 C   s   |  |\}}}| j|}| j|}| j|}||jd |jd d| jjj	}||jd |jd d| jjj	}	||jd |jd d| jjj	}
t
j||	|
gdd}||jd |jd d}|||j |fS )Nr         dim)base_linear_forwardadapter	adapter_q	adapter_k	adapter_vreshapeshapeto_wrapconfigkv_channelstorchcat)r   xlinear_outputbiaslayernorm_outputqueryr   valuequery_4dkey_4dvalue_4dqkv_4dadapter_outputr   r   r    forwardF   s   """zLoRALinearSplitQKV.forwardNr!   r"   r#   r$   rF   r   r   r   r    r)   =       r)   c                   @   r(   )LoRALinearSplitFC1UpGatea  An adapter wrapper for `linear_fc1` where up_proj and gate_proj are two separate adapters.
    This module that adds the output of the adapters to the output of the wrapped module while taking care of shape.

    This class is designed to be used with LoRA (Low-Rank Adaptation) and similar techniques
    where the adapter's output is added to the main module's output. It extends the AdapterWrapper
    class to provide a specific implementation of the forward method.
    c                 C   sN   |  |\}}}| j|}| j|}tj||gdd}|||j |fS )Nr,   r-   )r/   r0   adapter_gate
adapter_upr9   r:   r4   r5   )r   r;   r<   r=   r>   adapter_output_gateadapter_output_uprE   r   r   r    rF   `   s
   z LoRALinearSplitFC1UpGate.forwardNrG   r   r   r   r    rI   W   rH   rI   c                   @   s   e Zd ZU dZedd dZee ed< dZ	e
ed< dZe
ed< d	Zeed
< dZed ed< dZeed< dZeed< dd ZddejfddZdS )CanonicalLoRAa*  
    Implements the LoRA (Low-Rank Adaptation) module for parameter-efficient fine-tuning.
    Canonical LoRA applies LoRA on Q, K, V projection matrices separately, as well as Up and Gate projection
    matrices separately. This follows more closely with Huggingface's implementation of LoRA.

    Args:
        target_modules (List[str], optional): A list of module names to apply LoRA to.
            Defaults to all linear layers ['linear_q', 'linear_k', 'linear_v', 'linear_proj',
                                           'linear_fc1_up', 'linear_fc1_gate', 'linear_fc2'].
                - 'linear_q', 'linear_k', 'linear_v': Apply LoRA to the linear layer used for query, key, and value
                        projections in self-attention. This is fused into one matrix in NeMo LoRA, but left as three
                        separate matrices in Canonical LoRA.
                - 'linear_proj': Apply LoRA to the linear layer used for projecting the output of self-attention.
                - 'linear_fc1_up', 'linear_fc1_proj': Apply LoRA to the Up proj and Gate proj layers.
                        These two together constitute the first fully-connected layer in MLP in NeMo LoRA.
                - 'linear_fc2': Apply LoRA to the second fully-connected layer in MLP.
            Target modules can also contain wildcards. For example, you can specify
                target_modules=['*.layers.0.*.linear_q', '*.layers.1.*.linear_q'] to add LoRA to only linear_q
                on the first two layers.
        exclude_modules (List[str], optional): A list of module names not to apply LoRa to. It will
            match all nn.Linear & nn.Linear-adjacent modules whose name does not match any string in
            exclude_modules. If used, will require target_modules to be empty list or None.
        dim (int): Dimension of the low-rank projection space. Defaults to 32.
        alpha (int): Weighting factor for the low-rank projection. Defaults to 32.
        dropout (float): Dropout rate for the low-rank projection. Defaults to 0.0.
        dropout_position (Literal['pre', 'post'], optional): Position for applying dropout.
            Can be 'pre' (before the low-rank projection) or 'post' (after). Defaults to 'pre'.

    Example:
    --------
        >>> from nemo.collections import llm
        >>> lora = llm.peft.CanonicalLoRA(target_modules=['linear_q', 'linear_k', 'linear_v', 'linear_fc1_up'], dim=32)
        >>> model = llm.Mistral7BModel(model_transform=lora)
        >>> # (set up trainer and data)
        >>> trainer.fit(model, data)

    References:
    -----------
        Hu, E. J., Shen, Y., Wallis, P., Allen-Zhu, Z., Li, Y., Wang, S., Wang, L., & Chen, W. (2021).
        LoRA: Low-Rank Adaptation of Large Language Models. arXiv preprint arXiv:2106.09685.
        https://arxiv.org/abs/2106.09685

    )
    c                   C   s   g dS )N)linear_qlinear_klinear_vlinear_projlinear_fc1_uplinear_fc1_gate
linear_fc2r   r   r   r   r    <lambda>   s    zCanonicalLoRA.<lambda>)default_factorytarget_modules    r.   alphag        dropoutpre)r\   postdropout_positionxavierlora_A_init_methodzerolora_B_init_methodc                 C   s   | j D ]q}|drJ d|drJ dd|v r(| j|dd d qd|v r9| j|dd d qd|v rJ| j|dd d qd|v r[| j|dd d qd	|v rl| j|d	d d	 q| j| | qd
S )a  
        Construct a mapping from the target module as supported in LoRA() to the specific parts of the layer for which
        adapter is applied.

        For example, if user specifies target_module = ['linear_q', 'linear_k', 'linear_proj', 'linear_fc1_up'], then
        canonical_lora_mapping = {
            "linear_qkv": {'linear_q', 'linear_k'},
            "linear_proj": {'linear_proj'},  # the value of this key does not matter
            "linear_fc1": {'linear_fc1_up'},
        }

        If user specifies target_module = ['*.layers.0.*.linear_q', '*.layers.1.*.linear_q'], then
        canonical_lora_mapping = {
            "'*.layers.0.*.linear_qkv'": {'linear_q'},
            "'*.layers.1.*.linear_qkv'": {'linear_q'},
        }

        
linear_qkvzCanonical LoRA does not support target 'linear_qkv'. Either use 'linear_qkv' with LoRA() or use ['linear_q', 'linear_k', 'linear_v'] with Canonical LoRA
linear_fc1zCanonical LoRA does not support target 'linear_fc1'. Either use 'linear_fc1' with LoRA() or use ['linear_fc1_up', 'linear_fc1_gate'] with Canonical LoRArO   rP   rQ   rS   rT   N)rX   endswithcanonical_mappingreplaceadd)r   targetr   r   r    __post_init__   s&   
zCanonicalLoRA.__post_init__Nmc                 C   s  ddl m} | ||| }dur|\}}t|tjr(t|| j| j| j	| j
dS t|\}}	}
}}t| j|dd| j
| jd|| j	| jt|dd| jt|||d}|d	v rj||	|
fi |}td
|  t||S | j| }td
| d| d |dkrd\}}}|jj|jj }d|v r||	|	fi |}d|v r||	|fi |}d|v r||	|fi |}t|||d}t||S |dkrd\}}d|v r||	|
d fi |}d|v r||	|
d fi |}t||d}t||S |S )a  
        Applies LoRA to a specific module within the model architecture.

        Args:
            m (nn.Module): The module to apply LoRA to.
            name (str, optional): Name of the module (if applicable). Defaults to None.
            prefix (str, optional): Prefix for the module name (if applicable). Defaults to None.

        Returns:
            nn.Module: The modified module with LoRA applied, or the original module if not a target.
        r   )ParallelLinearAdapterN)r.   rZ   r[   r`   identityFr7   )r.   base_linear_name
activation	norm_typecolumn_init_methodrow_init_methodgather_outputinput_is_parallelr[   r^   model_parallel_configrZ   	is_expertdisable_sequence_parallel_commbase_linear_is_parallel)rR   rU   zAdding lora to: z ()rc   )NNNrO   rP   rQ   )r1   r2   r3   rd   NNrS   r,   rT   )rK   rJ   )nemo.collections.llm.peft.utilsrl   match
isinstancer	   Linearr
   r.   rZ   r[   r`   r   r'   rb   r^   getattrr   r   infor   rf   r7   r8   num_query_groupsr   r)   rI   )r   rk   namer   rl   ansr|   	full_namert   in_featuresout_featuresdisable_sp_commrx   adapter_kwargsr0   canonical_submodulesr1   r2   r3   kv_out_featuresadaptersrK   rJ   r   r   r    	transform   sh   





zCanonicalLoRA.transformrz   )r!   r"   r#   r$   r   rX   r   r%   __annotations__r.   r&   rZ   r[   floatr^   r   r`   rb   rj   r	   Moduler   r   r   r   r    rN   i   s   
 -*rN   )dataclassesr   r   typingr   r   r   r   r9   (megatron.core.dist_checkpointing.mappingr   r	   nemo.collections.llm.peft.lorar
   r   (nemo.collections.llm.peft.module_matcherr   r{   r   r   %nemo.lightning.pytorch.callbacks.peftr   r   
nemo.utilsr   r   r)   rI   rN   r   r   r   r    <module>   s    