o
    }oiN                  8   @   s  d dl Z d dlZd dlZd dlZd dlmZ d dlmZ d dlm	Z	m
Z
mZ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 d dlmZ d d	lm Z m!Z! d d
l"m#Z#m$Z$m%Z%m&Z& d dl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0 d dlm1Z1m2Z2m3Z3m4Z4m5Z5m6Z6 d dl7m8Z8 d dl9m:Z: d dl;m<Z<m=Z=m>Z> d dl?m@Z@ d dlAmBZB e	rd dlCmDZD d dlEmFZF e
ZGeeeHf ZIejJjKdd					ddeejLeIf dejMde4deee2 ejNe2 f deee1 ejNe1 f dee3 deeG deee<e>ef  defdd ZOejJjKdd			ddeejLeIf dejMde4deee2 ejNe2 f deee1 ejNe1 f dee3 defd!d"ZPejJjKdd					ddeejLeIf dejMde4deee2 ejNe2 f deee1 ejNe1 f dee3 d#eee<e>ef  deeG defd$d%ZQejJjKdd					ddejLdejMde4deee2 ejNe2 f deee1 ejNe1 f dee3 deeG deee<e>ef  defd&d'ZRejJjKd(dd)	*	*	*	*	+			,dd-eHd.eHd/e*d0eSd1eSd2eSd3eSd4eSdejMdB d5eHdB d6eTdeHfd7d(ZUejJjKd8dd)						dd9eId:eIdejMde4d;eeI deee2 ejNe2 f deee1 ejNe1 f dee3 deeG deee<e>ef  defd<d8ZVejJjKd=dd)	*	*								,	,dd>eHd?e)d@eSdAeSdBeSdB dCeSdB d0eSdB d1eSdB dDeee+ ejNe+ f dEedB d5eHdB d6eTdFeTdefdGd=ZWejJjKdd		H		I	*	J	K	L		M	L	N	*	*	*	*	*	*	*		O	P	Q	M	M	M	,dd-eeI dReHdSeeH dTeHdUeeS dVeSdWeSdXeHdYeeI dZeTd[eHd\eSd]eSd1eSd^eSd_eSd`eSdaeSdbeSdceeH ddeSdeeSdfeSdgeTdheTdieTd6eTf6djdkZXejJjKdde$dldmdfdne%doe$dpe#dB deYfdqdrZZejJjKdsdd)		,ddejLdteHdueeI dveTdef
dwdxZ[dyeIdzeHde6j\fd{d|Z]ejJjKd}dd)dd,e]dfdyeIdzeHdueeI dveTd~eeeHge6j\f deYeHe
f defddZ^ejJjKddd)dddej_d,ddddd,ddMfdyeIdej4dee`eH  dee`eH  deeejMeHf  dejadeTdfeSdeeS deSded deTdueeI dieTde`edeHf  fddZbdejLdejMdeGddfddZcdejLdejMde4dee2 dee1 dee3 deeG deee<e>ef  de
fddZddd Ze					ddejLdejMde4dee2 dee1 dee3 deeG deee<e>ef  ddfddZfdddZgdeejLeIf fddZhdS )    N)deepcopy)Path)TYPE_CHECKINGAnyCallableOptionalUnion)parallel_state)Console)all_gather_object)	Annotated)GPTModelHFAutoModelForCausalLM)AdapterConfigEvaluationConfigEvaluationTargetMisconfigurationError)	DistillationGPTModelExportConfigPruningConfigQuantizationConfig	Quantizerprune_gpt_modelsave_pruned_model#set_modelopt_spec_if_exists_in_ckpt2setup_trainer_and_restore_model_with_modelopt_spec)
AutoResume
NeMoLoggerOptimizerModuleTrainer-configure_no_restart_validation_training_loopio)NEMO_MODELS_CACHE)ckpt_to_context_subdir)PEFTJitTransformModelTransform)logging)is_global_rank_zero)CommonInferenceParams)InferenceRequestllm)	namespacemodeldatatrainerlogresumeoptim	tokenizermodel_transformreturnc           	   
   C   sf   t | } |r|jr|jjrt| |jj n	|jrt| |j t| |||||||d}|| | |jS )a  
    Trains a model using the specified data and trainer, with optional tokenizer, source, and export.

    Args:
        model (Union[pl.LightningModule, AnyPath]): The model to be trained or a path to the NeMo 2 checkpoint.
        data (pl.LightningDataModule): The data module containing training data.
        trainer (Trainer): The trainer instance configured with a MegatronStrategy.
        log (NeMoLogger): A nemologger instance.
        resume (Optional[Union[AutoResume, Resume]]): Resume training from a checkpoint.
        optim (Optional[OptimizerModule]): The optimizer module to be used. If not provided, the default optimizer
            from the model will be used.
        tokenizer (Optional[TokenizerType]): Tokenizer setting to be applied. Can be 'data' or 'model'
            or an instance of TokenizerSpec.
        export (Optional[str]): Filename to save the exported checkpoint after training.
        model_transform (Optional[Union[Callable[[nn.Module], nn.Module], PEFT]]): A model transform to be applied.

    Returns
    -------
        Path: The directory path where training artifacts are saved.

    Examples
    --------
        >>> from nemo.collections import llm
        >>> from nemo import lightning as nl
        >>> model = llm.MistralModel()
        >>> data = llm.SquadDataModule(seq_length=4096, global_batch_size=16, micro_batch_size=2)
        >>> precision = nl.MegatronMixedPrecision(precision="bf16-mixed")
        >>> trainer = nl.Trainer(strategy=nl.MegatronStrategy(tensor_model_parallel_size=2), plugins=precision)
        >>> llm.train(model, data, trainer, tokenizer="data")
        PosixPath('/path/to/log_dir')
    r-   r.   r/   r0   r1   r2   r3   r4   )_load_model_from_pathrestore_configpathr   resume_from_path_setupfitexp_dir	r-   r.   r/   r0   r1   r2   r3   r4   	app_state r@   L/home/ubuntu/.local/lib/python3.10/site-packages/nemo/collections/llm/api.pytrainH   s$   +rB   c              	   C   s2   t | } t| |||||d t| |||||ddS )a  
    Pretrains a model using the specified data and trainer, with optional logging, resuming, and optimization.

    This function is a wrapper around the `train` function, specifically configured for pretraining tasks.
    Note, by default it will use the tokenizer from the model.

    Args:
        model (Union[pl.LightningModule, AnyPath]): The model to be pretrained or a path to the NeMo 2 checkpoint.
        data (pl.LightningDataModule): The data module containing pretraining data.
        trainer (Trainer): The trainer instance configured with a MegatronStrategy.
        log (NeMoLogger): A nemologger instance.
        resume (Optional[AutoResume]): Resume training from a checkpoint.
        optim (Optional[OptimizerModule]): The optimizer module to be used. If not provided, the default
            optimizer from the model will be used.

    Returns:
        Path: The directory path where pretraining artifacts are saved.

    Examples:
        >>> from nemo.collections import llm
        >>> from nemo import lightning as nl
        >>> model = llm.MistralModel()
        >>> data = llm.PretrainingDataModule(paths=[...], seq_length=4096, global_batch_size=16, micro_batch_size=2)
        >>> precision = nl.MegatronMixedPrecision(precision="bf16-mixed")
        >>> trainer = nl.Trainer(strategy=nl.MegatronStrategy(tensor_model_parallel_size=2), plugins=precision)
        >>> llm.pretrain(model, data, trainer)
        PosixPath('/path/to/log_dir')
    )r0   r1   r2   r.   )r-   r.   r/   r0   r1   r2   r3   r7   _validate_configrB   )r-   r.   r/   r0   r1   r2   r@   r@   rA   pretrain   s   %rE   peftc              
   C   s6   t | } t| ||||||d t| |||||||dS )a  
    Finetunes a model using the specified data and trainer, with optional logging, resuming, and PEFT.

    Note, by default it will use the tokenizer from the model.

    Args:
        model (Union[pl.LightningModule, AnyPath]): The model to be finetuned.
        data (pl.LightningDataModule): The data module containing finetuning data.
        trainer (Trainer): The trainer instance configured with a MegatronStrategy.
        log (NeMoLogger): A nemologger instance.
        resume (Optional[AutoResume]): Resume training from a checkpoint.
        optim (Optional[OptimizerModule]): The optimizer module to be used. If not provided, the default
            optimizer from the model will be used.
        peft (Optional[PEFT]): A PEFT (Parameter-Efficient Fine-Tuning) configuration to be applied.
        tokenizer (Optional[TokenizerType]): Tokenizer setting to be applied. Can be 'data' or 'model'
            or an instance of TokenizerSpec. If 'data' uses the data loader's tokenizer instead of the tokenizer
            from the model checkpoint, which is useful for expanding vocabulary or adding special tokens
            (such as chat template tokens).

    Returns:
        Path: The directory path where finetuning artifacts are saved.

    Examples:
        >>> from nemo.collections import llm
        >>> from nemo import lightning as nl
        >>> model = llm.MistralModel()
        >>> data = llm.SquadDataModule(seq_length=4096, global_batch_size=16, micro_batch_size=2)
        >>> precision = nl.MegatronMixedPrecision(precision="bf16-mixed")
        >>> trainer = nl.Trainer(strategy=nl.MegatronStrategy(tensor_model_parallel_size=2), plugins=precision)
        >>> llm.finetune(model, data, trainer, peft=llm.peft.LoRA()])
        PosixPath('/path/to/log_dir')
    )r0   r1   r2   r4   r6   rC   )r-   r.   r/   r0   r1   r2   rF   r3   r@   r@   rA   finetune   s   +rG   c           	   
   C   s*   t | |||||||d}|| | |jS )a  
    Validates a model using the specified data and trainer, with optional logging, resuming, and model transformations.

    Args:
        model (pl.LightningModule): The model to be validated.
        data (pl.LightningDataModule): The data module containing validation data.
        trainer (Trainer): The trainer instance configured with a MegatronStrategy.
        log (NeMoLogger): A nemologger instance.
        resume (Optional[AutoResume]): Resume from a checkpoint for validation.
        optim (Optional[OptimizerModule]): The optimizer module to be used. If not provided, the default optimizer
            from the model will be used.
        tokenizer (Optional[TokenizerType]): Tokenizer setting to be applied. Can be 'data' or 'model'
            or an instance of TokenizerSpec.
        model_transform (Optional[Union[Callable[[nn.Module], nn.Module], PEFT]]): A model transform to be applied.

    Returns:
        Path: The directory path where validation artifacts are saved.

    Examples:
        >>> from nemo.collections import llm
        >>> from nemo import lightning as nl
        >>> model = llm.MistralModel()
        >>> data = llm.SquadDataModule(seq_length=4096, global_batch_size=16, micro_batch_size=2)
        >>> precision = nl.MegatronMixedPrecision(precision="bf16-mixed")
        >>> trainer = nl.Trainer(strategy=nl.MegatronStrategy(tensor_model_parallel_size=2), plugins=precision)
        >>> llm.validate(model, data, trainer, tokenizer="data")
        PosixPath('/path/to/log_dir')
    r6   )r;   validater=   r>   r@   r@   rA   rH      s   'rH   prune)namer,         Fnemo_checkpoint	save_pathpruning_configdevices	num_nodestp_sizepp_sizenum_train_samplestokenizer_pathlegacy_ckptc                 C   s   |dur|j |jksJ d||j  }n|}t| ||||d|	|
ddd|||dddid\}}t|||| t|| t }|d	| d
 |S )a  
    Prunes a model using the specified data and trainer. Currently only supports GPT models.

    Args:
        nemo_checkpoint (str): The path to the NeMo checkpoint to be pruned.
        save_path (str): The path to save the pruned NeMo checkpoint.
        pruning_config (PruningConfig): The pruning configuration.
        devices (int): The number of devices to use for pruning.
        num_nodes (int): The number of nodes to use for pruning.
        tp_size (int): The tensor parallel size.
        pp_size (int): The pipeline parallel size.
        num_train_samples (int): Number of training samples for importance estimation using forward pass.
        data (pl.LightningDataModule): The data module for forward pass.
            Required if not dropping layers.
        tokenizer_path (str): Path to the tokenizer if not using model's tokenizer.
        legacy_ckpt (bool): If True, allow loading ckpt saved with older version of TE.
            Use for cases like missing state dict keys ending with `_extra_state`.

    Returns:
        str: The path to the pruned NeMo checkpoint.

    Examples:
        >>> from nemo.collections import llm
        >>> from nemo.collections.llm.modelopt.prune import PruningConfig
        >>> data = llm.PretrainingDataModule(
                paths=["1.0", "path/to/tokenized/data"],
                seq_length=256,
                global_batch_size=1,
                micro_batch_size=1,
            )
        >>> llm.prune(
                nemo_checkpoint="path/to/llama3.1-8b",
                save_path="path/to/pruned_llama_model",
                pruning_config=PruningConfig(target_ffn_hidden_size=9216, target_hidden_size=3072),
                data=data
            )
    Nz3Global batch size must be equal to micro batch sizeTF)sequence_parallelreplace_progress_bar)	max_stepslimit_val_batchesval_check_intervalrW   )
model_pathtensor_model_parallel_sizepipeline_model_parallel_sizerP   rQ   inference_onlyrU   rV   strategy_kwargstrainer_kwargsmodel_config_overridesu8   [green]✓ Pruning succeded, pruned checkpoint saved to [/green])global_batch_sizemicro_batch_sizer   r   r   r
   print)rM   rN   rO   rP   rQ   rR   rS   rT   r.   rU   rV   stepsr-   r/   consoler@   r@   rA   rI   /  s,   3


distillstudent_model_pathteacher_model_pathdistillation_config_pathc
              
   C   s   t jt| dd}
t jt|dd}t|
tsJ dt|ts$J d|du r<t|
ddp3t|dd}|dus<J dt|
j|j||d}|
j|_t	||||||||	dS )	a  
    Distills a teacher model into a student model using special Knowledge-Distillation losses.

    Note that this requires an existing NeMo 2.0 checkpoint of the student model as well, as
    the model class is not known beforehand.
    This script currently supports instances of ``nemo.collections.llm.GPTModel`` for now.

    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.
        data (pl.LightningDataModule): The data module containing training data.
        trainer (Trainer): The trainer instance configured with a MegatronStrategy.
        distillation_config_path (Optional[Path]): Path to distillation config YAML file.
            If not provided, by default will perform logits-only distillation.
        log (NeMoLogger): A nemologger instance.
        resume (Optional[Union[AutoResume, Resume]]): Resume training from a checkpoint.
        optim (Optional[OptimizerModule]): The optimizer module to be used. If not provided, the default optimizer
            from the model will be used.
        tokenizer (Optional[TokenizerType]): Tokenizer setting to be applied. Can be 'data' or 'model'
            or an instance of TokenizerSpec.
        export (Optional[str]): Filename to save the exported checkpoint after training.
        model_transform (Optional[Union[Callable[[nn.Module], nn.Module], PEFT]]): A model transform to be applied.

    Returns
    -------
        Path: The directory path where training artifacts are saved.

    Examples
    --------
        >>> from nemo.collections import llm
        >>> from nemo import lightning as nl
        >>> student = "/path/to/student/nemo/ckpt"  # <-- change me
        >>> teacher = "/path/to/teacher/nemo/ckpt"  # <-- change me
        >>> data = llm.SquadDataModule(seq_length=4096, global_batch_size=16, micro_batch_size=2)
        >>> precision = nl.MegatronMixedPrecision(precision="bf16-mixed")
        >>> trainer = nl.Trainer(strategy=nl.MegatronStrategy(tensor_model_parallel_size=2), plugins=precision)
        >>> llm.distill(student, teacher, data, trainer, tokenizer="model")
        PosixPath('/path/to/log_dir')
    r-   subpathz<Only models based on `llm.GPTModel` are supported currently.Nr3   z/Tokenizer neither provided nor found in models.)teacher_ckpt_pathrl   )r-   r.   r2   r3   r/   r0   r1   r4   )
r!   load_contextr#   
isinstancer   getattrr   config__io__rB   )rj   rk   r.   r/   rl   r0   r1   r2   r3   r4   _student_model_teacher_modelr-   r@   r@   rA   ri   ~  s0   4ptqr\   export_configcalibration_tpcalibration_pp"num_layers_in_first_pipeline_stage!num_layers_in_last_pipeline_stagequantization_configforward_looptrust_remote_codec                 C   s   |st  }|du r|}|du r|}t||}t|  s$J d|  dt| d  }d}|rE|jdks9J dt| |dd}|  nt| ||||||d	|
|d
d	di dd
id\}}|||	}|	|| | t
 rzt }|d|j d |jS )aK  
    Applies Post-Training Quantization (PTQ) for a model using the specified quantization and export configs. It runs
    calibration for a small dataset to collect scaling factors low-precision GEMMs used by desired quantization method.
    By default, this function produces TensorRT-LLM checkpoint ready for deployment using nemo.export and nemo.deploy
    modules or direcly using TensorRT-LLM library.

    The function can be used through the NeMo CLI in the following way:
    ```bash
    # Run calibration using tensor parallel set to 8 and export quantized checkpoint with tensor parallel equal 2
    nemo llm ptq run.executor=torchrun run.executor.ntasks_per_node=8         model_path=/models/Llama-3-70B         export_config.path=/models/Llama-3-70B-FP8         calibration_tp=8         export_config.inference_tp=2

    # Choose different quantization method, for example, INT8 SmoothQuant
    nemo llm ptq run.executor=torchrun run.executor.ntasks_per_node=1         model_path=/models/Llama-3-8B         export_config.path=/models/Llama-3-8B-INT8_SQ         quantization_config.algorithm=int8_sq

    # Export as NeMo checkpoint instead
    nemo llm ptq run.executor=torchrun         model_path=/models/Llama-3-8B         export_config.path=/models/Llama-3-8B-INT8_SQ         quantization_config.algorithm=int8_sq         export_config.export_format=nemo

    # Quantize HF AutoModel checkpoint.
    nemo llm ptq run.executor=torchrun run.executor.ntasks_per_node=1         model_path=/models/Llama-3-70B-HF         export_config.path=/models/Llama-3-70B-HF-FP8         export_config.export_format=hf
    ```

    Args:
        model_path (str): The path to model to be quantized.
        calibration_tp (int): Calibration tensor parallelism.
        calibration_pp (int): Calibration pipeline parallelism.
        num_layers_in_first_pipeline_stage (int): Number of layers in the first pipeline stage.
        num_layers_in_last_pipeline_stage (int): Number of layers in the last pipeline stage.
        export_config (ExportConfig): Export configuration for output checkpoint.
        devices (int): Number of devices to use for calibration. Default: calibration_tp.
        num_nodes (int): Number of nodes to use for calibration. Default: calibration_pp.
        quantization_config (QuantizationConfig): Configuration for quantization algorithm.
        forward_loop (Callable): Forward loop to use for calibration.
            If not provided, a forward loop will be created using the calibration dataset.
        tokenizer_path (str): Path to the tokenizer if not using model's tokenizer.
        legacy_ckpt (bool): If True, allow loading ckpt saved with older version of TE.
        trust_remote_code (bool): Trust remote code when loading HuggingFace models.

    Returns:
        Path: The path where the quantized checkpoint has been saved after calibration.
    NzPath z does not existzconfig.jsonnemoz1Automodel PTQ does not support export format nemoauto)
model_namer   
device_mapTF)rW   	lazy_initrW   )r\   r]   r^   r{   r|   rP   rQ   r_   rU   rV   r`   ra   rb   u:   [green]✓ PTQ succeded, quantized checkpoint exported to rc   )r   r   r   existsexport_formatr   configure_modelr   quantizeexportr(   r
   rf   r9   )r\   rx   ry   rz   r{   r|   rP   rQ   r}   r~   rU   rV   r   	quantizeris_automodelr/   r-   rh   r@   r@   rA   rw     sF   F


in-frameworktriton_model@  A  0.0.0.0T           backend
model_typetriton_model_nametriton_model_versiontriton_http_porttriton_grpc_porttriton_http_addresstriton_model_repositorystart_fastapi_serverfastapi_http_addressfastapi_portnum_gpustensor_parallelism_sizepipeline_parallelism_sizecontext_parallel_sizeexpert_model_parallel_sizeexpert_tensor_parallel_sizedtypemax_input_lenmax_output_lenmax_batch_sizeoutput_context_logitsoutput_generation_logitsenable_flash_decodec           %      C   sZ  ddl }ddl}ddlm} |dkr|	du sJ d||kr#td||jd< t||jd	< zdd
lm} W n t	yQ } ztdt
|j d| dd}~ww || |||||||||||d} tj rtj dkrz|| ||||||d}!td |!  |!  W n t	y }" ztdt|"  W Y d}"~"dS d}"~"ww z9|	rztd |jd|
|dd W n t	y }" ztdt|"  W Y d}"~"nd}"~"ww td |!  W n t	y }" ztdt|"  W Y d}"~"dS d}"~"ww td |!  dS tj dkr|   dS dS dS |dkrddlm}#m}$ |$  |#| |||||||||||} z|| ||||||d}!td |!  |!  W n t	yp }" ztdt|"  W Y d}"~"dS d}"~"ww ztd |!  W n t	y }" ztdt|"  W Y d}"~"dS d}"~"ww td |!  dS td| d)a  
    Deploys nemo model on a PyTriton server either "in-framework" or by converting to trtllm depending on the backend.
    This deploy method is intended to be used for evaluation.

    Args:
        nemo_checkpoint (Path): Path for nemo checkpoint.
        backend (str): options: "in-framework" or "trtllm". Deploys nemo2 checkpoint directly on Pytriton server w/o
            any conversion if "in-framework". If "trtllm", exports nemo2 model to trtllm and deploys on PyTriton.
            Default: "in-framework".
        model_type (str): Type of the model for the "trtllm" backend option. Autodetected from the given nemo
            checkpoint by default.
        triton_model_name (str): Name for the model that gets deployed on PyTriton. Please ensure that the same model
            name is passed to the evalute method for the model to be accessible while sending evalution requests.
            Default: 'triton_model'.
        triton_model_version (Optional[int]): Version for the triton model. Default: 1.
        triton_http_port (int): HTTP port for the PyTriton server. Default: 8000.
        triton_grpc_port (int): gRPC Port for the PyTriton server. Default: 8001.
        triton_http_address (str): HTTP address for the PyTriton server. Default:  "0.0.0.0".
        triton_model_repository (Path): Folder for the trt-llm conversion, trt-llm engine gets saved in this specified
            path. If None, saves it in /tmp dir. Default: None.
        start_fastapi_server (bool): Starts FastAPI server which acts as a proxy in between to expose the
            v1/completions and v1/chat/completions OpenAI (OAI) compatible endpoints as PyTriton does not expose a
            standard HTTP/REST API. Only supported for "in-framework" deployment and not with "trtllm" backend.
            Default: True.
        fastapi_http_address (str): HTTP address for FastAPI interface/server.  Default: "0.0.0.0". OAI endpoints via
            FastAPI interface are only supported for "in-framework" backend.
        fastapi_port (int): Port for FastAPI interface/server. Applicable only for "in-framework" backend.
            Default: 8080.
        num_gpus (int): Number of GPUs per node for export to trtllm and deploy. Default: 1.
        tensor_parallelism_size (int): Tensor parallelism size. Default: 1.
        pipeline_parallelism_size (int): Pipeline parallelism size. Default: 1.
        dtype (str): dtype of the TensorRT-LLM model. Autodetected from the model weights dtype by default.
        max_input_len (int): Max input length of the model. Default: 4096.
        max_output_len (int): Max output length of the model. Default: 256.
        max_batch_size (int): Max batch size of the model. Default: 8.
        openai_format_response (bool): Return the response from PyTriton server in OpenAI compatible format.
            Needs to be True while running evaluation. Default: True.
        output_context_logits (bool): If True builds trtllm engine with 'gather_context_logits=True'. Default: True.
        context_logits are used to compute the logProb of the output token in multi-token prediction benchmarks.
            Used only with "trtllm" backend.
        output_generation_logits (bool): If True builds trtllm engine with gather_generation_logits set to True.
        generation_logits are used to compute the logProb of the output token in case of single token prediction
            benchmarks (like MMLU, lambada). Default: True. Used only with "trtllm" backend.
        enable_flash_decode (bool): If True runs in-framework deployment with flash decode enabled (not supported for
            the trtllm backend).
        legacy_ckpt (bool): Indicates whether the checkpoint is in the legacy format. Default: False
    r   N)DeployPyTritonr   Tzin-framework deployment exposes OAI API endpoints v1/completions and         v1/chat/completions hence needs fastAPI interface to expose these endpoints to PyTriton. Please set         start_fastapi_server to TruezPFastAPI port and Triton server port cannot use the same port. Please change themTRITON_HTTP_ADDRESSTRITON_PORT)MegatronLLMDeployableNemo2z0Unable to import MegatronLLMDeployable, due to: z: z3 cannot run evaluation with in-framework deployment)nemo_checkpoint_filepathnum_devicesrQ   r]   r^   r   r   r   inference_max_seq_lengthr   r   rV   )r-   r   r   r   	http_port	grpc_portaddressz&Triton deploy function will be called.zBError message has occurred during deploy function. Error message: zREST service will be started.z5nemo.deploy.service.fastapi_interface_to_pytriton:app)hostportreloadzEError message has occurred during REST service start. Error message: z(Model serving on Triton will be started.zModel serving will be stopped.trtllm)get_trtllm_deployableunset_environment_variableszInvalid backend 'z6'. Supported backends are 'in-framework' and 'trtllm'.)osuvicornnemo.deployr   
ValueErrorenvironstr&nemo.deploy.nlp.megatronllm_deployabler   	Exceptiontype__name__torchdistributedis_initializedget_rankr'   infodeployrunerrorservestopgenerate_other_ranks nemo.collections.llm.deploy.baser   r   )%rM   r   r   r   r   r   r   r   r   r   r   r   r   rQ   r   r   r   r   r   r   r   r   r   r   r   r   rV   r   r   r   r   etriton_deployablenmr   r   r   r@   r@   rA   r   ?  s   M









*




r   gsm8k)r   
target_cfgeval_cfgadapter_cfgc              	   C   s  ddl m}m}m} | jjdur|| |d dS ddl}|jd}t	|dkr;|\}}	|
dd}| d|	 |_nt	|d	krId|d }}	ntd
|du rV||	}
n	d|
dd }
z	tjd|
d}W n ty{   td|
 d|j dw | jjd\}}||| jjd}|stdd}|rddlm} ||\}}d|j | j_z |j| |d}| }W |r|dur| r|j| j_|  n|r|dur| r|j| j_|  w w w w td t|| |S )a  
    Evaluates nemo model deployed on PyTriton server using nvidia-lm-eval

    Args:
        target_cfg (EvaluationTarget): target of the evaluation. Providing model_id and
            url in EvaluationTarget.api_endpoint is required to run evaluations.
        eval_cfg (EvaluationConfig): configuration for evaluations. Default type (task): gsm8k.
        adapter_cfg (AdapterConfig): configuration for adapters, the object between becnhmark and endpoint.
            Default: None.
    r   )_legacy_evaluatefind_frameworkwait_for_fastapi_serverN)r   r   .   _-rK   zQeval_type must follow 'framework_name.task_name'. No additional dots are allowed.zcore_evals.z	.evaluate)packagezPlease ensure that z3 is installed in your env as it is required to run z evaluationz/v1)base_urlr   zServer not ready for evaluation)create_server_processzhttp://localhost:z========== RESULTS ==========)$nemo.collections.llm.evaluation.baser   r   r   api_endpointnemo_checkpoint_pathyamlr   splitlenreplacer   	importlibimport_moduleImportErrorurlmodel_idRuntimeError/nemo.collections.llm.evaluation.adapters.serverr   
local_portevaluate_accuracy
model_dumpis_aliveapi_url	terminater'   r   dump)r   r   r   r   r   r   r   eval_type_componentsframework_name	task_nameframework_module_nameevaluater   r   server_readypr   resultsresults_dictr@   r@   rA   r     sj   





r   importsourceoutput_path	overwritec                 K   s   |rt |}| r|std| dtjd| |||d|}t }|r0|d| d n	|dt d t|dd	}|| |S )a  
    Imports a checkpoint into a model using the model's associated importer, typically for
    the purpose of fine-tuning a community model trained in an external framework, such as
    Hugging Face.

    This function can be used both programmatically and through the NeMo CLI:

    CLI Usage:
    ```bash
    # Import Llama 3 8B from HuggingFace (saves to $NEMO_MODELS_CACHE)
    nemo llm import model=llama3_8b source="hf://meta-llama/Llama-3.1-8B"

    # Import with custom output path
    nemo llm import model=llama3_8b source="hf://meta-llama/Llama-3.1-8B" output_path="/path/to/save"

    # Force overwrite existing checkpoint
    nemo llm import model=llama3_8b source="hf://meta-llama/Llama-3.1-8B" overwrite=true
    ```

    Python Usage:
    ```python
    model = Mistral7BModel()
    imported_path = import_ckpt(model, "hf://mistralai/Mistral-7B-v0.1")
    ```

    The importer component of the model reads the checkpoint data from the specified source
    and transforms it into the right format. This is particularly useful for adapting
    models that have been pre-trained in different environments or frameworks to be fine-tuned
    or further developed within the current system.

    For instance, using `import_ckpt(Mistral7BModel(), "hf")` initiates the import process
    by searching for a registered model importer tagged with "hf". In NeMo, `HFMistral7BImporter`
    is registered under this tag via:
    `@io.model_importer(Mistral7BModel, "hf", default_path="mistralai/Mistral-7B-v0.1")`.
    This links `Mistral7BModel` to `HFMistral7BImporter`, designed for HuggingFace checkpoints.

    Args:
        model (pl.LightningModule): The model into which the checkpoint will be imported.
            This model must implement the ConnectorMixin.
        source (str): The source from which the checkpoint will be imported. This can be
            a file path, URL, or any other string identifier that the model's importer
            can recognize.
        output_path (Optional[Path]): The path where the imported checkpoint will be stored.
            If not specified, the checkpoint will be saved to $NEMO_MODELS_CACHE
            (defaults to ~/.cache/nemo/models/ if the environment variable is not set).
        overwrite (bool): If set to True, existing files at the output path will be overwritten.
            This is useful for model updates where retaining old checkpoint files is not required.

    Returns:
        Path: The path where the checkpoint has been saved after import.

    Raises:
        ValueError: If the model does not implement ConnectorMixin, indicating a lack of
            necessary importer functionality.
        FileExistsError: If the output path is provided (that is, when not using models cache)
            and it exists and overwrite is not set to True.
    Output path / exists. Use overwrite=True to force overwrite.)r-   r  r  r  u"   [green]✓ Checkpoint imported to rc   z[green] $NEMO_MODELS_CACHE=z	 [/green]zImported Checkpoint)	root_nameNr@   )	r   r   FileExistsErrorr!   import_ckptr
   rf   r"   _build_directory_tree)r-   r  r  r  kwargsoutputrh   dir_treer@   r@   rA   r
  e  s   A
r
  r9   targetc                 C   s(   t | ts	t| } tj| dd|| S Nr-   rm   )rq   r   r!   rp   exporter)r9   r  r@   r@   rA    load_connector_from_trainer_ckpt  s   
r  r   load_connectormodelopt_export_kwargsc           	      K   s|   t | ts	t| } |r"t |ts"t|}| r"|s"td| dtj| |||||fi |}t }|d| d |S )a	  
    Exports a checkpoint from a model using the model's associated exporter, typically for
    the purpose of sharing a model that has been fine-tuned or customized within NeMo.

    This function can be used both programmatically and through the NeMo CLI:

    CLI Usage:
    ```bash
    # Export model to HuggingFace format (saves to {checkpoint_path}/hf/)
    nemo llm export path=/path/to/model.nemo target="hf"

    # Export with custom output path
    nemo llm export path=/path/to/model.nemo target="hf" output_path="/path/to/save"

    # Force overwrite existing export
    nemo llm export path=/path/to/model.nemo target="hf" overwrite=true
    ```

    Python Usage:
    ```python
    nemo_ckpt_path = Path("/path/to/model.nemo")
    export_path = export_ckpt(nemo_ckpt_path, "hf")
    ```

    The exporter component of the model reads the model's state from the specified path and
    exports it into the format specified by the 'target' identifier. This is particularly
    useful for adapting models that have been developed or fine-tuned within NeMo to be
    compatible with other environments or frameworks.

    Args:
        path (Path): The path to the model's checkpoint file from which data will be exported.
        target (str): The identifier for the exporter that defines the format of the export
            (e.g., "hf" for HuggingFace format).
        output_path (Optional[Path]): The path where the exported checkpoint will be saved.
            If not specified, defaults to {checkpoint_path}/{target}/.
        overwrite (bool): If set to True, existing files at the output path will be overwritten.
            This is useful for model updates where retaining old checkpoint files is not required.
        load_connector (Callable[[Path, str], ModelConnector]): A function to load the appropriate
            exporter based on the model and target format. Defaults to `load_connector_from_trainer_ckpt`.
        modelopt_export_kwargs (Dict[str, Any]): Additional keyword arguments for ModelOpt export to HuggingFace.

    Returns:
        Path: The path where the checkpoint has been saved after export.

    Raises:
        ValueError: If the model does not implement ConnectorMixin, indicating a lack of
            necessary exporter functionality.
        FileExistsError: If the output path is provided (that is, when not using models cache)
            and it exists and overwrite is not set to True.
    r  r  u"   [green]✓ Checkpoint exported to rc   )rq   r   r   r	  r!   export_ckptr
   rf   )	r9   r  r  r  r  r  r  r  rh   r@   r@   rA   r    s   
<r  generate   i  promptsencoder_promptsinput_datasetparams_dtypeadd_BOSrandom_seed&inference_batch_times_seqlen_thresholdinference_paramsr)   	text_onlyr*   c              
      s  ddl m} |dur9t|tr|n|j}t|}dd | D }dd |D }W d   n1 s3w   Y  n|dur@|}ntd|j| |||	|d\} |
j	t
 fd	d
|D  }||j_||j_|jjdkro|}n)|jjd }|jjd }t|| d | }|| }t|| t|}||| }|j| ||||||
d}|jjdkr|}n&dg| }t|fdd|D t d dd |D }t|t|ksJ |dur?t r?t|dL}t|r|n||D ]:\}}t|tkr
|dd|d< r|n|j|d< nt|tkr|r|n|jd}|t |d  qW d   n	1 s2w   Y  t!"d|  |S )a  
    Generates text using a NeMo LLM model.

    This function takes a checkpoint path and a list of prompts,
    and generates text based on the loaded model and parameters.
    It returns a list of generated text, either as a string or as an InferenceRequest object.

    Python Usage:
    ```python
    strategy = nl.MegatronStrategy(
        tensor_model_parallel_size=2,
        pipeline_model_parallel_size=1,
        context_parallel_size=1,
        sequence_parallel=False,
        setup_optimizers=False,
        store_optimizer_states=False,
    )

    trainer = nl.Trainer(
        accelerator="gpu",
        devices=2,
        num_nodes=1,
        strategy=strategy,
        plugins=nl.MegatronMixedPrecision(
            precision="bf16-mixed",
            params_dtype=torch.bfloat16,
            pipeline_dtype=torch.bfloat16,
            autocast_enabled=False,
            grad_reduce_in_fp32=False,
        ),
    )
    prompts = [
        "Hello, how are you?",
        "How many r's are in the word 'strawberry'?",
        "Which number is bigger? 10.119 or 10.19?",
    ]

    if __name__ == "__main__":
        results = api.generate(
            path=os.path.join(os.environ["NEMO_HOME"], "models", "meta-llama/Meta-Llama-3-8B"),
            prompts=prompts,
            trainer=trainer,
            inference_params=CommonInferenceParams(temperature=0.1, top_k=10, num_tokens_to_generate=512),
            text_only=True,
        )
    ```

    Args:
        path (Union[Path, str]): The path to the model checkpoint.
        prompts (list[str]): The list of prompts to generate text for.
        trainer (nl.Trainer): The trainer object.
        encoder_prompts (Optional[list[str]], optional): The list of encoder prompts. Defaults to None.
        input_dataset (Optional[Union[pl.LightningDataModule, str]], optional): The input data module or jsonl file.
            Test set will be used for generation for data modules. Defaults to None.
        params_dtype (torch.dtype, optional): The data type of the model parameters. Defaults to torch.bfloat16.
        add_BOS (bool, optional): Whether to add the beginning of sequence token. Defaults to False.
        max_batch_size (int, optional): The maximum batch size. Defaults to 4.
        random_seed (Optional[int], optional): The random seed. Defaults to None.
        inference_batch_times_seqlen_threshold (int, optional): If batch-size times sequence-length is smaller than
            this threshold then we will not use pipelining, otherwise we will. Defaults to 1000.
        inference_params (Optional["CommonInferenceParams"], optional): The inference parameters defined in
            Mcore's CommonInferenceParams. Defaults to None.
        text_only (bool, optional): Whether to return only the generated text as a string. Defaults to False.
        output_path (Optional[Union[Path, str]], optional): The path to save the generated text or test dataset
            predictions. Defaults to None.
        enable_flash_decode (bool, optional): Whether to enable flash decode. Defaults to True.

    Returns:
        list[Union["InferenceRequest", str]]: A list of generated text,
            either as a string or as an InferenceRequest object.
    r   )	inferenceNc                 S   s   g | ]}t |qS r@   )jsonloads.0sampler@   r@   rA   
<listcomp>i  s    zgenerate.<locals>.<listcomp>c                 S   s   g | ]}|d  qS )inputr@   r$  r@   r@   rA   r'  j  s    z1Either prompts or input_dataset must be provided.)r9   r/   r  r  r   c                 3   s    | ]
}t  |V  qd S N)r   tokenize)r%  r   )mcore_tokenizerr@   rA   	<genexpr>x  s    zgenerate.<locals>.<genexpr>rK   num_replicasrank)r-   r3   r  r  r  r   r  r  c                    s   g | ]	} r	|j n|qS r@   )generated_text)r%  r)r   r@   rA   r'        )groupc                 S   s   g | ]	}|D ]}|qqS r@   r@   )r%  sublistresultr@   r@   rA   r'    r1  wr  label
prediction)r(  r7  
zPredictions written to )#nemo.collections.llmr!  rq   r   	test_pathopen	readlinesr   setup_model_and_tokenizernum_tokens_to_generatemaxinference_wrapper_configr   inference_contextmax_sequence_lengthstrategyr   distributed_sampler_kwargsr   minr  r   r	   get_data_parallel_groupr(   zipr   dictpopr/  writer"  dumpsr'   r   )r9   r/   r  r  r  r  r  r   r  r  r  r   r  r   r!  
input_pathfdatasetinputsinference_wrapped_modelmax_seq_lengthinputs_on_this_dp_rankdp_sizedp_rank
chunk_size	start_idxend_idxresults_on_this_dp_rankgathered_resultsr&  predr@   )r+  r   rA   r    s|   X


c                 C   s   |dkrt | d|j d S |dkrt |d| j d S z!ddlm} t||r5t | d| t |d| W d S td|  tyF   tdw )Nr.   r3   r-   r   )TokenizerSpecz2Expected TokenizerSpec or 'data' or 'model', got: zTokenizerSpec is not available)_set_with_ior3   1nemo.collections.common.tokenizers.tokenizer_specr[  rq   r   r   )r-   r.   r3   r[  r@   r@   rA   _use_tokenizer  s   
r^  c                 C   s2  t | |pt }|rt|tr|jrtd d|j_|j|t	|ddt	t
dd d}	|d ur6|||  |r=||  |rEt| || |rMt| d| t	| dd rptdd |jD spt|tri|j| n|jt  d }
t|jD ]\}}t|tr|
d u sJ |j|}
qw|
d ur|j|
 |	S )	Nz8Disabling try_restore_best_ckpt restoration for adaptersFresume_if_existsrt   )r_  task_configr4   c                 s   s    | ]}t |tV  qd S r)  )rq   r&   )r%  cbr@   r@   rA   r,    s    z_setup.<locals>.<genexpr>)r    r   rq   r$   ckptr'   r   try_restore_best_ckptsetuprr   rB   connectr^  r\  any	callbacksr&   append	enumerater%   rI  )r-   r.   r/   r0   r1   r2   r3   r4   _logr?   jit_cbira  r@   r@   rA   r;     s@   







r;   c                 C   s@   t | || t| drt|drt | j|t|j d S d S d S )Nrt   )setattrhasattrrt   r   )objattrvaluer@   r@   rA   r\    s   r\  c                 C   s  t | dr<t| jdddksJ t| jdddksJ | jjdks#J | jjdks+J | jjdks3J | jjdks;J nt|jt	j
rGJ d|jdksNJ t|jt	j
ro|jdks\J |jdkscJ |j|j dksoJ dt|jt	j
rV|jjdksJ |jjdksJ |jjdksJ |j|j |jj|jj |jj  dksJ d|j|j|j|j |jj|jj |jj    dksJ d	|jjdkr|jjd
krtd d|j_|jjdkr|jjd usJ dn|jjd urtd d |j_|jjd ur
td d |j_|jjdkr/t | dr/| jjd ur/| jj|jjd  dks/J d|jjdkrXt | drZ| jjd usGJ d| jj|jj dks\J dd S d S d S d S )Nrs   
seq_lengthrK   r   max_position_embeddingszExpected model.config to existzGGlobal batch size must be divisible by micro batch size in data module.z[Number of GPUs must be divisible by the product of all parallelism sizes for data parallel.z]Global batch size must be divisible by the product of micro batch size and data parallel sizeTzKDisabling sequence parallelism because tensor model parallelism is disabledFzCpipeline_dtype must be set if pipeline model parallelism is enabledzUDisabling virtual pipeline parallelism because pipeline model parallelism is disabledzMSetting pipeline dtype to None because pipeline model parallelism is disabledr   z[Sequence length must be divisible by 2 * context parallel size if context parallel is used.z<num_experts must be non None to use expert model parallelismzENumber of experts should be a multiple of expert model parallel_size.)rn  rr   rs   
num_layershidden_sizenum_attention_headsffn_hidden_sizerq   rC  nlMegatronStrategyre   rd   rr  r]   r^   r   r   rQ   rW   warningswarnpipeline_dtype$virtual_pipeline_model_parallel_sizer   num_moe_expertsr6   r@   r@   rA   rD     s   





9rD   c                 C   s   ddl m} t| } |du r|d|p| j d}t|  dd d}|D ]P}| r;|d	|j d
}t|| q%|j	dv rK|d|j d q%|j	dv r[|d|j d q%|j	dv rk|d|j d q%|d|j d q%|S )z:Build a Rich Tree representation of a directory structure.r   )TreeNz[bold blue]z[/bold blue]c                 S   s   |    | jfS r)  )is_dirrJ   )xr@   r@   rA   <lambda>g  s    z'_build_directory_tree.<locals>.<lambda>)keyz[bold cyan]z/[/bold cyan])z.jsonz.jsonlz[yellow]z	[/yellow])z.ptz.binz.ckptz.nemoz	[magenta]z
[/magenta])z.pyz.shz[green]rc   z[white]z[/white])
	rich.treer  r   rJ   sortediterdirr  addr  suffix)r9   treer  r  itemsitembranchr@   r@   rA   r  ^  s"   


r  c                 C   s    t | trtjt| dd} | S r  )rq   AnyPathr!   rp   r#   )r-   r@   r@   rA   r7   {  s   
r7   )NNNNN)NNN)NNNNr-   )rK   rK   rK   rK   rL   NNF)NNNNNN)rK   rK   NNNNNNNFF)Nr   Nr   rK   r   r   r   NTr   r   rK   rK   rK   rK   rK   rK   rK   Nr   r   r   TTTF)NF)NN)ir   r"  multiprocessingrz  copyr   pathlibr   typingr   r   r   r   r   lightning.pytorchpytorchplnemo_runr   r   megatron.corer	   rich.consoler
   torch.distributedr   typing_extensionsr   nemo.lightning	lightningrx  r9  r   r   #nemo.collections.llm.evaluation.apir   r   r   r   nemo.collections.llm.modeloptr   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   nemo.lightning.baser"   nemo.lightning.ckpt_utilsr#    nemo.lightning.pytorch.callbacksr$   r%   r&   
nemo.utilsr'   nemo.utils.get_rankr(   /megatron.core.inference.common_inference_paramsr)   )megatron.core.inference.inference_requestr*   TokenizerTyper   r  cli
entrypointLightningModuleLightningDataModuleConfigrB   rE   rG   rH   intboolrI   ri   rw   r   rH  r   r
  ModelConnectorr  r  bfloat16listr   r  r^  r;   r\  rD   r  r7   r@   r@   r@   rA   <module>   s  , 
C2	8	6	
N	
P	
o	
 TQT
J

	
 "	
2
	

f