Quantization#
This guide covers model quantization in Megatron Bridge using NVIDIA ModelOpt, including post-training quantization (PTQ) and quantization-aware training (QAT).
Note: The scripts referenced in this guide are minimal, hard-coded reference examples. For more comprehensive, production-quality quantization, export, and Quantization Aware Distillation (QAD) scripts, see the NVIDIA Model Optimizer repository: examples/megatron_bridge/.
Table of Contents#
Overview#
Quantization is an effective model optimization technique that compresses models by reducing precision from high-precision formats (FP16/BF16) to lower-precision formats (NVFP4, FP8, INT8, INT4). Quantization with Model Optimizer can compress model size by 2x-4x, speeding up inference while preserving model quality.
In Megatron Bridge, quantization is enabled by NVIDIA Model Optimizer (ModelOpt) — a library to quantize and compress deep learning models for optimized inference on GPUs. Model Optimizer enables highly performant quantization formats including FP8, INT8, INT4, and NVFP4, and supports advanced algorithms such as SmoothQuant and AWQ with easy-to-use Python APIs.
Quantization Methods#
Megatron Bridge supports two quantization approaches:
Post-Training Quantization (PTQ)#
PTQ reduces model precision after training to improve inference efficiency without requiring retraining. This is the fastest approach and works well for most models.
Process:
Load a pretrained model checkpoint
Calibrate the model using a small dataset (typically 128-512 samples) to obtain scaling factors
Produce a quantized checkpoint
Quantization-Aware Training (QAT)#
Quantization Aware Training (QAT) helps to improve the model accuracy beyond post training quantization (PTQ). QAT can further preserve model accuracy at low precisions (e.g., INT4, or FP4 in NVIDIA Blackwell platform).
Process:
Train/fine-tune the model in the original precision without quantization
Quantize the model from step 1 with
mtq.quantize()Train/fine-tune the quantized model with a small learning rate (e.g., 1e-5 for Adam optimizer)
Note: Step 3 is the actual ‘Quantization Aware Training’ step. The optimal hyperparameter setting for QAT can vary depending on the model and training dataset.
Note: QAT without the original precision training/fine-tuning (i.e., skipping Step 1) gives worse accuracy. Therefore, un-quantized original precision training/fine-tuning followed by QAT is recommended for best accuracy.
Post-Training Quantization (PTQ)#
PTQ quantizes a pretrained model by running calibration with a small dataset to compute scaling factors. The complete workflow includes: quantize → resume and generate → export.
Quantize#
Use the examples/quantization/quantize.py script for LLM PTQ:
uv run python -m torch.distributed.run --nproc_per_node 2 examples/quantization/quantize.py \
--hf-model-id Qwen/Qwen3-0.6B \
--export-quant-cfg fp8 \
--tp 2 \
--megatron-save-path ./qwen3_0_6b_fp8
Use the examples/quantization/quantize_vlm.py script for VLM PTQ:
uv run python -m torch.distributed.run --nproc_per_node 8 examples/quantization/quantize_vlm.py \
--hf-model-id Qwen/Qwen3-VL-30B-A3B-Instruct \
--export-quant-cfg fp8 \
--megatron-save-path ./Qwen3-VL-30B-A3B-Instruct_fp8 \
--tp 4 \
--etp 4 \
--pp 2 \
--calib-size 256
Key Arguments:
--hf-model-id- HuggingFace model ID or local path--export-quant-cfg- Quantization format (fp8,nvfp4, etc.)--megatron-save-path- Output checkpoint path--tp- Tensor parallelism size--pp- Pipeline parallelism size--ep- Expert parallelism for MoE models--etp- Expert tensor parallelism for MoE models--calib-size- Calibration samples for quantization (default: 512)
Resume and Generate#
Resume the quantized checkpoint and test with text generation using examples/quantization/ptq_generate.py for LLM:
uv run python -m torch.distributed.run --nproc_per_node 2 examples/quantization/ptq_generate.py \
--hf-model-id Qwen/Qwen3-0.6B \
--megatron-load-path ./qwen3_0_6b_fp8 \
--tp 2
Resume the quantized checkpoint and test with text generation using examples/quantization/ptq_generate_vlm.py for VLM:
uv run python -m torch.distributed.run --nproc_per_node 8 examples/quantization/ptq_generate_vlm.py \
--hf-model-id Qwen/Qwen3-VL-30B-A3B-Instruct \
--megatron-load-path ./Qwen3-VL-30B-A3B-Instruct_fp8 \
--tp 8 \
--ep 8 \
--image-path ./demo.jpeg \
--prompts "Describe this image."
Key Arguments:
--megatron-load-path- Path to quantized checkpoint--hf-model-id- HuggingFace model ID or local path (for tokenizer)--image-path- Path to the input image file used for visual-language model prompt generation--prompts- Test prompts
Export#
Export the quantized checkpoint to a quantized HuggingFace checkpoint using examples/quantization/export.py:
uv run python -m torch.distributed.run --nproc_per_node 2 examples/quantization/export.py \
--hf-model-id Qwen/Qwen3-0.6B \
--megatron-load-path ./qwen3_0_6b_fp8 \
--export-dir ./qwen3_0_6b_fp8_hf \
--tp 2
The export runs at any tensor, pipeline, expert and expert-tensor parallelism and writes the same checkpoint for all
of them: packed quantized weights with their scales, and the quantization_config in config.json that vLLM, SGLang
and TensorRT-LLM read. Unquantized linear layers are listed in its ignore list, derived from the disabled weight
quantizers. Fused projections are split the way the bridge’s own weight mapping splits them, and each quantized
weight’s scales follow its rows. A quantized KV cache adds k_scale and v_scale to each attention layer (see
KV-cache scales). For unsupported configurations (e.g. KV-cache quantization of
attention without a fused QKV mapping, such as MLA, or a mapping that transposes or slices the columns of a quantized
weight), the script falls back to ModelOpt’s Megatron exporter, which supports TP=1 only.
Key Arguments:
--export-dir- Output directory for the quantized HuggingFace checkpoint--export-extra-modules- Also export EAGLE / Medusa heads, through ModelOpt’s Megatron exporter (TP=1 only)
scripts/conversion/convert.sh export --device gpu writes the same quantized checkpoint, without the fallback (see
the conversion launcher).
From Python, save a quantized model directly:
bridge.save_hf_pretrained_modelopt(megatron_model, "./qwen3_0_6b_fp8_hf")
Programmatic ModelOpt Export#
Use AutoBridge.export_hf_weights_modelopt() when you need to stream ModelOpt deployment weights from an
already-loaded Megatron model instead of writing a full checkpoint through the export script. This is useful for
integrations that consume Hugging Face weight names directly, such as inference-engine refit paths.
Build one export plan after ModelOpt calibration and pass its quantization_config unchanged to the consumer. The
plan retains only stable topology and format metadata, so it can be reused for every weight stream. Mutable quantizer
state is captured as each weight is streamed. Megatron-Bridge supplies canonical Hugging Face weight names; ModelOpt
owns packed values, relative sidecar names, and formats. Unquantized parameters retain their regular Hugging Face
names.
Plan reuse requires unchanged quantizer enablement, formats, and block sizes. Each stream validates these metadata before conversion; amax and scale updates remain supported. If the quantization configuration changes, rebuild the plan and reinitialize the consumer with its new configuration. Export exclusions must be expressed by disabled quantizers in the ModelOpt recipe; this API does not apply a separate ignore list.
from safetensors.torch import save_file
plan = bridge.build_hf_modelopt_export_plan(model)
quantization_config = plan.quantization_config
state_dict = {}
for name, weight in bridge.export_hf_weights_modelopt(
model,
export_plan=plan,
cpu=True,
show_progress=False,
):
state_dict[name] = weight.contiguous()
save_file(state_dict, "modelopt-nvfp4.safetensors")
For large models, consume the iterator directly in the downstream writer or refit path instead of materializing the
full state_dict.
for name, weight in bridge.export_hf_weights_modelopt(
model,
export_plan=plan,
show_progress=False,
):
refit_engine.replace_weight(name, weight)
Plan construction and export-stream iteration perform WORLD and model-parallel collectives. Every distributed rank
must therefore build the plan and fully consume each export stream in the same task order, without rank-local early
termination. The streaming API supports canonical per-expert layouts and grouped expert mappings that expose local
expert specifications. Grouped mappings are resolved to per-expert gate, up, and down tensors before ModelOpt packing
and EP collection. Unsupported custom grouped mappings fail explicitly. GPT-OSS experts, which Hugging Face stores
as one tensor per projection, export only as weight-only MXFP4 (e.g. ModelOpt’s mxfp4_mlp_weight_only recipe), in
the format of OpenAI’s released checkpoints: *_blocks / *_scales tensors and "quant_method": "mxfp4", which keeps
every other layer in BF16. This needs a ModelOpt release that packs weight-only MXFP4 (NVIDIA/Model-Optimizer#3221).
Quantized adapter-wrapped weights are not supported. Fold adapters into the base weights before ModelOpt calibration or QAT. Quantized dimension-permuting mappings are also rejected by the streaming API; unquantized mappings retain their ordinary conversion path. Custom QKV mappings that only select or reorder whole rows are supported for quantized weights; mappings that transpose, slice columns, or combine row values are rejected. Post-mapping key renames of quantized weights are not supported; excluded weights retain their normal renaming behavior. This API requires a ModelOpt release that provides the functional quantized-weight export interface.
KV-cache scales in online export#
The streaming API also supports symmetric FP8 and NVFP4 K/V quantizers on standard
QKV-mapped attention layers. It supports both KV-only models with unquantized weights
and combined weight/KV quantization. Build the plan after calibration and pass its
quantization_config to the inference engine, as in the examples above.
GPT-OSS’s native MXFP4 format cannot carry KV-cache quantization metadata, so combining
that format with KV quantization is rejected.
FP8 requires static per-tensor E4M3 quantization. NVFP4 requires block-16 E2M1 quantization with dynamic E4M3 block scales and a static global scale. Enabled query quantizers must use the FP8 layout. Rotation and pre-quant scaling are rejected even on disabled quantizers; enabled custom quantization backends are also unsupported. The same checks run when a plan is reused.
Each stream emits current q_scale, k_scale, and v_scale tensors under the
attention’s Hugging Face prefix, once per QKV conversion group. An absent, disabled or
constant-amax query quantizer exports a Q scale of one. Calibrated Q scales use the
maximum across TP ranks to cover all query heads; K/V scales must agree across TP.
FP8 scales are not clamped to one in this online
path. The consumer remains responsible for native cache allocation and for refreshing
any captured attention coefficients when scales change.
This requires ModelOpt’s functional KV-cache export API; constant-amax FP8 recipes
also require constant-amax export support. Asymmetric K/V formats, partially selected
attention layers, and attention without a supported QKV mapping are rejected.
save_hf_pretrained_modelopt() writes the same scales as ModelOpt’s checkpoint exporters do: FP8 K/V scales are
raised to at least one, and q_scale is written only for an enabled query quantizer.
Fake-Quantized Hugging Face Export#
AutoBridge.save_hf_pretrained() and save_hf_weights() also save a fake-quantized ModelOpt model, for
example to evaluate a format that inference engines have no kernels for in vLLM’s ModelOpt fake-quant serving.
Weights are saved as they are in the model, so fold the weight quantizers into them first with
modelopt.torch.quantization.fold_weight. The enabled quantizers are written next to the weights under
Hugging Face names:
quantizer_state.pth: their tensors (e.g.model.layers.0.self_attn.q_proj.input_quantizer._amax), in their original precision;quant_recipe.yaml: their settings, one ModelOptget_modelopt_state(properties_only=True)per quantizer, under aformat: modelopt_quantizer_recipe,version: 1header.
Neither file is written when no quantizer is enabled, e.g. a weight-only format after folding. The export fails if
an enabled quantizer has no Hugging Face name or holds tensors other than _amax, or if a disabled quantizer
still rotates or scales its input (e.g. the query rotation of rotated KV-cache quantization). See the
ModelOpt Megatron-Bridge example
for the export and serving commands.
Supported Models For PTQ#
Model |
fp8 |
nvfp4 |
|---|---|---|
Llama-3.2-1B |
✅ |
✅ |
Qwen3-8B |
✅ |
✅ |
Qwen3-30B-A3B |
✅ |
✅ |
Qwen3-VL-8B-Instruct |
✅ |
✅ |
Qwen3-VL-30B-A3B-Instruct |
✅ |
✅ |
Quantization-Aware Training (QAT)#
In QAT, a model quantized using mtq.quantize() can be directly fine-tuned with the original training pipeline. During QAT, the scaling factors inside quantizers are frozen and the model weights are fine-tuned.
Complete QAT Workflow#
Step 1: Create Initial Quantized Checkpoint (PTQ)#
uv run python -m torch.distributed.run --nproc_per_node 8 examples/quantization/quantize.py \
--hf-model-id meta-llama/Meta-Llama-3-8B \
--export-quant-cfg fp8 \
--tp 8 \
--megatron-save-path /models/llama3_8b_fp8_init
Step 2: Configure Training#
Create a YAML configuration file (e.g., conf/my_qat_config.yaml):
model:
tensor_model_parallel_size: 4
gradient_accumulation_fusion: False
train:
train_iters: 20
global_batch_size: 8
eval_iters: 0
scheduler:
lr_warmup_iters: 10
logger:
log_interval: 1
checkpoint:
pretrained_checkpoint: /models/llama3_8b_fp8_init
save_interval: 20
finetune: true
Step 3: Run QAT Training#
Use examples/quantization/pretrain_quantized_llama3_8b.py:
uv run python -m torch.distributed.run --nproc-per-node=4 pretrain_quantized_llama3_8b.py \
--config-file=conf/my_qat_config.yaml \
--hf-path=meta-llama/Meta-Llama-3-8B
Configuration Overrides:
You can also use command-line overrides:
uv run python -m torch.distributed.run --nproc_per_node 4 pretrain_quantized_llama3_8b.py \
model.tensor_model_parallel_size=4 \
model.gradient_accumulation_fusion=False \
checkpoint.pretrained_checkpoint=/models/llama3_8b_fp8_init
Scale Learning (LSQ)#
ModelOpt’s learnable-scale algorithm (quantization algorithm method: lsq) makes the NVFP4 per-block weight scales trainable parameters (_amax_pre / _amax_post), trained alone (scale-only) or together with the weights.
Quantize with a learnable-scale recipe, e.g. ModelOpt’s
general/qad/nvfp4_lsq-mse_init-fp8_kv(static-block NVFP4 requirestensor_model_parallel_size=1).Restore the checkpoint as in the QAT workflow above. Megatron Bridge gives the scales of expert weights the expert-data-parallel reduction group.
Optionally give the scales their own optimizer parameter group:
from megatron.bridge.training.post_training.lsq import LSQOptimizerConfigOverrideProvider
cfg.optimizer_config_override_provider = LSQOptimizerConfigOverrideProvider(
scale_lr=3e-5, # peak LR of the scales; follows the main LR schedule
scale_min_lr=None, # None uses optimizer.min_lr
scale_wd_mult=0.0, # no weight decay on the scales
)
For scale-only training, register the freeze hook; the frozen weights take no gradient buffer or optimizer state:
from megatron.bridge.training.post_training.lsq import freeze_all_but_lsq_scales
cfg.model.register_pre_wrap_hook(freeze_all_but_lsq_scales)
# With a ModelConfig instead of a model provider:
# cfg.model.pre_wrap_hooks.append(freeze_all_but_lsq_scales)
The hook can run before or after the ModelOpt state is restored. Training the scales, with or without the provider and the hook, needs nvidia-modelopt with NVIDIA/Model-Optimizer#3069, which computes the scale gradients of Transformer Engine LayerNormLinear layers and of frozen weights; the provider and the hook raise an error with an older version. The same PR adds them to ModelOpt’s examples/megatron_bridge/distill.py as --lsq_scale_lr and --lsq_scale_only.
Supported Models For QAT#
Model |
Support |
|---|---|
Meta-Llama-3-8B |
✅ |