982d72eafc fix(hf_ptq): use no_grad instead of inference_mode in export_quantized (NVBug 6537702) (#2047)
### What does this PR do?

Type of change: Bug fix

Fixes [NVBug 6537702](https://nvbugspro.nvidia.com/bug/6537702) /
[OMNIML-5658](https://jirasw.nvidia.com/browse/OMNIML-5658) — multi-node
FSDP2 PTQ export fails on all ranks:

```
hf_ptq.py:910 export_quantized -> export_hf_checkpoint
unified_export_hf.py:1446 _export_transformers_checkpoint -> get_model_state_dict
modelopt/torch/opt/_hooks.py:88 _get_model_state_dict_with_dm_check
torch/distributed/checkpoint/state_dict.py:481 _get_model_state_dict
torch/nn/modules/module.py:2160 _save_to_state_dict
    destination[prefix + name] = param if keep_vars else param.detach()
RuntimeError: Cannot set version_counter for inference tensor
```

**Root cause.** `export_quantized` wrapped its whole body in
`torch.inference_mode()`. On the FSDP2 path (`--use_fsdp2`),
`get_model_state_dict(full_state_dict=True)` gathers the full params
*inside* that context, so the gathered tensors are inference tensors.
Inference tensors have no version counter, so the subsequent
`state_dict()` → `param.detach()` raises.

**Fix.** Use `torch.no_grad()` for the export context. It still disables
autograd, but the gathered params stay normal tensors with an intact
version counter, so `detach()` works. FSDP2-only failure — the non-FSDP2
path never hit it because its params already exist outside the context.

The one-line fix is originally by @shengliangx (`b0e4328` on
`shengliangx/distributed-unified`); this PR retargets it to the
post-rename `examples/hf_ptq/` path and adds a changelog entry and a
regression guard.

### Usage

```bash
# 2 nodes x 8 GB200, previously failed at export on every rank
torchrun --nnodes=2 --node_rank=0 --master_addr=$MASTER --master_port=6000 --nproc_per_node=8 \
  hf_ptq.py --model Llama-3.1-8B-Instruct --dataset cnn_dailymail \
  --recipe general/ptq/fp8_default-kv_fp8 --batch_size 8 --calib_size 512 \
  --export_path ./Llama-3.1-8B-Instruct-fp8_default-kv_fp8 --use_fsdp2
```

### Testing

- End-to-end on 2 nodes by @shengliangx on the original branch: dense
Qwen3-8B and Qwen3-30B-A3B (MoE) FSDP2 PTQ fp8 checkpoints export
successfully.
- Added `tests/examples/hf_ptq/test_export_quantized_context.py`, a
CPU-only guard asserting `export_quantized` enters `torch.no_grad()` and
not `torch.inference_mode()`. A functional regression test would need a
2-node FSDP2 job, which CI does not run, so this encodes the invariant
instead.
- `pre-commit run --files` clean on all three changed files.

Reporter (Kenny Kang, GPU SWQA) still needs to confirm on the original
2x8 GB200 Llama-3.1-8B repro.

### 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?: ❌

### Additional Information

Keyword `Committed_ModelOpt_0.46.0` on the bug — should land for 0.46.

🤖 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 multi-node quantized model exports to prevent runtime errors
when gathering and detaching parameters.
  * Improved compatibility with FSDP2 during Hugging Face PTQ exports.

* **Tests**
* Added coverage to verify the export process uses the compatible
gradient context.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Signed-off-by: Zhiyu Cheng <zhiyuc@nvidia.com>
Co-authored-by: Shengliang Xu <shengliangx@nvidia.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-04 21:02:18 -07:00
…
…
2026-07-09 12:54:24 +05:30

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%