yueshen2016andClaude Opus 5 fc4c40fcbe Fix HF export crash when a dynamic-block quantizer has zero amax (#2438)
### What does this PR do?

Type of change: Bug fix

`TensorQuantizer.export_amax()` early-returns `self.amax` unsanitized
for dynamic-block
quantizers, while the static path immediately below it has always
substituted `maxbound` for
zero/NaN entries. The `nvfp4` numerics unit sets `type: dynamic`, so a
recipe that applies it to
an *activation* quantizer — e.g.
`general/ptq/nvfp4_mlp_only-kv_fp8_cast`, which targets
`*mlp*input_quantizer` — feeds a raw `0.0` into
`NVFP4QTensor.get_activation_scaling_factor`,
whose assert aborts the entire export:

```
AssertionError: Failed to export module 'model.language_model.layers.37.mlp.gate_proj'
(type=QuantLinear):  activation scaling factor 0.0 not positive.
```

Calibration leaves `amax` at 0 whenever a layer — or an unrouted MoE
expert — saw only zeros, so
one dead layer costs the whole run at the final export step.

This factors the substitution into `_sanitize_export_amax()` and calls
it from both branches. Two
details beyond de-duplication:

- **Branch-free, so it survives a meta `amax`.** `torch.where` +
`nan_to_num` both have meta
kernels; `bool()` on a meta tensor raises. The layerwise and streaming
export flows carry meta
`amax` — `validate_attr` short-circuits on `is_meta` for exactly that
reason — so only the
  warning is gated on a materialized tensor.
- **No longer mutates calibrated state.** The old in-place `amax[amax ==
0] = ...` wrote through a
view of `self._amax`; `torch.where` returns a fresh tensor, so that
hazard disappears.
- **Warns, with a count.** The fix turns a loud failure into a silent
one, and a zero amax means
calibration never activated that layer — worth surfacing rather than
papering over. The message
reports how many entries were substituted, since per-location dedup
otherwise collapses many
dead experts into one uninformative message. A healthy model emits none.

Scope: only the activation path is data-dependent and reachable this
way. Weight-side `_amax` uses
are left alone, since a weight amax of 0 would require an all-zero
weight matrix.

**Knowingly left as follow-up:**
`export/quant_utils.py::get_scaling_factor` discards the sanitized
`amax` when `num_bits == (2, 1)` and recomputes via
`get_weights_scaling_factor_2_from_quantizer`,
which reads `weight_quantizer._amax` raw — so a dynamic-NVFP4 *input*
quantizer on a module whose
*weight* quantizer is a different format (or disabled) can still trip
`assert torch.all(scaling_factor > 0)`. Format dispatch is
weight-driven, so the reported recipe
does not reach that branch; fixing it properly changes a signature
shared with the weight-side
callers and is out of scope here.

Not a regression. The dynamic early return, the `type: dynamic` numerics
unit, and the recipe that
combines them all ship in released 0.46.0 / 0.46.1.

### Usage

No new or changed API. Exports that previously aborted now complete and
warn:

```python
# Recipe applies dynamic NVFP4 to *mlp*input_quantizer; layer 37 never activated during calibration.
mtq.quantize(model, quant_cfg, forward_loop)
export_hf_checkpoint(model, export_dir=out)   # before: AssertionError; now: exports + UserWarning
```

### Testing

- New `test_amax_export_unusable_amax`, parametrized over zero and NaN,
covering the
dynamic-NVFP4 and static per-tensor configs; asserts the exported scale
is positive and that
export leaves the calibrated `amax` untouched. Plus
`test_amax_export_meta_amax`, pinning that
a meta `amax` survives export rather than raising. Both run on CPU and
CUDA via the shared tester.
- `tests/unit/torch/quantization/test_tensor_quantizer_cpu.py` — 40
passed.
`tests/gpu/torch/quantization/test_tensor_quantizer_cuda.py` — 40 passed
(GB300).
- End-to-end repro on GB300, small Llama with one MLP fed all-zero
activations under
`general/ptq/nvfp4_mlp_only-kv_fp8_cast`: dead layer `export_amax()`
`0.0` → `6.0`, live layer
unchanged at `3.921875`, and `export_hf_checkpoint` goes from the
`AssertionError` above to
  writing `model.safetensors`.
- Full `examples/hf_ptq/hf_ptq.py` with the reported recipe and flags on
a healthy model
(Qwen3-0.6B): exits 0 and writes the checkpoint, confirming the normal
path is unaffected.
- `pre-commit run` clean on all changed files.

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

- Is this change backward compatible?: ✅
- If you copied code from any other sources or added a new PIP
dependency, did you follow guidance in `CONTRIBUTING.md`: N/A
- Did you write any new necessary tests?: ✅
- Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?:
✅
- Did you get Claude approval on this PR?: ✅ — `/claude review` run; its
one IMPORTANT finding (meta-tensor regression) and both SUGGESTIONs
addressed or answered in 251f2e3d

### Additional Information

Fixes NVBug 6768300, reported against 0.47.0rc1 on GB200. The reporter
also notes it passed on
0.47.0rc0; that is not explained by code — `git diff
0.47.0rc0..0.47.0rc1` touches
`export/quant_utils.py` only in `get_kv_cache_scaling_factor` (new
`clamp_fp8_scales` argument
whose default preserves the old behaviour) and the INT4-AWQ packing
path, neither of which is on
the dense-HF NVFP4 activation-scale path. Whether `amax` lands on
exactly 0 is
calibration/model-state dependent, which is what makes it look
version-flaky.

Worth flagging separately: in the reported log the **pre-PTQ** sample
output is already
gibberish, so that BF16 checkpoint looks broken independently of
quantization. This change stops
the crash, but such a run will now export a valid-but-garbage checkpoint
— the new warning is the
signal to investigate.

Suggest the `cherry-pick-0.47.0` label so this lands in the ongoing
release.

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


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Bug Fixes**
* Fixed Hugging Face checkpoint export when dynamic-block quantizers
have zero or invalid calibration scales.
* Exports now use a positive fallback scale and issue a warning instead
of failing when applicable.
* Export operations no longer modify the original calibrated quantizer
state.
* Meta-device exports remain non-erroring and preserve device placement.
* **Tests**
* Added coverage for zero- and invalid-scale exports across dynamic and
static quantization modes.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Signed-off-by: Yue <yueshen@nvidia.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 17:47:34 +00:00
…
…
…

Banner image

NVIDIA Model Optimizer

Documentation version license

Documentation | Roadmap | Announcement Blogs


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

ModelOpt's agent skills can be installed from this repository and used in any workspace.

Claude Code

claude plugin marketplace add https://github.com/NVIDIA/Model-Optimizer.git
claude plugin install modelopt@modelopt

Codex

codex plugin marketplace add https://github.com/NVIDIA/Model-Optimizer.git

Then open /plugins, select the modelopt marketplace, and install modelopt. Contributors can also use the skills directly from a checkout. 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%