Keval MorabiaandClaude Opus 5.5 6f4cb4a82c Fix NaN amax when restoring a quantized Megatron-Core model before its weights load (#3398)
### What does this PR do?

Type of change: Bug fix

Megatron-Bridge's `load_megatron_model` builds the model without
initializing its weights, restores the sharded `modelopt_state` (which
runs `modelopt_post_restore` through the quantizers' extra state), and
only then loads the weights. `_ParallelLinear.modelopt_post_restore`
recalibrates the weight quantizer's `_amax` from `self.weight` to give
it the shape of the current parallelism; the checkpoint's `_amax`
replaces the value when the weights load. With uninitialized memory that
holds NaNs, the recalibration fails `MaxCalibrator.collect` with
`detected nan values in amax`. That memory is zeros on a fresh GPU, so
it showed up on CPU (`convert.sh export --device cpu`) and on later
pipeline stages (PP=2 export of a quantized Qwen3 toy via
Megatron-Bridge's `examples/quantization/export.py` and `convert.sh`).

The recalibration now reads `torch.nan_to_num(self.weight)`. Loaded
weights are unchanged by it.

### Usage

No API change.

### Testing

- `tests/gpu_megatron/torch/quantization/plugins/test_megatron.py`:
`_test_sharded_state_dict` now fills `model_test`'s linear weights with
NaN before the sharded restore, as in Megatron-Bridge's load. Without
the fix, `test_homogeneous_sharded_state_dict[local-False-*]` and
`test_homogeneous_sharded_state_dict_te_spec` fail with the NaN
assertion; with it, every `sharded_state_dict` test passes on 2x RTX
6000 Ada (the 4-GPU MoE cases were skipped).
- Megatron-Bridge `convert.sh export` /
`examples/quantization/export.py` of an NVFP4 Qwen3 toy at PP=2 now
loads and writes the same checkpoint as at 1 GPU; distributed CPU export
loads too.
- Not changed: `_QuantTEGroupedLinear.modelopt_post_restore`
recalibrates experts the same way, but only after a TP/EP change makes
the restored `_amax` shape mismatch; I could not write a test that
reaches it with uninitialized weights, so it is left for a follow-up.

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

Make sure you read and follow [Contributor
guidelines](https://github.com/NVIDIA/Model-Optimizer/blob/main/CONTRIBUTING.md)
and your commits are signed (`git commit -s -S`).

Make sure you read and follow the [Security Best
Practices](https://github.com/NVIDIA/Model-Optimizer/blob/main/SECURITY.md#security-coding-practices-for-contributors)
(e.g. avoiding hardcoded `trust_remote_code=True`, `torch.load(...,
weights_only=False)`, `pickle`, etc.).

- 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?: N/A

### Additional Information

Found while extending Megatron-Bridge's `convert.sh export` to write
quantized checkpoints (OMNIML-5979). Present in 0.48.0.

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


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

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Fixed an issue that could prevent quantized Megatron-Core checkpoints
from loading into models with uninitialized weights when those weights
contained NaN values.
* Checkpoint loading now handles this case on CPU and with pipeline
parallelism, avoiding errors about NaN values during calibration.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Signed-off-by: Keval Morabia <28916987+kevalmorabia97@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 21:31:23 +05:30

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

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
2.8 GiB
Languages
Python 97.7%
Shell 1%
Cuda 0.8%
Jinja 0.2%
C++ 0.2%