o
    }oi                     @   s>  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 d dlmZmZmZ d dlmZ d d	lmZ d
Z										d$dededeej dee dedededededeeeje   dejej fddZejjej ed			
		d%de!de!dee! d ee! d!e!dededej"fd"d#Z#dS )&    )OptionalN)Callback)DistributedDataParallelConfig)	lightning)llm)default_logdefault_resumetensorboard_logger),distributed_fused_adam_with_cosine_annealing)
bf16_mixeddefault      T{ tensor_parallelismpipeline_parallelismpipeline_parallelism_typevirtual_pipeline_parallelismcontext_parallelismsequence_parallelism	num_nodesnum_gpus_per_node	max_steps	callbacksreturnc
                 C   sj   t jtj| |||||o| dk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 )a  Configure the NeMo Lightning Trainer (for no model in particular).

    This function sets up the distributed training strategy.

    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=llama31_8b ...

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

    Note:
        This configuration uses extensive parallelism to handle the large model size efficiently.
    r   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gpu2       
   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)runConfignlMegatronStrategyr   Trainerr   )r   r   r   r   r   r   r   r   r   r   r5   trainer r>   m/home/ubuntu/.local/lib/python3.10/site-packages/nemo/collections/llm/modelopt/recipes/distillation_recipe.pyr=       sJ   *
r=   )targetnamestudent_model_pathteacher_model_pathdistillation_config_pathdirrA   c                 C   sR   t jtj| ||t||dt jtjddddt||t|ddt	dd	t
 d
	}|S )a  Create a generic distillation recipe.

    This function sets up a complete configuration for distillation, including
    trainer, data, logging, optimization, and resumption settings.

    Args:
        student_model_path (Path): Path to student model NeMo checkpoint to be trained.
        teacher_model_path (Path): Path to teacher model NeMo checkpoint to distill from.
        distillation_config_path (Optional[str]): Path to distillation config file.
        dir (Optional[str]): Directory for saving logs and checkpoints.
        name (str): Name of the distillation 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.

    Returns:
        run.Partial: Partial configuration for distillation.

    Python recipe usage:
        >>> import nemo_run as run
        >>> from nemo.collections import llm
        >>> from nemo.collections.llm.modelopt.recipes import distillation_recipe
        >>> recipe = distillation_recipe(
        ...     student_model_path="/path/to/student/nemo/ckpt/",
        ...     teacher_model_path="/path/to/teacher/nemo/ckpt/",
        ...     distillation_config_path="/path/to/distillation/config.yaml",
        ... )
        >>> # Override the configuration with desired components:
        >>> recipe.data = run.Config(llm.PreTrainingDataModule, ...)
        >>> recipe.trainer.strategy.tensor_model_parallel_size = 8
        >>> ...
        >>> run.run(recipe)
    )r   r   i    i   r   )
seq_lengthglobal_batch_sizemicro_batch_size)rA   )rE   rA   r	   giUMu>)max_lr)rB   rC   rD   r=   datalogoptimresume)r8   Partialr   distillr=   r9   MockDataModuler   r	   r
   r   )rB   rC   rD   rE   rA   r   r   reciper>   r>   r?   distillation_recipes   s   ,rR   )
r   r   NNr   Tr   r   r   N)NNr   r   r   )$typingr   nemo_runr8   torch$lightning.pytorch.callbacks.callbackr   megatron.core.distributedr   nemor   r:   nemo.collectionsr   (nemo.collections.llm.recipes.log.defaultr   r   r	   'nemo.collections.llm.recipes.optim.adamr
   6nemo.collections.llm.recipes.precision.mixed_precisionr   NAMEintdtypeboollistr9   r<   r=   clifactoryrO   strrN   rR   r>   r>   r>   r?   <module>   s   	


S