o
    }oi)5                     @   sd  d dl mZmZ d dlmZ d dlZd dl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 d dlmZm Z m!Z! d dl"m#Z# d dl$m%Z% d dl&m'Z' d dl(m)Z) d dl*m+Z+ dZ,ej-j.e,ddej/ej0 fddZ1										d;de2de2deej3 dee2 d e2d!e4d"e2d#e2d$e2d%ee5ej/e
   dej/ej6 fd&d'Z7ej-j.ee,d(dd)dddefd*ee8 d+e8d"e2d#e2d,e4d-edej9fd.d/Z:d0ej9dej9fd1d2Z;ej-j.ee,d(		)			3			d<d*ee8 d+e8d"e2d#e2d4ee8 d5ee2 d6ee4 d,e4dej9fd7d8Z<d0ej9d4e8dej9fd9d:Z=dS )=    )CallableOptionalN)Callback)DistributedDataParallelConfig)	lightning)finetunepretrain)MockDataModule)PackedSequenceSpecs)Llama2Config7B
LlamaModel)PEFT_STR2CLS)default_finetune_recipe)default_logdefault_resumetensorboard_logger),distributed_fused_adam_with_cosine_annealing)
bf16_mixed)GarbageCollectionCallback)MegatronCommOverlapCallback)TimingCallback	llama2_7bnamereturnc                   C   s   t jtt tdS )a^  
    Factory function to create a Llama2 7B model configuration.

    Returns:
        run.Config[pl.LightningModule]: Configuration for the Llama2 7B model.

    Examples:
        CLI usage:
            $ nemo llm pretrain model=llama2_7b ...

        Python API usage:
            >>> model_config = model()
            >>> print(model_config)
    )config)runConfigr   r    r   r   Z/home/ubuntu/.local/lib/python3.10/site-packages/nemo/collections/llm/recipes/llama2_7b.pymodel)   s   r          F   { tensor_parallelismpipeline_parallelismpipeline_parallelism_typevirtual_pipeline_parallelismcontext_parallelismsequence_parallelism	num_nodesnum_gpus_per_node	max_steps	callbacksc
                 C   sb   t jtj| |||||dddt jtddddddd}
t jtjdd|	|ddd||t |
d	d
d}|S )ad  
    Configure the NeMo Lightning Trainer for Llama2 7B model.

    This function sets up the distributed training strategy and other training parameters.

    Args:
        tensor_parallelism (int): Degree of tensor model parallelism.
        pipeline_parallelism (int): Degree of pipeline model parallelism.
        pipeline_parallelism_type (Optional[torch.dtype]): Data type for pipeline parallelism.
        virtual_pipeline_parallelism (Optional[int]): Size of virtual pipeline parallelism.
        context_parallelism (int): Degree of context parallelism.
        sequence_parallelism (bool): Whether to use sequence parallelism.
        num_nodes (int): Number of compute nodes to use.
        num_gpus_per_node (int): Number of GPUs per node.
        max_steps (int): Maximum number of training steps.
        callbacks (Optional[list[run.Config[Callback]]]): List of callback configurations.

    Returns:
        run.Config[nl.Trainer]: Configuration for the NeMo Lightning Trainer.

    Examples:
        CLI usage:
            $ nemo llm pretrain trainer=llama2_7b ...

        Python API usage:
            >>> trainer_config = trainer(num_nodes=2, num_gpus_per_node=8)
            >>> print(trainer_config)

    Note:
        For more information on distributed training strategies, refer to the
        NeMo documentation on multi-GPU and multi-node training.
    Tcheck_for_nan_in_gradgrad_reduce_in_fp32overlap_grad_reduceoverlap_param_gatheraverage_in_collective)
tensor_model_parallel_sizepipeline_model_parallel_sizepipeline_dtype$virtual_pipeline_model_parallel_sizecontext_parallel_sizesequence_parallelgradient_as_bucket_viewckpt_async_saveckpt_parallel_loadddpgpur"   2       
   Fi  )acceleratoraccumulate_grad_batchesr.   deviceslimit_test_batcheslimit_val_batcheslog_every_n_stepsr-   r+   pluginsstrategyuse_distributed_samplerval_check_interval)r   r   nlMegatronStrategyr   Trainerr   )r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   rJ   trainerr   r   r   rP   <   sJ   ,rP   )targetr   defaultdirr   performance_modefnc                 C   sb   t j|t t||t tgdt jtddddt| |t|ddt	dd	t
 d
}|r/t|}|S )a  
    Create a pre-training recipe for Llama2 7B model.

    This function sets up a complete configuration for pre-training, including
    model, trainer, data, logging, optimization, and resumption settings.

    Args:
        dir (Optional[str]): Directory for saving logs and checkpoints.
        name (str): Name of the pre-training run.
        num_nodes (int): Number of compute nodes to use.
        num_gpus_per_node (int): Number of GPUs per node.
        performance_mode (bool): If true, enables optimizations for maximum performance.
        fn (Callable): The pre-training function to use.

    Returns:
        run.Partial: Partial configuration for pre-training.

    Examples:
        CLI usage:
            $ nemo llm pretrain --factory llama2_7b
            $ nemo llm pretrain --factory "llama2_7b(num_nodes=2, name='my_pretrain')"

        Python API usage:
            >>> recipe = pretrain_recipe(name="llama2_7b_pretrain", num_nodes=2)
            >>> print(recipe)
    )r+   r,   r.      i   r"   )
seq_lengthglobal_batch_sizemicro_batch_sizer   )rS   r   r   ga2U0*3?)max_lr)r    rP   datalogoptimresume)r   Partialr    rP   r   r   r	   r   r   r   r   "pretrain_performance_optimizations)rS   r   r+   r,   rT   rU   reciper   r   r   pretrain_recipe   s    #
rb   ra   c                 C   s   | j jtjtdd | S )a  
    Create a performance-optimized pre-training recipe for Llama2 7B model.

    This method enables performance optimizations that may not be suitable for all use cases.
    It builds upon the standard pre-training recipe and adds additional performance enhancements.

    Args:
        recipe (run.Partial): Base pre-train recipe to which performance optimizations will be added

    Returns:
        run.Partial: Partial configuration for performance-optimized pre-training.

    Note:
        Use this method with caution and only when you need maximum performance.
        It may not be suitable for all hardware configurations or use cases.
    Ftp_comm_overlap)rP   r.   appendr   r   r   )ra   r   r   r   r`      s   r`   lorapeft_schemerW   packed_sequencec           	      C   s  |du r|}|du r|rdnd}t t d| ||||}|du s%| dkr0d|jj_d|jj_n/| dv rXt	
t|  |_d	|j_d
|j_d|jj_d|jj_d|jj_ntd| ||jj_||j_|ryddi|j_t	j
t|d|j_|rt||}|S )a  
    Create a fine-tuning recipe for Llama2 7B model.

    This function sets up a complete configuration for fine-tuning, including
    model, trainer, data, logging, optimization, and resumption settings.
    The recipe uses LoRA (Low-Rank Adaptation) for efficient fine-tuning, unless peft_scheme is set to None.

    Args:
        dir (Optional[str]): Directory for saving logs and checkpoints.
        name (str): Name of the fine-tuning run.
        num_nodes (int): Number of compute nodes to use.
        num_gpus_per_node (int): Number of GPUs per node.
        peft_scheme (Optional[str]): Name of the peft scheme to use for fine-tuning.
            Allowed values: 'lora'/'dora'/'none'/None.
        seq_length (int): Maximum number of tokens per microbatch.
        packed_sequence (Optional[bool]): If true, fine-tuning sequences will be packed into batches up to the given
            maximum seq_length for better efficiency. By default, this value equals performance_mode.
        performance_mode (bool): If true, enables optimizations for maximum performance.

    Returns:
        run.Partial: Partial configuration for fine-tuning.

    Examples:
        CLI usage:
            $ nemo llm finetune --factory llama2_7b

        Python API usage:
            >>> recipe = finetune_recipe(name="llama2_7b_finetune", num_nodes=2)
            >>> print(recipe)

    Note:
        This recipe uses the SQuAD dataset for fine-tuning.
    NrV   i   zmeta-llama/Llama-2-7b-hfnoner!   gh㈵>)rf   dorar#      Fg-C6?zUnrecognized peft scheme: pad_to_max_lengthT)packed_sequence_size)r   r    lowerrP   rJ   r5   r]   r   lrr   r   r   peftdimalphause_distributed_optimizercross_entropy_loss_fusion
ValueErrorrW   r[   dataset_kwargsr
   packed_sequence_specs"finetune_performance_optimizations)	rS   r   r+   r,   rg   rW   rh   rT   ra   r   r   r   finetune_recipe   s4   .




ry   c                 C   s   d| j j_t| j dsg | j _|du s| dkr9d| j j_tj	t
dddddd| j j_| j jtj	tdd nd	g| j_| j jt	t | j jt	td
d
 | S )a  
    Modify the given recipe to optimize settings for performance.

    This method enables performance optimizations that may not be suitable for all use cases.
    Intended to build upon the standard fine-tuning recipe.

    Args:
        recipe (run.Partial): Base fine-tuning recipe to which performance optimizations will be added
        peft_scheme (Optional[str]): Name of the peft scheme to use for fine-tuning.
            Allowed values: 'lora'/'dora'/'none'/None.

    Returns:
        run.Partial: Partial configuration for performance-optimized fine-tuning.

    Note:
        Use this method with caution and only when you need maximum performance.
        It may not be suitable for all hardware configurations or use cases.
    r"   r.   Nri   FTr/   rc   
linear_qkvd   )rP   rJ   r5   hasattrr.   rn   rI   r1   r   r   r   r>   re   r   rp   target_modulesr   r   )ra   rg   r   r   r   rx   7  s:   


rx   )
r!   r"   NNr"   Fr"   r#   r$   N)NrR   r"   r#   rf   NNF)>typingr   r   lightning.pytorchpytorchplnemo_runr   torch$lightning.pytorch.callbacks.callbackr   megatron.core.distributedr   nemor   rM   nemo.collections.llm.apir   r   "nemo.collections.llm.gpt.data.mockr	   -nemo.collections.llm.gpt.data.packed_sequencer
   $nemo.collections.llm.gpt.model.llamar   r   nemo.collections.llm.peftr   -nemo.collections.llm.recipes.finetune_defaultr   (nemo.collections.llm.recipes.log.defaultr   r   r   'nemo.collections.llm.recipes.optim.adamr   6nemo.collections.llm.recipes.precision.mixed_precisionr   3nemo.lightning.pytorch.callbacks.garbage_collectionr   6nemo.lightning.pytorch.callbacks.megatron_comm_overlapr   nemo.utils.exp_managerr   NAMEclifactoryr   LightningModuler    intdtypeboollistrO   rP   strr_   rb   r`   ry   rx   r   r   r   r   <module>   s   	


U6	T