Chenjie LuoandClaude Opus 4.8 23be82655b Add nvfp4_act_headroom activation calibration for NVFP4 (#2028)
### What does this PR do?

Type of change: new feature

Adds `nvfp4_act_headroom`, a calibration algorithm for NVFP4
**activation** global scales.

NVFP4 scales a tensor in two levels: an FP8-E4M3 scale per 16-element
block, plus one per-tensor global scale. Plain `max` calibration sets
that global scale from the largest per-block amax seen during
calibration, which leaves no room above it — any activation larger than
the calibration max saturates.

`nvfp4_act_headroom` instead anchors the global scale to a low
percentile of the per-block amax distribution:

```
amax = max(rho * anchor, floor)
```

`anchor` is the per-block amax at `anchor_percentile`; `upper` is the
per-block amax at `upper_percentile` and is the top of the range the
scale commits to representing. Multiplying the low anchor by `rho`
places the calibrated blocks in the lower part of the FP8 scale range
and leaves the rest as headroom.

`upper_percentile` defaults to 99.99 rather than the literal maximum on
purpose. Flooring at the literal max means one freak block drags the
global scale up until every other block's FP8 block scale falls below
subnormal: on a tensor with a single block seven orders of magnitude
above the rest, that flushes 99.998% of elements to zero, versus 6.7%
when the rare blocks are clipped instead. On a benign wide-range tensor
the two choices differ by 0.4% relative MSE. Set `upper_percentile=100`
to floor at the literal observed max, which guarantees no calibration
data is clipped, at that exposure. The calibrator warns when the
per-block range is too wide for `rho` to clear any headroom.

The algorithm applies only to NVFP4 dynamic-block **input** quantizers;
weight quantizers and everything else keep plain `max`.

Files:

- `calib/nvfp4_act_headroom.py` — `NVFP4ActHeadroomCalibrator` (log2
histogram of per-block amaxes, bounded memory)
- `config.py` — `NVFP4ActHeadroomCalibConfig` (`anchor_percentile`
default 1, `rho` default 16384)
- `model_calib.py` — `nvfp4_act_headroom_calibrate`
- `mode.py` — mode registration
- `modelopt_recipes/general/ptq/nvfp4_act_headroom-kv_fp8_cast.yaml` —
mirrors `nvfp4_default-kv_fp8_cast` (dynamic NVFP4 W4A4 + FP8 KV-cache
cast, same module coverage) with only the calibration algorithm swapped:

```diff
-  algorithm: max
+  algorithm:
+    method: nvfp4_act_headroom
+    anchor_percentile: 1
```

### Why a dedicated collector rather than reusing `HistogramCalibrator`

`HistogramCalibrator` histograms the tensor values themselves into
linear, dynamically re-ranged bins, and its percentile mode returns an
amax that *clips* a high-tail fraction. This algorithm needs a different
statistic (per-block amaxes, a derived quantity), different bin spacing
(log2, because block amaxes span many decades and the anchor is read
from the **low** tail, where linear bins have almost no resolution), and
a different reduction (a low-percentile anchor scaled up, not an
upper-tail clip). Reusing it would mean changing its collection
semantics for every existing caller; composing it would still leave the
log-spacing and the derived statistic unaddressed. The collector here is
a fixed 512-bin int64 histogram per quantizer, so the memory argument
for a histogram (rather than retaining values) is preserved.

### Usage

```bash
python examples/hf_ptq/hf_ptq.py --pyt_ckpt_path <model> \
    --recipe general/ptq/nvfp4_act_headroom-kv_fp8_cast --dataset <calib.jsonl>
```

Or directly:

```python
import modelopt.torch.quantization as mtq

NVFP4 = {"num_bits": (2, 1), "block_sizes": {-1: 16, "type": "dynamic", "scale_bits": (4, 3)}}
config = {
    "quant_cfg": [
        {"quantizer_name": "*", "enable": False},
        {"quantizer_name": "*weight_quantizer", "cfg": NVFP4},
        {"quantizer_name": "*input_quantizer", "cfg": NVFP4},
    ],
    "algorithm": {"method": "nvfp4_act_headroom", "anchor_percentile": 1, "rho": 16384},
}
model = mtq.quantize(model, config, forward_loop)
```

### Testing

**Unit tests** —
`tests/unit/torch/quantization/test_nvfp4_act_headroom.py`, 26 tests
covering the anchor and range terms, monotonicity in
`anchor_percentile`, headroom above plain max, the too-wide-range
fallback and its warning, the rare-outlier case (the default clips it;
`upper_percentile=100` chases it), the `upper_percentile=100`
no-clipping guarantee across six distributions, input validation (`rho`
/ percentile bounds, NaN/Inf, all-zero, a last dim that is not a
multiple of the block size), quantizer selection, calibrator restoration
after calibration, `shared_states` / `sync_expert_weight_amax`
forwarding, and W4A4 end-to-end confirming weights fall back to plain
max while only activations get the headroom scale.

Full `tests/unit/torch/quantization/` and `tests/unit/recipe/` suites
pass with no regressions (the remaining failures in this environment are
a pre-existing broken-`torchvision` import and
`test_data_parallel_auto_quantize`, both of which fail identically on
`main`).

**End-to-end on a real model** — ran the shipped recipe on a 30B hybrid
Mamba/attention MoE (1024 calibration samples @ seq 4096) and verified
the export is a standard NVFP4 checkpoint: 6268 activation quantizers
calibrated; 19G vs the 62G BF16 source; 6260 `input_scale`, 6267
`weight_scale` / `weight_scale_2`; `quant_algo: NVFP4`,
`kv_cache_quant_algo: FP8`; 53 excluded modules; no module carrying an
`input_scale` without a `weight_scale`. 32 of 6268 quantizers (0.5%) had
a per-block range too wide for `rho` to clear and warned.

### Before your PR is "*Ready for review*"

- Is this change backward compatible?: ✅ — purely additive: a new opt-in
algorithm, config class, and recipe. No existing behavior changes.
- If you copied code from any other sources or added a new PIP
dependency, did you follow guidance in `CONTRIBUTING.md`: N/A — no
copied code, no new dependencies.
- Did you write any new necessary tests?: ✅ — 12 new unit tests.
- Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?:
✅ — entry under 0.47 → New Features → Quantization.
- Did you get Claude approval on this PR?: ❌ — not yet run.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Chenjie Luo <chenjiel@nvidia.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 17:22:23 +00:00
…
…
…

Banner image

NVIDIA Model Optimizer

Documentation version license

Documentation | Roadmap


NVIDIA Model Optimizer (referred to as Model Optimizer, or ModelOpt) is a library comprising state-of-the-art model optimization techniques including quantization, pruning, Neural Architecture Search (NAS), distillation, speculative decoding and sparsity to accelerate models.

[Input] Model Optimizer currently supports inputs of a Hugging Face, PyTorch or ONNX model.

[Optimize] Model Optimizer provides Python APIs for users to easily compose the above model optimization techniques and export an optimized quantized checkpoint. Model Optimizer is also integrated with NVIDIA Megatron-Bridge, Megatron-LM and Hugging Face Accelerate for training required inference optimization techniques.

[Export for deployment] Seamlessly integrated within the NVIDIA AI software ecosystem, the quantized checkpoint generated from Model Optimizer is ready for deployment in downstream inference frameworks like SGLang, TensorRT-LLM, TensorRT, or vLLM. The unified Hugging Face export API now supports both transformers and diffusers models.

Latest News

Previous News

Install

To install stable release packages for Model Optimizer with pip from PyPI:

pip install -U nvidia-modelopt[all]

Model Optimizer will download and install additional third-party open source software projects. Review the license terms of these open source projects before use.

To install from source in editable mode with all development dependencies or to use the latest features, run:

# Clone the Model Optimizer repository
git clone git@github.com:NVIDIA/Model-Optimizer.git
cd Model-Optimizer

pip install -e .[dev]

You can also directly use NVIDIA container images, which have Model Optimizer pre-installed:

  • nvcr.io/nvidia/pytorch:<version>-py3
  • nvcr.io/nvidia/nemo:<version>
  • nvcr.io/nvidia/tensorrt-llm/release:<version>

Before pulling and using the container images, please review their respective license terms. Make sure to upgrade Model Optimizer to the latest version as described above. Visit our installation guide for more fine-grained control on installed dependencies or for alternative docker images and environment variables to setup.

Techniques

Technique Description Examples Docs
Post Training Quantization Compress model size by 2x-4x, speeding up inference while preserving model quality! [HF LLMs / VLMs] [Megatron-Bridge LLMs / VLMs] [Diffusers] [ONNX] [Windows] [docs]
Quantization Aware Training / Distillation Refine accuracy of quantized models even further with a few training steps! [Hugging Face] [Megatron-Bridge] [docs]
Pruning Reduce your model parameters or memory footprint and accelerate inference by removing unnecessary weights! [General] [Megatron-Bridge]
Distillation Reduce deployment model size by teaching small models to behave like larger models! [Hugging Face] [Megatron-Bridge] [Megatron-LM] [docs]
Speculative Decoding Train draft modules to predict extra tokens during inference! [Hugging Face] [Megatron-LM] [docs]
Sparsity Efficiently compress your model by storing only its non-zero parameter values and their locations [Hugging Face] [docs]

Pre-Quantized Checkpoints

Resources

Model Support Matrix

Model Type Support Matrix
LLM / VLM Quantization View Support Matrix
Diffusers Quantization View Support Matrix
ONNX Quantization View Support Matrix
Windows Quantization View Support Matrix
Quantization Aware Training View Support Matrix
Pruning View Support Matrix
Distillation View Support Matrix
Speculative Decoding View Support Matrix

Deprecation Policy

Model Optimizer follows a structured approach to managing deprecated features:

  • Communication: Deprecation notices are documented in the Changelog. Deprecated items include source code statements indicating deprecation timing, with runtime warnings issued upon use.
  • Migration Period: Since Model Optimizer is still pre-1.0, we provide a 1-release (~1-month) migration period after deprecation. During this window, deprecated features continue functioning while issuing warnings.
  • Scope: The policy addresses both complete deprecations (entire APIs removed) and partial ones (specific parameters removed while methods remain).
  • Removal: Following the migration period, deprecated elements are removed in alignment with semantic versioning standards, potentially including breaking changes in minor version updates while Model Optimizer remains in 0.x.

Citation

If you use NVIDIA Model Optimizer in your research, please cite it as follows:

@misc{nvidia-modelopt,
  author       = {{NVIDIA Corporation}},
  title        = {{NVIDIA Model Optimizer}},
  howpublished = {\url{https://github.com/NVIDIA/Model-Optimizer}},
  year         = {2024--2026},
  note         = {GitHub repository}
}

Contributing

Model Optimizer is now open source! We welcome any feedback, feature requests and PRs. Please read our Contributing guidelines for details on how to contribute to this project.

AI Agents

For AI-assisted development setup, see the agent tooling notes.

Top Contributors

Contributors

Happy optimizing!

S
Description
GitHub Trending: NVIDIA/Model-Optimizer
Readme Multiple Licenses
1.2 GiB
Languages
Python 97.3%
Shell 1.3%
Cuda 0.8%
Jinja 0.3%
C++ 0.2%