# Megatron Bridge This directory contains examples of using Model Optimizer with the [NeMo Megatron-Bridge](https://github.com/NVIDIA-Nemo/Megatron-Bridge) framework for quantization, pruning, and distillation. These workflows can be used on their own or combined.
| **Section** | **Description** | **Link** | | :------------: | :------------: | :------------: | | Pre-Requisites | Development environment setup | \[[Link](#pre-requisites)\] | | Post-Training Quantization | Quantizing a model | \[[Link](#post-training-quantization)\] | | Distillation | Distilling a pruned or quantized model | \[[Link](#distillation)\] | | Pruning | Pruning a model using Minitron algorithm | \[[Link](#pruning)\] | | Sanity-Check Generation | Quick generation check with vLLM | \[[Link](#sanity-check-generation)\] | | Resources | Extra links to relevant resources | \[[Link](#resources)\] |
This README is the getting-started guide, with each workflow shown on small models (mostly Qwen3-8B). > [!TIP] > For complete end-to-end workflows on larger models, see the [tutorials](tutorials/README.md): [Nemotron-3-Nano-30B-A3B](tutorials/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16/README.md) pruning + distillation + quantization, [Qwen3.6-35B-A3B](tutorials/Qwen3.6-35B-A3B/README.md) W4A4 NVFP4 + QAD, and [NVIDIA Nemotron 3.5 Super VL](tutorials/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-BF16/README.md) W4A4 + QAD. ## Pre-Requisites Running these examples requires many additional dependencies to be installed (e.g., Megatron-Bridge, Megatron-core, etc.), hence we strongly recommend directly using the NeMo container (e.g., `nvcr.io/nvidia/nemo:26.10`) which has all the dependencies installed. To get the ModelOpt examples scripts, mount your Model-Optimizer repo to the container as follows: ```bash export MODELOPT_DIR=${PWD}/Model-Optimizer # or set to your local Model-Optimizer repository path if you have cloned it if [ ! -d "${MODELOPT_DIR}" ]; then git clone https://github.com/NVIDIA/Model-Optimizer.git ${MODELOPT_DIR} fi export DOCKER_IMAGE=nvcr.io/nvidia/nemo:26.10 docker run \ --gpus all \ --shm-size=16GB \ --net=host \ --ulimit memlock=-1 \ --rm -it \ -v ${MODELOPT_DIR}:/opt/Model-Optimizer \ -v ${MODELOPT_DIR}/modelopt:/opt/venv/lib/python3.12/site-packages/modelopt \ -v ${MODELOPT_DIR}/modelopt_recipes:/opt/venv/lib/python3.12/site-packages/modelopt_recipes \ -w /opt/Model-Optimizer/examples/megatron_bridge \ ${DOCKER_IMAGE} bash ``` Some features (e.g. [`--vllm_fakequant_export`](#evaluating-a-qad-checkpoint-in-vllm-with-fake-quantization), `--fake_quant_weight_cache` and GLM-5.3-Flash support) need a newer Megatron-Bridge than the one in `nvcr.io/nvidia/nemo:26.10`. Until `nemo:26.12` ships it, check out Megatron-Bridge at the commit ModelOpt's CI tests against, together with its Megatron-LM submodule: ```bash export MBRIDGE_DIR=${PWD}/Megatron-Bridge git clone https://github.com/NVIDIA-NeMo/Megatron-Bridge.git ${MBRIDGE_DIR} git -C ${MBRIDGE_DIR} checkout 24b6adc89f5429e55863abc4cee56173eb5eff1a git -C ${MBRIDGE_DIR} submodule update --init 3rdparty/Megatron-LM ``` and add these mounts to the `docker run` command above: ```bash -v ${MBRIDGE_DIR}/src/megatron/bridge:/opt/Megatron-Bridge/src/megatron/bridge \ -v ${MBRIDGE_DIR}/3rdparty/Megatron-LM/megatron:/opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron \ ``` > [!WARNING] > Use `python -m pip` instead of `pip` to avoid conflicts with the system-wide installed packages in the NeMo containers. You may also refer to this [doc](https://github.com/NVIDIA-NeMo/Megatron-Bridge/blob/main/docker/common/README.md#installing-packages-inside-the-container) on how to correctly install packages in the NeMo containers without breaking existing torch installation. You also need to login with your HuggingFace token to download gated datasets / models. Note that the default dataset for pruning and quantization is [`nemotron-post-training-dataset-v2`](https://huggingface.co/datasets/nvidia/Nemotron-Post-Training-Dataset-v2), which is gated. ```bash hf auth login --token ``` ### Importing a HuggingFace Checkpoint (optional) The scripts below take a HuggingFace checkpoint directly, but if you want a Megatron distributed checkpoint (e.g. to reuse across runs), convert it with Megatron-Bridge's conversion script — use `--tp` / `--pp` / `--ep` to shard a model that does not fit on one GPU (`--ep` for MoE models), or `--device cpu` to convert in a single process without GPUs: ```bash bash /opt/Megatron-Bridge/scripts/conversion/convert.sh import \ --executor local \ --device gpu \ --gpus-per-node 8 \ --hf-model Qwen/Qwen3-8B \ --megatron-path /tmp/Qwen3-8B-megatron ``` ## Post-Training Quantization This section shows how to quantize a HuggingFace model using ModelOpt in the Megatron-Bridge framework. Quantization is a two-step flow: 1. [quantize.py](quantize.py) applies post-training quantization (PTQ) with calibration and saves a **Megatron checkpoint** (with ModelOpt state). Tensor / pipeline / expert parallelism are all supported, and the checkpoint can be reloaded for further training (Quantization Aware Training / Quantization Aware Distillation). 2. [export_quantized_megatron_to_hf.py](export_quantized_megatron_to_hf.py) converts that Megatron checkpoint to a **HuggingFace (unified) checkpoint** that deploys directly with TensorRT-LLM, vLLM, or SGLang. `quantize.py` supports the following formats via `--quant_cfg` (e.g. `fp8`, `nvfp4`, `int8_smoothquant`, `int4_awq`, `w4a8_awq_beta`, ...). You can also pass any full config name exposed by ModelOpt (e.g. `NVFP4_DEFAULT_CFG`) or a YAML `--recipe` (e.g. `general/ptq/nvfp4_default-kv_fp8`, authoritative for quant_cfg + algorithm + KV-cache). KV-cache quantization can be enabled on top via `--kv_cache_quant` (e.g. `fp8`, `nvfp4`). **Step 1 — quantize** Qwen3-8B to NVFP4 on 2 GPUs (Tensor Parallelism = 2) using 1024 samples from default dataset (Mix of [`cnn_dailymail`](https://huggingface.co/datasets/abisee/cnn_dailymail) and [`nemotron-post-training-dataset-v2`](https://huggingface.co/datasets/nvidia/Nemotron-Post-Training-Dataset-v2)) for calibration (sequence length = 4096): ```bash torchrun --nproc_per_node 2 quantize.py \ --hf_model_name_or_path Qwen/Qwen3-8B \ --quant_cfg nvfp4 \ --tp_size 2 \ --calib_batch_size 1 \ --seq_length 4096 \ --export_megatron_path /tmp/Qwen3-8B-NVFP4-megatron ``` > [!NOTE] > Data parallelism is implicit: `DP = world_size / (tp_size * pp_size * cp_size)`. Launching with more GPUs than `tp_size * pp_size * cp_size` shards calibration across the extra data-parallel ranks (e.g. `torchrun --nproc_per_node 8 quantize.py --tp_size 2` runs with DP=4). **Step 2 — export** the Megatron checkpoint to a deployable HuggingFace checkpoint: ```bash torchrun --nproc_per_node 2 export_quantized_megatron_to_hf.py \ --hf_model_name_or_path Qwen/Qwen3-8B \ --megatron_path /tmp/Qwen3-8B-NVFP4-megatron \ --pp_size 2 \ --export_unified_hf_path /tmp/Qwen3-8B-NVFP4-hf ``` > [!NOTE] > The HuggingFace unified exporter can't split weights across GPUs with tensor parallelism. For large models, use `--pp_size` on `export_quantized_megatron_to_hf.py` to shard the export across GPUs with pipeline parallelism instead. > [!TIP] > To recover the accuracy lost during quantization, fine-tune the quantized Megatron checkpoint (from step 1) with [Quantization Aware Distillation (QAD)](#quantization-aware-distillation-qad) before running the step 2 export. To see the full usage for advanced configurations, run `torchrun --nproc_per_node 1 quantize.py --help` (or `export_quantized_megatron_to_hf.py --help`). ### Vision-Language Models (VLMs) For a vision-language model (e.g. Qwen3.5-VL, Gemma3-VL), `quantize.py` automatically quantizes only the **language model** and leaves the vision tower and vision-language projector in full precision, then saves the full VLM back as a Megatron checkpoint. The calibration modality is inferred from `--calib_dataset_name`: - An **image-text** dataset (the default for VLMs, `nemotron_vlm_dataset_v2`) drives the full VLM forward, so the language model is calibrated on vision-conditioned activations. - A **text** dataset runs text-only calibration of the language model (vision tower idle). > [!NOTE] > HuggingFace unified export (`export_quantized_megatron_to_hf.py`) of a quantized VLM covers **Qwen3-VL** and **Qwen3.5-VL**. Other VLMs such as Gemma3-VL are saved in Megatron checkpoint format only. ### Tracking runs with MLflow Set MLflow's own `MLFLOW_TRACKING_URI`, or pass `--mlflow `, to record a run on an MLflow server. Every script here that writes a checkpoint takes the flag — [`prune_minitron.py`](#pruning), `quantize.py`, [`distill.py`](#distillation), `export_quantized_megatron_to_hf.py` and `export_distilled_megatron_to_hf.py` — and they share one experiment-name convention, so a pruning, a quantization, the distillation that refines its checkpoint and the export that deploys it can be found together. (One gap remains: `distill.py --hf_export_path` writes its HuggingFace checkpoint from rank 0, which is not the rank that owns that run, so it carries no pointer.) ```bash torchrun --nproc_per_node 2 quantize.py \ --hf_model_name_or_path Qwen/Qwen3-8B \ --recipe general/ptq/nvfp4_default-kv_fp8 \ --tp_size 2 \ --export_megatron_path /tmp/Qwen3-8B-NVFP4-megatron \ --mlflow https:/// ``` The run opens *before* the model loads, so a bad URI fails in seconds rather than after a full calibration. Only the master rank uploads: the invocation, every argument as a searchable param, the resolved recipe, that rank's log and the quantizer summary — plus `.experiment.json` written into `--export_megatron_path` once the checkpoint is saved, so a checkpoint on disk names the run that produced it. A failed run is still recorded, with its traceback. `--mlflow_experiment` defaults to `$USER/